blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
616
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
112
| license_type
stringclasses 2
values | repo_name
stringlengths 5
115
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 777
values | visit_date
timestamp[us]date 2015-08-06 10:31:46
2023-09-06 10:44:38
| revision_date
timestamp[us]date 1970-01-01 02:38:32
2037-05-03 13:00:00
| committer_date
timestamp[us]date 1970-01-01 02:38:32
2023-09-06 01:08:06
| github_id
int64 4.92k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-04 01:52:49
2023-09-14 21:59:50
⌀ | gha_created_at
timestamp[us]date 2008-05-22 07:58:19
2023-08-21 12:35:19
⌀ | gha_language
stringclasses 149
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 3
10.2M
| extension
stringclasses 188
values | content
stringlengths 3
10.2M
| authors
listlengths 1
1
| author_id
stringlengths 1
132
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6a2271851da9a4bd341bde931f2a28406cfaf4b2 | 741333ced9ea1b326997dc031e5de27529bad04a | /glue_vispy_viewers/extern/vispy/scene/cameras/_base.py | f3829d981ac94a9eacfd344537214be1e3f3a7af | [
"BSD-2-Clause",
"BSD-3-Clause"
]
| permissive | jzuhone/glue-vispy-viewers | f1b7f506d3263c4b0c2f4032d4940b931b2c1ada | d940705f4ba95f8d7a9a74d37fb68c71080b490a | refs/heads/master | 2020-06-20T19:10:02.866527 | 2019-06-24T11:40:39 | 2019-06-24T11:40:39 | 197,217,964 | 0 | 0 | BSD-2-Clause | 2019-07-16T15:14:53 | 2019-07-16T15:14:52 | null | UTF-8 | Python | false | false | 1,263 | py | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
from .base_camera import BaseCamera
from .perspective import PerspectiveCamera
from .panzoom import PanZoomCamera
from .arcball import ArcballCamera
from .turntable import TurntableCamera
from .fly import FlyCamera
def make_camera(cam_type, *args, **kwargs):
""" Factory function for creating new cameras using a string name.
Parameters
----------
cam_type : str
May be one of:
* 'panzoom' : Creates :class:`PanZoomCamera`
* 'turntable' : Creates :class:`TurntableCamera`
* None : Creates :class:`Camera`
Notes
-----
All extra arguments are passed to the __init__ method of the selected
Camera class.
"""
cam_types = {None: BaseCamera}
for camType in (BaseCamera, PanZoomCamera, PerspectiveCamera,
TurntableCamera, FlyCamera, ArcballCamera):
cam_types[camType.__name__[:-6].lower()] = camType
try:
return cam_types[cam_type](*args, **kwargs)
except KeyError:
raise KeyError('Unknown camera type "%s". Options are: %s' %
(cam_type, cam_types.keys()))
| [
"[email protected]"
]
| |
a55df25f9f74de9e0ec69b926948719fa010268d | 6518c74441a68fc99b2b08423b5ea11480806499 | /tests/resources/mlflow-test-plugin/mlflow_test_plugin/dummy_evaluator.py | c88bd21d093219c4d2d59ada023cd3f754142dc2 | [
"Apache-2.0"
]
| permissive | criteo-forks/mlflow | da58e64d09700623810da63999a1aca81b435b90 | 499284d8dc9e9ec79d8d9dbd03c58d162a2b7eaa | refs/heads/master | 2023-04-14T17:59:29.997458 | 2022-01-11T09:50:26 | 2022-01-11T09:50:26 | 191,391,769 | 5 | 4 | Apache-2.0 | 2023-04-07T15:16:20 | 2019-06-11T14:44:00 | Python | UTF-8 | Python | false | false | 3,149 | py | import mlflow
from mlflow.models.evaluation import (
ModelEvaluator,
EvaluationMetrics,
EvaluationArtifact,
EvaluationResult,
)
from mlflow.tracking.artifact_utils import get_artifact_uri
from mlflow.entities import Metric
from sklearn import metrics as sk_metrics
import time
import pandas as pd
import io
class Array2DEvaluationArtifact(EvaluationArtifact):
def save(self, output_artifact_path):
pd.DataFrame(self._content).to_csv(output_artifact_path, index=False)
def _load_content_from_file(self, local_artifact_path):
pdf = pd.read_csv(local_artifact_path)
return pdf.to_numpy()
class DummyEvaluator(ModelEvaluator):
# pylint: disable=unused-argument
def can_evaluate(self, *, model_type, evaluator_config, **kwargs):
return model_type in ["classifier", "regressor"]
def _log_metrics(self, run_id, metrics, dataset_name):
"""
Helper method to log metrics into specified run.
"""
client = mlflow.tracking.MlflowClient()
timestamp = int(time.time() * 1000)
client.log_batch(
run_id,
metrics=[
Metric(key=f"{key}_on_{dataset_name}", value=value, timestamp=timestamp, step=0)
for key, value in metrics.items()
],
)
# pylint: disable=unused-argument
def evaluate(
self, *, model, model_type, dataset, run_id, evaluator_config, **kwargs
) -> EvaluationResult:
client = mlflow.tracking.MlflowClient()
X = dataset.features_data
y = dataset.labels_data
y_pred = model.predict(X)
if model_type == "classifier":
accuracy_score = sk_metrics.accuracy_score(y, y_pred)
metrics = EvaluationMetrics(accuracy_score=accuracy_score)
self._log_metrics(run_id, metrics, dataset.name)
confusion_matrix = sk_metrics.confusion_matrix(y, y_pred)
confusion_matrix_artifact_name = f"confusion_matrix_on_{dataset.name}.csv"
confusion_matrix_artifact = Array2DEvaluationArtifact(
uri=get_artifact_uri(run_id, confusion_matrix_artifact_name),
content=confusion_matrix,
)
confusion_matrix_csv_buff = io.StringIO()
confusion_matrix_artifact.save(confusion_matrix_csv_buff)
client.log_text(
run_id, confusion_matrix_csv_buff.getvalue(), confusion_matrix_artifact_name
)
artifacts = {confusion_matrix_artifact_name: confusion_matrix_artifact}
elif model_type == "regressor":
mean_absolute_error = sk_metrics.mean_absolute_error(y, y_pred)
mean_squared_error = sk_metrics.mean_squared_error(y, y_pred)
metrics = EvaluationMetrics(
mean_absolute_error=mean_absolute_error, mean_squared_error=mean_squared_error
)
self._log_metrics(run_id, metrics, dataset.name)
artifacts = {}
else:
raise ValueError(f"Unsupported model type {model_type}")
return EvaluationResult(metrics=metrics, artifacts=artifacts)
| [
"[email protected]"
]
| |
dee4ecc799e94344f16d8476f0dde02257339b4d | dba0f66eef2f173b8cc148d0c51fc338c7c9a70e | /leo/plugins/cursesGui2.py | 853f215e3ffe52490ff065d808f182601fff553f | [
"BSD-3-Clause",
"MIT"
]
| permissive | iggu/leo-editor | 6adcbf1c7727f00115a62ffb68d31c22624e4404 | a8cade8563afdc6b76638e152b91679209a5bf94 | refs/heads/master | 2022-03-16T05:44:42.864262 | 2022-02-25T13:30:51 | 2022-02-25T13:30:51 | 232,984,997 | 0 | 0 | NOASSERTION | 2021-05-05T03:32:44 | 2020-01-10T06:53:10 | null | UTF-8 | Python | false | false | 161,011 | py | # -*- coding: utf-8 -*-
#@+leo-ver=5-thin
#@+node:ekr.20170419092835.1: * @file ../plugins/cursesGui2.py
#@@first
# Disable all mypy checks.
# type:ignore
#@+<< cursesGui2 docstring >>
#@+node:ekr.20170608073034.1: ** << cursesGui2 docstring >>
"""
A curses gui for Leo using npyscreen.
The ``--gui=curses`` command-line option enables this plugin.
**Warnings**
- Leo will crash on startup if the console is not big enough.
- This is beta-level code. Be prepared to recover from data loss. Testing
on files under git control gives you diffs and easy reverts.
- There are many limitations: see http://leoeditor.com/console-gui.html
Please report any problem here:
https://github.com/leo-editor/leo-editor/issues/488
Devs, please read:
http://leoeditor.com/console-gui.html#developing-the-cursesgui2-plugin
"""
#@-<< cursesGui2 docstring >>
#@+<< cursesGui2 imports >>
#@+node:ekr.20170419172102.1: ** << cursesGui2 imports >>
import copy
import logging
import logging.handlers
import re
import sys
from typing import Any, List
# Third-party.
try:
import curses
except ImportError:
print('cursesGui2.py: curses required.')
raise
from leo.external import npyscreen
import leo.external.npyscreen.utilNotify as utilNotify
from leo.external.npyscreen.wgwidget import( # type:ignore
EXITED_DOWN, EXITED_ESCAPE, EXITED_MOUSE, EXITED_UP)
try:
from tkinter import Tk
except ImportError:
print('cursesGui2.py: Tk module required for clipboard handling.')
raise
#
# Leo imports
from leo.core import leoGlobals as g
from leo.core import leoFrame
from leo.core import leoGui
from leo.core import leoMenu
from leo.core import leoNodes
#@-<< cursesGui2 imports >>
# pylint: disable=arguments-differ,logging-not-lazy
# pylint: disable=not-an-iterable,unsubscriptable-object,unsupported-delete-operation
native = True
# True: use native Leo data structures, replacing the
# the values property by a singleton LeoValues object.
#@+<< forward reference classes >>
#@+node:ekr.20170511053555.1: ** << forward reference classes >>
# These classes aren't necessarily base classes, but
# they must be defined before classes that refer to them.
#@+others
#@+node:ekr.20170602094648.1: *3* class LeoBodyTextfield (npyscreen.Textfield)
class LeoBodyTextfield(npyscreen.Textfield):
"""
A class to allow an overridden h_addch for body text.
MultiLines are *not* Textfields, the *contain* Textfields.
"""
def __init__(self, *args, **kwargs):
self.leo_parent = None # Injected later.
super().__init__(*args, **kwargs)
self.set_handlers()
#@+others
#@+node:ekr.20170604182251.1: *4* LeoBodyTextfield handlers
# All h_exit_* methods call self.leo_parent.set_box_name.
# In addition, h_exit_down inserts a blank(!!) for '\n'.
#@+node:ekr.20170602095236.1: *5* LeoBodyTextfield.h_addch
def h_addch(self, ch_i):
"""
Update a single line of the body text, carefully recomputing c.p.b.
Also, update v.insertSpot, v.selectionLength, and v.selectionStart.
"""
trace = False and not g.unitTesting
if not self.editable:
if trace:
g.trace('LeoBodyTextfiedl: not editable')
return
parent_w = self.leo_parent
assert isinstance(parent_w, LeoBody), repr(parent_w)
c = parent_w.leo_c
p = c.p
if trace:
g.trace('LeoBodyTextfield. row: %s len(p.b): %4s ch_i: %s' % (
parent_w.cursor_line, len(p.b), ch_i))
try:
# Careful: chr can fail.
ch = g.toUnicode(chr(ch_i))
except Exception:
if trace:
g.es_exception()
return
# Update this line...
i = self.cursor_position
s = self.value
self.value = s[:i] + ch + s[i:]
self.cursor_position += len(ch)
self.update()
# Update the parent and Leo's data structures.
parent_w.update_body(self.cursor_position, self.value)
#@+node:ekr.20170603131317.1: *5* LeoBodyTextfield.h_cursor_left
def h_cursor_left(self, ch_i):
self.cursor_position -= 1
# -1 Means something.
#@+node:ekr.20170603131253.1: *5* LeoBodyTextfield.h_delete_left
def h_delete_left(self, ch_i):
# pylint: disable=no-member
i = self.cursor_position
if self.editable and i > 0:
self.value = self.value[: i - 1] + self.value[i:]
self.cursor_position -= 1
self.begin_at -= 1
#@+node:ekr.20170602110807.2: *5* LeoBodyTextfield.h_exit_down
def h_exit_down(self, ch_i):
"""
From InputHandler.h_exit_down
Terminate editing for *this* line, but not overall editing.
"""
if ch_i in (curses.ascii.CR, curses.ascii.NL):
# A kludge, but much better than adding a blank.
self.h_addch(ord('\n'))
self.cursor_position = 0
if not self._test_safe_to_exit():
return False
# Don't end overall editing.
# self.leo_parent.set_box_name('Body Pane')
self.editing = False
self.how_exited = EXITED_DOWN
return None
#@+node:ekr.20170602110807.3: *5* LeoBodyTextfield.h_exit_escape
def h_exit_escape(self, ch_i):
"""From InputHandler.h_exit_escape"""
# Leo-specific exit code.
self.leo_parent.set_box_name('Body Pane')
# Boilerplate exit code...
if not self._test_safe_to_exit():
return False
self.editing = False
self.how_exited = EXITED_ESCAPE
return None
#@+node:ekr.20170602110807.4: *5* LeoBodyTextfield.h_exit_mouse
def h_exit_mouse(self, ch_i):
"""From InputHandler.h_exit_mouse"""
# pylint: disable=no-member
parent_w = self.leo_parent
parent_w.set_box_name('Body Pane')
mouse_event = self.parent.safe_get_mouse_event()
if mouse_event and self.intersted_in_mouse_event(mouse_event):
self.handle_mouse_event(mouse_event)
else:
if mouse_event and self._test_safe_to_exit():
curses.ungetmouse(*mouse_event)
ch = self.parent.curses_pad.getch()
assert ch == curses.KEY_MOUSE
self.editing = False
self.how_exited = EXITED_MOUSE
#@+node:ekr.20170602110807.5: *5* LeoBodyTextfield.h_exit_up
def h_exit_up(self, ch_i):
"""LeoBodyTextfield.h_exit_up."""
# Don't end overall editing.
# self.leo_parent.set_box_name('Body Pane')
self.editing = False
self.how_exited = EXITED_UP
#@+node:ekr.20170604180351.1: *5* LeoBodyTextfield.set_handlers
def set_handlers(self):
# pylint: disable=no-member
self.handlers = {
# From InputHandler...
curses.ascii.NL: self.h_exit_down,
curses.ascii.CR: self.h_exit_down,
curses.KEY_DOWN: self.h_exit_down,
curses.KEY_UP: self.h_exit_up, # 2017/06/06.
curses.ascii.ESC: self.h_exit_escape,
curses.KEY_MOUSE: self.h_exit_mouse,
# From Textfield...
curses.KEY_BACKSPACE: self.h_delete_left,
curses.KEY_DC: self.h_delete_right,
curses.KEY_LEFT: self.h_cursor_left,
curses.KEY_RIGHT: self.h_cursor_right,
curses.ascii.BS: self.h_delete_left,
curses.ascii.DEL: self.h_delete_left,
# New bindings...
curses.ascii.TAB: self.h_addch,
}
# dump_handlers(self)
#@-others
#@+node:ekr.20170603104320.1: *3* class LeoLogTextfield (npyscreen.Textfield)
class LeoLogTextfield(npyscreen.Textfield):
"""
A class to allow an overridden h_addch for body text.
MultiLines are *not* Textfields, the *contain* Textfields.
"""
def __init__(self, *args, **kwargs):
self.leo_parent = None # Injected later.
super().__init__(*args, **kwargs)
self.set_handlers()
#@+others
#@+node:ekr.20170604113445.1: *4* LeoLogTextfield handlers
# All h_exit_* methods call self.leo_parent.set_box_name.
# In addition, h_exit_down inserts a blank(!!) for '\n'.
#@+node:ekr.20170603104320.5: *5* LeoLogTextfield.h_exit_escape
def h_exit_escape(self, ch_i):
"""From InputHandler.h_exit_escape"""
parent_w = self.leo_parent
parent_w.set_box_name('Log Pane')
if not self._test_safe_to_exit():
return False
self.editing = False
self.how_exited = EXITED_ESCAPE
return None
#@+node:ekr.20170603104320.6: *5* LeoLogTextfield.h_exit_mouse
def h_exit_mouse(self, ch_i):
"""From InputHandler.h_exit_mouse"""
# pylint: disable=no-member
parent_w = self.leo_parent
parent_w.set_box_name('Log Pane')
mouse_event = self.parent.safe_get_mouse_event()
if mouse_event and self.intersted_in_mouse_event(mouse_event):
self.handle_mouse_event(mouse_event)
else:
if mouse_event and self._test_safe_to_exit():
curses.ungetmouse(*mouse_event)
ch = self.parent.curses_pad.getch()
assert ch == curses.KEY_MOUSE
self.editing = False
self.how_exited = EXITED_MOUSE
#@+node:ekr.20170603104320.8: *5* LeoLogTextfield.h_exit_down
def h_exit_down(self, ch_i):
"""LeoLogTextfield.h_exit_up. Delegate to LeoLog."""
# g.trace('(LeoLogTextfield)', self._test_safe_to_exit())
if ch_i in (curses.ascii.CR, curses.ascii.NL):
# A pretty horrible kludge.
self.h_addch(ord(' '))
self.cursor_position = 0
else:
parent_w = self.leo_parent
parent_w.set_box_name('Log Pane')
if not self._test_safe_to_exit():
return False
self.editing = False
self.how_exited = EXITED_DOWN
return None
#@+node:ekr.20170603104320.9: *5* LeoLogTextfield.h_exit_up
def h_exit_up(self, ch_i):
"""LeoLogTextfield.h_exit_up. Delegate to LeoLog."""
parent_w = self.leo_parent
if not self._test_safe_to_exit():
return False
parent_w.set_box_name('Log Pane')
self.editing = False
self.how_exited = EXITED_DOWN
return None
#@+node:ekr.20170604075324.1: *4* LeoLogTextfield.set_handlers
def set_handlers(self):
# pylint: disable=no-member
self.handlers = {
# From InputHandler...
curses.ascii.NL: self.h_exit_down,
curses.ascii.CR: self.h_exit_down,
curses.KEY_DOWN: self.h_exit_down,
curses.KEY_UP: self.h_exit_up, # 2017/06/06.
curses.ascii.ESC: self.h_exit_escape,
curses.KEY_MOUSE: self.h_exit_mouse,
# From Textfield...
curses.KEY_BACKSPACE: self.h_delete_left,
curses.KEY_DC: self.h_delete_right,
curses.KEY_LEFT: self.h_cursor_left,
curses.KEY_RIGHT: self.h_cursor_right,
curses.ascii.BS: self.h_delete_left,
curses.ascii.DEL: self.h_delete_left,
# New bindings...
curses.ascii.TAB: self.h_addch,
}
# dump_handlers(self)
#@-others
#@+node:ekr.20170507184329.1: *3* class LeoTreeData (npyscreen.TreeData)
class LeoTreeData(npyscreen.TreeData):
"""A TreeData class that has a len and new_first_child methods."""
#@+<< about LeoTreeData ivars >>
#@+node:ekr.20170516143500.1: *4* << about LeoTreeData ivars >>
# EKR: TreeData.__init__ sets the following ivars for keyword args.
# self._parent # None or weakref.proxy(parent)
# self.content.
# self.selectable = selectable
# self.selected = selected
# self.highlight = highlight
# self.expanded = expanded
# self._children = []
# self.ignore_root = ignore_root
# self.sort = False
# self.sort_function = sort_function
# self.sort_function_wrapper = True
#@-<< about LeoTreeData ivars >>
def __len__(self):
if native:
p = self.content
assert p and isinstance(p, leoNodes.Position), repr(p)
content = p.h
else:
content = self.content
return len(content)
def __repr__(self):
if native:
p = self.content
assert p and isinstance(p, leoNodes.Position), repr(p)
return '<LeoTreeData: %s, %s>' % (id(p), p.h)
return '<LeoTreeData: %r>' % self.content
__str__ = __repr__
#@+others
#@+node:ekr.20170516153211.1: *4* LeoTreeData.__getitem__
def __getitem__(self, n):
"""Return the n'th item in this tree."""
aList = self.get_tree_as_list()
data = aList[n] if n < len(aList) else None
# g.trace(n, len(aList), repr(data))
return data
#@+node:ekr.20170516093009.1: *4* LeoTreeData.is_ancestor_of
def is_ancestor_of(self, node):
assert isinstance(node, LeoTreeData), repr(node)
parent = node._parent
while parent:
if parent == self:
return True
parent = parent._parent
return False
#@+node:ekr.20170516085427.1: *4* LeoTreeData.overrides
# Don't use weakrefs!
#@+node:ekr.20170518103807.6: *5* LeoTreeData.find_depth
def find_depth(self, d=0):
if native:
p = self.content
n = p.level()
return n
parent = self.get_parent()
while parent:
d += 1
parent = parent.get_parent()
return d
#@+node:ekr.20170516085427.2: *5* LeoTreeData.get_children
def get_children(self):
if native:
p = self.content
return p.children()
return self._children
#@+node:ekr.20170518103807.11: *5* LeoTreeData.get_parent
def get_parent(self):
if native:
p = self.content
return p.parent()
return self._parent
#@+node:ekr.20170516085427.3: *5* LeoTreeData.get_tree_as_list
def get_tree_as_list(self): # only_expanded=True, sort=None, key=None):
"""
Called only from LeoMLTree.values._getValues.
Return the result of converting this node and its *visible* descendants
to a list of LeoTreeData nodes.
"""
assert g.callers(1) == '_getValues', g.callers()
aList = [z for z in self.walk_tree(only_expanded=True)]
# g.trace('LeoTreeData', len(aList))
return aList
#@+node:ekr.20170516085427.4: *5* LeoTreeData.new_child
def new_child(self, *args, **keywords):
if self.CHILDCLASS:
cld = self.CHILDCLASS
else:
cld = type(self)
child = cld(parent=self, *args, **keywords)
self._children.append(child)
return child
#@+node:ekr.20170516085742.1: *5* LeoTreeData.new_child_at
def new_child_at(self, index, *args, **keywords):
"""Same as new_child, with insert(index, c) instead of append(c)"""
# g.trace('LeoTreeData')
if self.CHILDCLASS:
cld = self.CHILDCLASS
else:
cld = type(self)
child = cld(parent=self, *args, **keywords)
self._children.insert(index, child)
return child
#@+node:ekr.20170516085427.5: *5* LeoTreeData.remove_child
def remove_child(self, child):
if native:
p = self.content
# g.trace('LeoTreeData', p.h, g.callers())
p.doDelete()
else:
self._children = [z for z in self._children if z != child]
# May be useful when child is cloned.
#@+node:ekr.20170518103807.21: *5* LeoTreeData.set_content
def set_content(self, content):
if native:
if content is None:
self.content = None
elif isinstance(content, str):
# This is a dummy node, not actually used.
assert content == '<HIDDEN>', repr(content)
self.content = content
else:
p = content
assert p and isinstance(p, leoNodes.Position), repr(p)
self.content = content.copy()
else:
self.content = content
#@+node:ekr.20170516085427.6: *5* LeoTreeData.set_parent
def set_parent(self, parent):
self._parent = parent
#@+node:ekr.20170518103807.24: *5* LeoTreeData.walk_tree (native only)
if native:
def walk_tree(self,
only_expanded=True,
ignore_root=True,
sort=None,
sort_function=None,
):
p = self.content.copy()
# Never change the stored position!
# LeoTreeData(p) makes a copy of p.
# g.trace('LeoTreeData: only_expanded:', only_expanded, p.h)
if not ignore_root:
yield self # The hidden root. Probably not needed.
if only_expanded:
while p:
if p.has_children() and p.isExpanded():
p.moveToFirstChild()
yield LeoTreeData(p)
elif p.next():
p.moveToNext()
yield LeoTreeData(p)
elif p.parent():
p.moveToParent()
yield LeoTreeData(p)
else:
return # raise StopIteration
else:
while p:
yield LeoTreeData(p)
p.moveToThreadNext()
# else use the base TreeData.walk_tree method.
#@-others
#@+node:ekr.20170508085942.1: *3* class LeoTreeLine (npyscreen.TreeLine)
class LeoTreeLine(npyscreen.TreeLine):
"""A editable TreeLine class."""
def __init__(self, *args, **kwargs):
self.leo_c = None # Injected later.
super().__init__(*args, **kwargs)
# Done in TreeLine.init:
# self._tree_real_value = None
# A weakproxy to LeoTreeData.
# self._tree_ignore_root = None
# self._tree_depth = False
# self._tree_sibling_next = False
# self._tree_has_children = False
# self._tree_expanded = True
# self._tree_last_line = False
# self._tree_depth_next = False
# self.safe_depth_display = False
# self.show_v_lines = True
self.set_handlers()
def __repr__(self):
val = self._tree_real_value
if native:
p = val and val.content
if p is not None:
assert p and isinstance(p, leoNodes.Position), repr(p)
return '<LeoTreeLine: %s>' % (p.h if p else 'None')
return '<LeoTreeLine: %s>' % (val.content if val else 'None')
__str__ = __repr__
#@+others
#@+node:ekr.20170514104550.1: *4* LeoTreeLine._get_string_to_print
def _get_string_to_print(self):
# From TextfieldBase.
if native:
if self.value:
assert isinstance(self.value, LeoTreeData)
p = self.value.content
assert p and isinstance(p, leoNodes.Position), repr(p)
return p.h or ' '
return ''
s = self.value.content if self.value else None
return g.toUnicode(s) if s else None
#@+node:ekr.20170522032805.1: *4* LeoTreeLine._print
def _print(self, left_margin=0):
"""LeoTreeLine._print. Adapted from TreeLine._print."""
# pylint: disable=no-member
def put(char):
self.parent.curses_pad.addch(
self.rely, self.relx + self.left_margin,
ord(char), curses.A_NORMAL)
self.left_margin += 1
self.left_margin = left_margin
self.parent.curses_pad.bkgdset(' ', curses.A_NORMAL)
if native:
c = getattr(self, 'leo_c', None)
val = self._tree_real_value
if val is None:
return # startup
p = val.content
assert isinstance(p, leoNodes.Position), repr(p)
self.left_margin += 2 * p.level()
if p.hasChildren():
put('-' if p.isExpanded() else '+')
else:
put(' ')
put(':')
put('*' if c and p == c.p else ' ')
put('C' if p and p.isCloned() else ' ')
put('M' if p and p.isMarked() else ' ')
put('T' if p and p.b.strip() else ' ')
put(':')
else:
self.left_margin += self._print_tree(self.relx)
# Now draw the actual line.
if self.highlight:
self.parent.curses_pad.bkgdset(' ', curses.A_STANDOUT)
# This draws the actual line.
super()._print()
#@+node:ekr.20170514183049.1: *4* LeoTreeLine.display_value
def display_value(self, vl):
# vl is a LeoTreeData.
if native:
p = vl.content
assert p and isinstance(p, leoNodes.Position), repr(p)
return p.h or ' '
return vl.content if vl else ''
#@+node:ekr.20170510210908.1: *4* LeoTreeLine.edit
def edit(self):
"""Allow the user to edit the widget: ie. start handling keypresses."""
# g.trace('LeoTreeLine 1')
self.editing = True
# self._pre_edit()
self.highlight = True
self.how_exited = False
# self._edit_loop()
old_parent_editing = self.parent.editing
self.parent.editing = True
while self.editing and self.parent.editing:
self.display()
self.get_and_use_key_press()
# A base TreeLine method.
self.parent.editing = old_parent_editing
self.editing = False
self.how_exited = True
# return self._post_edit()
self.highlight = False
self.update()
#@+node:ekr.20170508130016.1: *4* LeoTreeLine.handlers
#@+node:ekr.20170508130946.1: *5* LeoTreeLine.h_cursor_beginning
def h_cursor_beginning(self, ch):
self.cursor_position = 0
#@+node:ekr.20170508131043.1: *5* LeoTreeLine.h_cursor_end
def h_cursor_end(self, ch):
# self.value is a LeoTreeData.
# native: content is a position.
content = self.value.content
s = content.h if native else content
self.cursor_position = max(0, len(s) - 1)
#@+node:ekr.20170508130328.1: *5* LeoTreeLine.h_cursor_left
def h_cursor_left(self, input):
# self.value is a LeoTreeData.
# native: content is a position.
content = self.value.content
s = content.h if native else content
i = min(self.cursor_position, len(s) - 1)
self.cursor_position = max(0, i - 1)
#@+node:ekr.20170508130339.1: *5* LeoTreeLine.h_cursor_right
def h_cursor_right(self, input):
# self.value is a LeoTreeData.
# native: content is a position.
content = self.value.content
s = content.h if native else content
i = self.cursor_position
i = min(i + 1, len(s) - 1)
self.cursor_position = max(0, i)
#@+node:ekr.20170508130349.1: *5* LeoTreeLine.h_delete_left
def h_delete_left(self, input):
# self.value is a LeoTreeData.
n = self.cursor_position
if native:
p = self.value.content
assert p and isinstance(p, leoNodes.Position), repr(p)
s = p.h
if 0 <= n <= len(s):
c = p.v.context
h = s[:n] + s[n + 1 :]
c.frame.tree.onHeadChanged(p, s=h, undoType='Typing')
# Sets p.h and handles undo.
else:
s = self.value.content
if 0 <= n <= len(s):
self.value.content = s[:n] + s[n + 1 :]
self.cursor_position -= 1
#@+node:ekr.20170510212007.1: *5* LeoTreeLine.h_end_editing
def h_end_editing(self, ch):
c = self.leo_c
c.endEditing()
self.editing = False
self.how_exited = None
#@+node:ekr.20170508125632.1: *5* LeoTreeLine.h_insert (to do: honor v.selection)
def h_insert(self, i):
# self.value is a LeoTreeData.
n = self.cursor_position + 1
if native:
p = self.value.content
c = p.v.context
s = p.h
h = s[:n] + chr(i) + s[n:]
c.frame.tree.onHeadChanged(p, s=h, undoType='Typing')
# Sets p.h and handles undo.
else:
s = self.value.content
self.value.content = s[:n] + chr(i) + s[n:]
self.cursor_position += 1
#@+node:ekr.20170508130025.1: *5* LeoTreeLine.set_handlers
#@@nobeautify
def set_handlers(self):
# pylint: disable=no-member
# Override *all* other complex handlers.
self.complex_handlers = (
(curses.ascii.isprint, self.h_insert),
)
self.handlers.update({
curses.ascii.ESC: self.h_end_editing,
curses.ascii.NL: self.h_end_editing,
curses.ascii.LF: self.h_end_editing,
curses.KEY_HOME: self.h_cursor_beginning, # 262
curses.KEY_END: self.h_cursor_end, # 358.
curses.KEY_LEFT: self.h_cursor_left,
curses.KEY_RIGHT: self.h_cursor_right,
curses.ascii.BS: self.h_delete_left,
curses.KEY_BACKSPACE: self.h_delete_left,
curses.KEY_MOUSE: self.h_exit_mouse, # New
})
#@+node:ekr.20170519023802.1: *4* LeoTreeLine.when_check_value_changed
if native:
def when_check_value_changed(self):
"""Check whether the widget's value has changed and call when_valued_edited if so."""
return True
#@-others
#@+node:ekr.20170618103742.1: *3* class QuitButton (npyscreen.MiniButton)
class QuitButton(npyscreen.MiniButtonPress):
"""Override the "Quit Leo" button so it prompts for save if needed."""
def whenPressed(self):
g.app.onQuit()
#@-others
#@-<< forward reference classes >>
#@+others
#@+node:ekr.20170501043944.1: ** curses2: top-level functions
#@+node:ekr.20170603110639.1: *3* curses2: dump_handlers
def dump_handlers(obj,
dump_complex=True,
dump_handlers=True,
dump_keys=True,
):
tag = obj.__class__.__name__
if dump_keys:
g.trace('%s: keys' % tag)
aList = []
for z in obj.handlers:
kind = repr(chr(z)) if isinstance(z, int) and 32 <= z < 127 else ''
name = method_name(obj.handlers.get(z))
aList.append('%3s %3s %4s %s' % (z, type(z).__name__, kind, name))
g.printList(sorted(aList))
if dump_handlers:
g.trace('%s: handlers' % tag)
aList = [method_name(obj.handlers.get(z))
for z in obj.handlers]
g.printList(sorted(set(aList)))
if dump_complex:
g.trace('%s: complex_handlers' % tag)
aList = []
for data in obj.complex_handlers:
f1, f2 = data
aList.append('%25s predicate: %s' % (method_name(f2), method_name(f1)))
g.printList(sorted(set(aList)))
#@+node:ekr.20170419094705.1: *3* curses2: init
def init():
"""
top-level init for cursesGui2.py pseudo-plugin.
This plugin should be loaded only from leoApp.py.
"""
if g.app.gui:
if not g.unitTesting:
s = "Can't install text gui: previous gui installed"
g.es_print(s, color="red")
return False
return curses and not g.unitTesting
# Not Ok for unit testing!
#@+node:ekr.20170501032705.1: *3* curses2: leoGlobals replacements
# CGui.init_logger monkey-patches leoGlobals with these functions.
#@+node:ekr.20170430112645.1: *4* curses2: es
def es(*args, **keys):
"""Monkey-patch for g.es."""
d = {
'color': None,
'commas': False,
'newline': True,
'spaces': True,
'tabName': 'Log',
}
d = g.doKeywordArgs(keys, d)
color = d.get('color')
s = g.translateArgs(args, d)
if isinstance(g.app.gui, LeoCursesGui):
if g.app.gui.log_inited:
g.app.gui.log.put(s, color=color)
else:
g.app.gui.wait_list.append((s, color),)
# else: logging.info(' KILL: %r' % s)
#@+node:ekr.20170613144149.1: *4* curses2: has_logger (not used)
def has_logger():
logger = logging.getLogger()
return any(isinstance(z, logging.handlers.SocketHandler) for z in logger.handlers or [])
#@+node:ekr.20170501043411.1: *4* curses2: pr
def pr(*args, **keys):
"""Monkey-patch for g.pr."""
d = {'commas': False, 'newline': True, 'spaces': True}
d = g.doKeywordArgs(keys, d)
s = g.translateArgs(args, d)
for line in g.splitLines(s):
if line.strip(): # No need to print blank logging lines.
line = ' pr: %s' % line.rstrip()
logging.info(line)
#@+node:ekr.20170429165242.1: *4* curses2: trace
def trace(*args, **keys):
"""Monkey-patch for g.trace."""
d = {
'align': 0,
'before': '',
'newline': True,
'caller_level': 1,
'noname': False,
}
d = g.doKeywordArgs(keys, d)
align = d.get('align', 0)
caller_level = d.get('caller_level', 1)
# Compute the caller name.
if d.get('noname'):
name = ''
else:
try: # get the function name from the call stack.
f1 = sys._getframe(caller_level) # The stack frame, one level up.
code1 = f1.f_code # The code object
name = code1.co_name # The code name
except Exception:
name = g.shortFileName(__file__)
if name == '<module>':
name = g.shortFileName(__file__)
if name.endswith('.pyc'):
name = name[:-1]
# Pad the caller name.
if align != 0 and len(name) < abs(align):
pad = ' ' * (abs(align) - len(name))
if align > 0:
name = name + pad
else:
name = pad + name
# Munge *args into s.
result = [name] if name else []
for arg in args:
if isinstance(arg, str):
pass
elif isinstance(arg, bytes):
arg = g.toUnicode(arg)
else:
arg = repr(arg)
if result:
result.append(" " + arg)
else:
result.append(arg)
s = ''.join(result)
line = 'trace: %s' % s.rstrip()
logging.info(line)
#@+node:ekr.20170526075024.1: *3* method_name
def method_name(f):
"""Print a method name is a simplified format."""
pattern = r'<bound method ([\w\.]*\.)?(\w+) of <([\w\.]*\.)?(\w+) object at (.+)>>'
m = re.match(pattern, repr(f))
if m:
return '%20s%s' % (m.group(1), m.group(2))
# Shows actual method: very useful
return repr(f)
#@+node:ekr.20210228141208.1: ** decorators (curses2)
def frame_cmd(name):
"""Command decorator for the LeoFrame class."""
return g.new_cmd_decorator(name, ['c', 'frame',])
def log_cmd(name):
"""Command decorator for the c.frame.log class."""
return g.new_cmd_decorator(name, ['c', 'frame', 'log'])
#@+node:ekr.20170524123950.1: ** Gui classes
#@+node:ekr.20171128051435.1: *3* class StringFindTabManager(cursesGui2.py)
class StringFindTabManager:
"""CursesGui.py: A string-based FindTabManager class."""
# A complete rewrite of the FindTabManager in qt_frame.py.
#@+others
#@+node:ekr.20171128051435.2: *4* sftm.ctor
def __init__(self, c):
"""Ctor for the StringFindTabManager class."""
self.c = c
assert c.findCommands
c.findCommands.minibuffer_mode = True
self.entry_focus = None # The widget that had focus before find-pane entered.
# Find/change text boxes.
self.find_findbox = None
self.find_replacebox = None
# Check boxes.
self.check_box_ignore_case = None
self.check_box_mark_changes = None
self.check_box_mark_finds = None
self.check_box_regexp = None
self.check_box_search_body = None
self.check_box_search_headline = None
self.check_box_whole_word = None
# self.check_box_wrap_around = None
# Radio buttons
self.radio_button_entire_outline = None
self.radio_button_node_only = None
self.radio_button_suboutline_only = None
# Push buttons
self.find_next_button = None
self.find_prev_button = None
self.find_all_button = None
self.help_for_find_commands_button = None
self.replace_button = None
self.replace_then_find_button = None
self.replace_all_button = None
#@+node:ekr.20171128051435.3: *4* sftm.text getters/setters
def get_find_text(self):
return g.toUnicode(self.find_findbox.text())
def get_change_text(self):
return g.toUnicode(self.find_replacebox.text())
def set_find_text(self, s):
w = self.find_findbox
s = g.toUnicode(s)
w.clear()
w.insert(s)
def set_change_text(self, s):
w = self.find_replacebox
s = g.toUnicode(s)
w.clear()
w.insert(s)
#@+node:ekr.20171128051435.4: *4* sftm.*_focus
def clear_focus(self):
pass
def init_focus(self):
pass
def set_entry_focus(self):
pass
#@+node:ekr.20171128051435.5: *4* sftm.set_ignore_case
def set_ignore_case(self, aBool):
"""Set the ignore-case checkbox to the given value."""
c = self.c
c.findCommands.ignore_case = aBool
w = self.check_box_ignore_case
w.setChecked(aBool)
#@+node:ekr.20171128051435.6: *4* sftm.init_widgets
def init_widgets(self):
"""
Init widgets and ivars from c.config settings.
Create callbacks that always keep the LeoFind ivars up to date.
"""
c = self.c
find = c.findCommands
# Find/change text boxes.
table = (
('find_findbox', 'find_text', '<find pattern here>'),
('find_replacebox', 'change_text', ''),
)
for ivar, setting_name, default in table:
s = c.config.getString(setting_name) or default
w = getattr(self, ivar)
w.insert(s)
# Check boxes.
table = (
('ignore_case', self.check_box_ignore_case),
('mark_changes', self.check_box_mark_changes),
('mark_finds', self.check_box_mark_finds),
('pattern_match', self.check_box_regexp),
('search_body', self.check_box_search_body),
('search_headline', self.check_box_search_headline),
('whole_word', self.check_box_whole_word),
# ('wrap', self.check_box_wrap_around),
)
for setting_name, w in table:
val = c.config.getBool(setting_name, default=False)
# The setting name is also the name of the LeoFind ivar.
assert hasattr(find, setting_name), setting_name
setattr(find, setting_name, val)
if val:
w.toggle()
def check_box_callback(n, setting_name=setting_name, w=w):
val = w.isChecked()
assert hasattr(find, setting_name), setting_name
setattr(find, setting_name, val)
# Radio buttons
table = (
('node_only', 'node_only', self.radio_button_node_only),
('entire_outline', None, self.radio_button_entire_outline),
('suboutline_only', 'suboutline_only', self.radio_button_suboutline_only),
)
for setting_name, ivar, w in table:
val = c.config.getBool(setting_name, default=False)
# The setting name is also the name of the LeoFind ivar.
if ivar is not None:
assert hasattr(find, setting_name), setting_name
setattr(find, setting_name, val)
w.toggle()
def radio_button_callback(n, ivar=ivar, setting_name=setting_name, w=w):
val = w.isChecked()
if ivar:
assert hasattr(find, ivar), ivar
setattr(find, ivar, val)
# Ensure one radio button is set.
if not find.node_only and not find.suboutline_only:
w = self.radio_button_entire_outline
w.toggle()
#@+node:ekr.20171128051435.7: *4* sftm.set_radio_button
#@@nobeautify
def set_radio_button(self, name):
"""Set the value of the radio buttons"""
c = self.c
fc = c.findCommands
d = {
# commandName fc.ivar # radio button.
'node-only': ('node_only', self.radio_button_node_only),
'entire-outline': (None, self.radio_button_entire_outline),
'suboutline-only': ('suboutline_only', self.radio_button_suboutline_only)
}
ivar, w = d.get(name)
assert w, repr(w)
if not w.isChecked():
w.toggle() # This just sets the radio button's value.
# First, clear the ivars.
fc.node_only = False
fc.suboutline_only = False
# Next, set the ivar.
if ivar:
setattr(fc, ivar, True)
#@+node:ekr.20171128051435.8: *4* sftm.toggle_checkbox
#@@nobeautify
def toggle_checkbox(self,checkbox_name):
"""Toggle the value of the checkbox whose name is given."""
c = self.c
fc = c.findCommands
if not fc:
return
d = {
'ignore_case': self.check_box_ignore_case,
'mark_changes': self.check_box_mark_changes,
'mark_finds': self.check_box_mark_finds,
'pattern_match': self.check_box_regexp,
'search_body': self.check_box_search_body,
'search_headline': self.check_box_search_headline,
'whole_word': self.check_box_whole_word,
# 'wrap': self.check_box_wrap_around,
}
w = d.get(checkbox_name)
assert w, repr(w)
assert hasattr(fc, checkbox_name),checkbox_name
setattr(fc, checkbox_name, not getattr(fc, checkbox_name))
w.toggle() # Only toggles w's internal value.
# g.trace(checkbox_name, getattr(fc, checkbox_name, None))
#@-others
#@+node:edward.20170428174322.1: *3* class KeyEvent
class KeyEvent:
"""A gui-independent wrapper for gui events."""
#@+others
#@+node:edward.20170428174322.2: *4* KeyEvent.__init__
def __init__(self, c, char, event, shortcut, w,
x=None,
y=None,
x_root=None,
y_root=None,
):
"""Ctor for KeyEvent class."""
assert not g.isStroke(shortcut), g.callers()
stroke = g.KeyStroke(shortcut) if shortcut else None
# g.trace('KeyEvent: stroke', stroke)
self.c = c
self.char = char or ''
self.event = event
self.stroke = stroke
self.w = self.widget = w
# Optional ivars
self.x = x
self.y = y
# Support for fastGotoNode plugin
self.x_root = x_root
self.y_root = y_root
#@+node:edward.20170428174322.3: *4* KeyEvent.__repr__
def __repr__(self):
return 'KeyEvent: stroke: %s, char: %s, w: %s' % (
repr(self.stroke), repr(self.char), repr(self.w))
#@+node:edward.20170428174322.4: *4* KeyEvent.get & __getitem__
def get(self, attr):
"""Compatibility with g.bunch: return an attr."""
return getattr(self, attr, None)
def __getitem__(self, attr):
"""Compatibility with g.bunch: return an attr."""
return getattr(self, attr, None)
#@+node:edward.20170428174322.5: *4* KeyEvent.type
def type(self):
return 'KeyEvent'
#@-others
#@+node:ekr.20170430114840.1: *3* class KeyHandler
class KeyHandler:
#@+others
#@+node:ekr.20170430114930.1: *4* CKey.do_key & helpers
def do_key(self, ch_i):
"""
Handle a key event by calling k.masterKeyHandler.
Return True if the event was completely handled.
"""
# This is a rewrite of LeoQtEventFilter code.
c = g.app.log and g.app.log.c
k = c and c.k
if not c:
return True # We are shutting down.
if self.is_key_event(ch_i):
try:
ch = chr(ch_i)
except Exception:
ch = '<no ch>'
char, shortcut = self.to_key(ch_i)
if g.app.gui.in_dialog:
if 0:
g.trace('(CKey) dialog key', ch)
elif shortcut:
try:
w = c.frame.body.wrapper
event = self.create_key_event(c, w, char, shortcut)
k.masterKeyHandler(event)
except Exception:
g.es_exception()
g.app.gui.show_label(c)
return bool(shortcut)
g.app.gui.show_label(c)
return False
#@+node:ekr.20170430115131.4: *5* CKey.char_to_tk_name
tk_dict = {
# Part 1: same as g.app.guiBindNamesDict
"&": "ampersand",
"^": "asciicircum",
"~": "asciitilde",
"*": "asterisk",
"@": "at",
"\\": "backslash",
"|": "bar",
"{": "braceleft",
"}": "braceright",
"[": "bracketleft",
"]": "bracketright",
":": "colon",
",": "comma",
"$": "dollar",
"=": "equal",
"!": "exclam",
">": "greater",
"<": "less",
"-": "minus",
"#": "numbersign",
'"': "quotedbl",
"'": "quoteright",
"(": "parenleft",
")": "parenright",
"%": "percent",
".": "period",
"+": "plus",
"?": "question",
"`": "quoteleft",
";": "semicolon",
"/": "slash",
" ": "space",
"_": "underscore",
}
def char_to_tk_name(self, ch):
return self.tk_dict.get(ch, ch)
#@+node:ekr.20170430115131.2: *5* CKey.create_key_event
def create_key_event(self, c, w, ch, binding):
trace = False
# Last-minute adjustments...
if binding == 'Return':
ch = '\n' # Somehow Qt wants to return '\r'.
elif binding == 'Escape':
ch = 'Escape'
# Switch the Shift modifier to handle the cap-lock key.
if isinstance(ch, int):
g.trace('can not happen: ch: %r binding: %r' % (ch, binding))
elif (
ch and len(ch) == 1 and
binding and len(binding) == 1 and
ch.isalpha() and binding.isalpha()
):
if ch != binding:
if trace:
g.trace('caps-lock')
binding = ch
if trace:
g.trace('ch: %r, binding: %r' % (ch, binding))
return leoGui.LeoKeyEvent(
c=c,
char=ch,
event={'c': c, 'w': w},
binding=binding,
w=w, x=0, y=0, x_root=0, y_root=0,
)
#@+node:ekr.20170430115030.1: *5* CKey.is_key_event
def is_key_event(self, ch_i):
# pylint: disable=no-member
return ch_i not in (curses.KEY_MOUSE,)
#@+node:ekr.20170430115131.3: *5* CKey.to_key
def to_key(self, i):
"""Convert int i to a char and shortcut."""
trace = False
a = curses.ascii
char, shortcut = '', ''
s = a.unctrl(i)
if i <= 32:
d = {
8: 'Backspace', 9: 'Tab',
10: 'Return', 13: 'Linefeed',
27: 'Escape', 32: ' ',
}
shortcut = d.get(i, '')
# All real ctrl keys lie between 1 and 26.
if shortcut and shortcut != 'Escape':
char = chr(i)
elif len(s) >= 2 and s.startswith('^'):
shortcut = 'Ctrl+' + self.char_to_tk_name(s[1:].lower())
elif i == 127:
pass
elif i < 128:
char = shortcut = chr(i)
if char.isupper():
shortcut = 'Shift+' + char
else:
shortcut = self.char_to_tk_name(char)
elif 265 <= i <= 276:
# Special case for F-keys
shortcut = 'F%s' % (i - 265 + 1)
elif i == 351:
shortcut = 'Shift+Tab'
elif s.startswith('\\x'):
pass
elif len(s) >= 3 and s.startswith('!^'):
shortcut = 'Alt+' + self.char_to_tk_name(s[2:])
else:
pass
if trace:
g.trace('i: %s s: %s char: %r shortcut: %r' % (i, s, char, shortcut))
return char, shortcut
#@-others
#@+node:ekr.20170419094731.1: *3* class LeoCursesGui (leoGui.LeoGui)
class LeoCursesGui(leoGui.LeoGui):
"""
Leo's curses gui wrapper.
This is g.app.gui, when --gui=curses.
"""
#@+others
#@+node:ekr.20171128041849.1: *4* CGui.Birth & death
#@+node:ekr.20170608112335.1: *5* CGui.__init__
def __init__(self):
"""Ctor for the CursesGui class."""
super().__init__('curses')
# Init the base class.
self.consoleOnly = False
# Required attribute.
self.curses_app = None
# The singleton LeoApp instance.
self.curses_form = None
# The top-level curses Form instance.
# Form.editw is the widget with focus.
self.curses_gui_arg = None
# A hack for interfacing with k.getArg.
self.in_dialog = False
# True: executing a modal dialog.
self.log = None
# The present log. Used by g.es
self.log_inited = False
# True: don't use the wait_list.
self.minibuffer_label = ''
# The label set by k.setLabel.
self.wait_list = []
# Queued log messages.
self.init_logger()
# Do this as early as possible.
# It monkey-patches g.pr and g.trace.
self.top_form = None
# The top-level form. Set in createCursesTop.
self.key_handler = KeyHandler()
#@+node:ekr.20170502083158.1: *5* CGui.createCursesTop & helpers
def createCursesTop(self):
"""Create the top-level curses Form."""
trace = False and not g.unitTesting
# Assert the key relationships required by the startup code.
assert self == g.app.gui
c = g.app.log.c
assert c == g.app.windowList[0].c
assert isinstance(c.frame, CoreFrame), repr(c.frame)
if trace:
g.trace('commanders in g.app.windowList')
g.printList([z.c.shortFileName() for z in g.app.windowList])
# Create the top-level form.
self.curses_form = form = LeoForm(name='Dummy Name')
# This call clears the screen.
self.createCursesLog(c, form)
self.createCursesTree(c, form)
self.createCursesBody(c, form)
self.createCursesMinibuffer(c, form)
self.createCursesStatusLine(c, form)
self.monkeyPatch(c)
self.redraw_in_context(c)
c.frame.tree.set_status_line(c.p)
# self.focus_to_body(c)
return form
#@+node:ekr.20170502084106.1: *6* CGui.createCursesBody
def createCursesBody(self, c, form):
"""
Create the curses body widget in the given curses Form.
Populate it with c.p.b.
"""
trace = False
class BoxTitleBody(npyscreen.BoxTitle):
# pylint: disable=used-before-assignment
_contained_widget = LeoBody
how_exited = None
box = form.add(
BoxTitleBody,
max_height=8, # Subtract 4 lines
name='Body Pane',
footer="Press e to edit line, esc to end editing, d to delete line",
values=g.splitLines(c.p.b),
slow_scroll=True,
)
assert isinstance(box, BoxTitleBody), repr(box)
# Get the contained widget.
widgets = box._my_widgets
assert len(widgets) == 1
w = widgets[0]
if trace:
g.trace('\nBODY', w, '\nBOX', box)
assert isinstance(w, LeoBody), repr(w)
# Link and check.
assert isinstance(c.frame, leoFrame.LeoFrame), repr(c.frame)
# The generic LeoFrame class
assert isinstance(c.frame.body, leoFrame.LeoBody), repr(c.frame.body)
# The generic LeoBody class
assert c.frame.body.widget is None, repr(c.frame.body.widget)
c.frame.body.widget = w
assert c.frame.body.wrapper is None, repr(c.frame.body.wrapper)
c.frame.body.wrapper = wrapper = BodyWrapper(c, 'body', w)
# Inject the wrapper for get_focus.
box.leo_wrapper = wrapper
w.leo_wrapper = wrapper
# Inject leo_c.
w.leo_c = c
w.leo_box = box
#@+node:ekr.20170502083613.1: *6* CGui.createCursesLog
def createCursesLog(self, c, form):
"""
Create the curses log widget in the given curses Form.
Populate the widget with the queued log messages.
"""
class BoxTitleLog(npyscreen.BoxTitle):
# pylint: disable=used-before-assignment
_contained_widget = LeoLog
how_exited = None
box = form.add(
BoxTitleLog,
max_height=8, # Subtract 4 lines
name='Log Pane',
footer="Press e to edit line, esc to end editing, d to delete line",
values=[s for s, color in self.wait_list],
slow_scroll=False,
)
assert isinstance(box, BoxTitleLog), repr(box)
# Clear the wait list and disable it.
self.wait_list = []
self.log_inited = True
widgets = box._my_widgets
assert len(widgets) == 1
w = widgets[0]
assert isinstance(w, LeoLog), repr(w)
# Link and check...
assert isinstance(self.log, CoreLog), repr(self.log)
self.log.widget = w
w.firstScroll()
assert isinstance(c.frame, leoFrame.LeoFrame), repr(c.frame)
# The generic LeoFrame class
c.frame.log.wrapper = wrapper = LogWrapper(c, 'log', w)
# Inject the wrapper for get_focus.
box.leo_wrapper = wrapper
w.leo_wrapper = wrapper
w.leo_box = box
#@+node:ekr.20170502084249.1: *6* CGui.createCursesMinibuffer
def createCursesMinibuffer(self, c, form):
"""Create the curses minibuffer widget in the given curses Form."""
trace = False
class MiniBufferBox(npyscreen.BoxTitle):
"""An npyscreen class representing Leo's minibuffer, with binding."""
# pylint: disable=used-before-assignment
_contained_widget = LeoMiniBuffer
how_exited = None
box = form.add(MiniBufferBox, name='Mini-buffer', max_height=3)
assert isinstance(box, MiniBufferBox)
# Link and check...
widgets = box._my_widgets
assert len(widgets) == 1
w = widgets[0]
if trace:
g.trace('\nMINI', w, '\nBOX', box)
assert isinstance(w, LeoMiniBuffer), repr(w)
assert isinstance(c.frame, CoreFrame), repr(c.frame)
assert c.frame.miniBufferWidget is None
wrapper = MiniBufferWrapper(c, 'minibuffer', w)
assert wrapper.widget == w, repr(wrapper.widget)
c.frame.miniBufferWidget = wrapper
# Inject the box into the wrapper
wrapper.box = box
# Inject the wrapper for get_focus.
box.leo_wrapper = wrapper
w.leo_c = c
w.leo_wrapper = wrapper
#@+node:ekr.20171129193946.1: *6* CGui.createCursesStatusLine
def createCursesStatusLine(self, c, form):
"""Create the curses minibuffer widget in the given curses Form."""
class StatusLineBox(npyscreen.BoxTitle):
"""An npyscreen class representing Leo's status line."""
# pylint: disable=used-before-assignment
_contained_widget = LeoStatusLine
how_exited = None
box = form.add(StatusLineBox, name='Status Line', max_height=3)
assert isinstance(box, StatusLineBox)
# Link and check...
widgets = box._my_widgets
assert len(widgets) == 1
w = widgets[0]
assert isinstance(w, LeoStatusLine), repr(w)
assert isinstance(c.frame, CoreFrame), repr(c.frame)
wrapper = StatusLineWrapper(c, 'status-line', w)
assert wrapper.widget == w, repr(wrapper.widget)
assert isinstance(c.frame.statusLine, g.NullObject)
# assert c.frame.statusLine is None
c.frame.statusLine = wrapper
c.frame.statusText = wrapper
# Inject the wrapper for get_focus.
box.leo_wrapper = wrapper
w.leo_c = c
w.leo_wrapper = wrapper
#@+node:ekr.20170502083754.1: *6* CGui.createCursesTree
def createCursesTree(self, c, form):
"""Create the curses tree widget in the given curses Form."""
class BoxTitleTree(npyscreen.BoxTitle):
# pylint: disable=used-before-assignment
_contained_widget = LeoMLTree
how_exited = None
hidden_root_node = LeoTreeData(content='<HIDDEN>', ignore_root=True)
if native:
pass # cacher created below.
else:
for i in range(3):
node = hidden_root_node.new_child(content='node %s' % (i))
for j in range(2):
child = node.new_child(content='child %s.%s' % (i, j))
for k in range(4):
grand_child = child.new_child(
content='grand-child %s.%s.%s' % (i, j, k))
assert grand_child # for pyflakes.
box = form.add(
BoxTitleTree,
max_height=8, # Subtract 4 lines
name='Tree Pane',
footer="Press d to delete node, e to edit headline (return to end), i to insert node",
values=hidden_root_node,
slow_scroll=False,
)
assert isinstance(box, BoxTitleTree), repr(box)
# Link and check...
widgets = box._my_widgets
assert len(widgets) == 1
w = leo_tree = widgets[0]
assert isinstance(w, LeoMLTree), repr(w)
leo_tree.leo_c = c
if native:
leo_tree.values = LeoValues(c=c, tree=leo_tree)
assert getattr(leo_tree, 'hidden_root_node') is None, leo_tree
leo_tree.hidden_root_node = hidden_root_node
assert isinstance(c.frame, leoFrame.LeoFrame), repr(c.frame)
# CoreFrame is a LeoFrame
assert isinstance(c.frame.tree, CoreTree), repr(c.frame.tree)
assert c.frame.tree.canvas is None, repr(c.frame.canvas)
# A standard ivar, used by Leo's core.
c.frame.canvas = leo_tree
# A LeoMLTree.
assert not hasattr(c.frame.tree, 'treeWidget'), repr(c.frame.tree.treeWidget)
c.frame.tree.treeWidget = leo_tree
# treeWidget is an official ivar.
assert c.frame.tree.widget is None
c.frame.tree.widget = leo_tree
# Set CoreTree.widget.
# Inject the wrapper for get_focus.
wrapper = c.frame.tree
assert wrapper
box.leo_wrapper = wrapper
w.leo_wrapper = wrapper
#@+node:ekr.20171126191726.1: *6* CGui.monkeyPatch
def monkeyPatch(self, c):
"""Monkey patch commands"""
table = (
('start-search', self.startSearch),
)
for commandName, func in table:
g.global_commands_dict[commandName] = func
c.k.overrideCommand(commandName, func)
# A new ivar.
c.inFindCommand = False
#@+node:ekr.20170419110052.1: *5* CGui.createLeoFrame
def createLeoFrame(self, c, title):
"""
Create a LeoFrame for the current gui.
Called from Leo's core (c.initObjects).
"""
return CoreFrame(c, title)
#@+node:ekr.20170502103338.1: *5* CGui.destroySelf
def destroySelf(self):
"""
Terminate the curses gui application.
Leo's core calls this only if the user agrees to terminate the app.
"""
sys.exit(0)
#@+node:ekr.20170501032447.1: *5* CGui.init_logger
def init_logger(self):
self.rootLogger = logging.getLogger('')
self.rootLogger.setLevel(logging.DEBUG)
socketHandler = logging.handlers.SocketHandler(
'localhost',
logging.handlers.DEFAULT_TCP_LOGGING_PORT,
)
self.rootLogger.addHandler(socketHandler)
logging.info('-' * 20)
# Monkey-patch leoGlobals functions.
g.es = es
g.pr = pr # Most ouput goes through here, including g.es_exception.
g.trace = trace
#@+node:ekr.20170419140914.1: *5* CGui.runMainLoop
def runMainLoop(self):
"""The curses gui main loop."""
# pylint: disable=no-member
#
# Do NOT change g.app!
self.curses_app = LeoApp()
stdscr = curses.initscr()
if 1: # Must follow initscr.
self.dump_keys()
try:
self.curses_app.run()
# run calls CApp.main(), which calls CGui.run().
finally:
curses.nocbreak()
stdscr.keypad(0)
curses.echo()
curses.endwin()
if 'shutdown' in g.app.debug:
g.pr('Exiting Leo...')
#@+node:ekr.20170502020354.1: *5* CGui.run
def run(self):
"""
Create and run the top-level curses form.
"""
self.top_form = self.createCursesTop()
# g.trace('(CGui) top_form', self.top_form)
self.top_form.edit()
#@+node:ekr.20170504112655.1: *4* CGui.Clipboard
# Yes, using Tkinter seems to be the standard way.
#@+node:ekr.20170504112744.3: *5* CGui.getTextFromClipboard
def getTextFromClipboard(self):
"""Get a unicode string from the clipboard."""
if not Tk:
return ''
root = Tk()
root.withdraw()
try:
s = root.clipboard_get()
except Exception: # _tkinter.TclError:
s = ''
root.destroy()
return g.toUnicode(s)
#@+node:ekr.20170504112744.2: *5* CGui.replaceClipboardWith
def replaceClipboardWith(self, s):
"""Replace the clipboard with the string s."""
if not Tk:
return
root = Tk()
root.withdraw()
root.clipboard_clear()
root.clipboard_append(s)
root.destroy()
# Do *not* define setClipboardSelection.
# setClipboardSelection = replaceClipboardWith
#@+node:ekr.20170502021145.1: *4* CGui.dialogs
#@+node:ekr.20170712145632.2: *5* CGui.createFindDialog
def createFindDialog(self, c):
"""Create and init a non-modal Find dialog."""
g.trace('not implemented')
#@+node:ekr.20171126182120.1: *5* CGui.dialog_message
def dialog_message(self, message):
"""No longer used: a placeholder for dialogs."""
if not g.unitTesting:
for s in g.splitLines(message):
g.pr(s.rstrip())
#@+node:ekr.20171126182120.2: *5* CGui.runAboutLeoDialog
def runAboutLeoDialog(self, c, version, theCopyright, url, email):
"""Create and run Leo's About Leo dialog."""
if not g.unitTesting:
message = '%s\n%s\n%s\n%s' % (version, theCopyright, url, email)
utilNotify.notify_confirm(message, title="About Leo")
# form_color='STANDOUT', wrap=True, wide=False, editw=0)
#@+node:ekr.20171126182120.3: *5* CGui.runAskLeoIDDialog
def runAskLeoIDDialog(self):
"""Create and run a dialog to get g.app.LeoID."""
if not g.unitTesting:
message = (
"leoID.txt not found\n\n" +
"The curses gui can not set this file." +
"Exiting..."
)
g.trace(message)
sys.exit(0)
# "Please enter an id that identifies you uniquely.\n" +
# "Your cvs/bzr login name is a good choice.\n\n" +
# "Leo uses this id to uniquely identify nodes.\n\n" +
# "Your id must contain only letters and numbers\n" +
# "and must be at least 3 characters in length."
#@+node:ekr.20171126182120.5: *5* CGui.runAskOkCancelNumberDialog
def runAskOkCancelNumberDialog(self, c, title, message,
cancelButtonText=None,
okButtonText=None,
):
"""Create and run askOkCancelNumber dialog ."""
if g.unitTesting:
return False
if self.curses_app:
self.in_dialog = True
val = utilNotify.notify_ok_cancel(message=message, title=title)
self.in_dialog = False
return val
return False
#@+node:ekr.20171126182120.6: *5* CGui.runAskOkCancelStringDialog
def runAskOkCancelStringDialog(self, c, title, message,
cancelButtonText=None,
okButtonText=None,
default="",
wide=False,
):
"""Create and run askOkCancelString dialog ."""
if g.unitTesting:
return False
self.in_dialog = True
val = utilNotify.notify_ok_cancel(message=message, title=title)
# val is True/False
self.in_dialog = False
return 'yes' if val else 'no'
#@+node:ekr.20171126182120.4: *5* CGui.runAskOkDialog
def runAskOkDialog(self, c, title,
message=None,
text="Ok",
):
"""Create and run an askOK dialog ."""
if g.unitTesting:
return False
if self.curses_app:
self.in_dialog = True
val = utilNotify.notify_confirm(message=message, title=title)
self.in_dialog = False
return val
return False
#@+node:ekr.20171126182120.8: *5* CGui.runAskYesNoCancelDialog
def runAskYesNoCancelDialog(self, c, title,
message=None,
yesMessage="Yes",
noMessage="No",
yesToAllMessage=None,
defaultButton="Yes",
cancelMessage=None,
):
"""Create and run an askYesNoCancel dialog ."""
if g.unitTesting:
return False
self.in_dialog = True
val = utilNotify.notify_yes_no(message=message, title=title)
# Important: don't use notify_ok_cancel.
self.in_dialog = False
return 'yes' if val else 'no'
#@+node:ekr.20171126182120.7: *5* CGui.runAskYesNoDialog
def runAskYesNoDialog(self, c, title,
message=None,
yes_all=False,
no_all=False,
):
"""Create and run an askYesNo dialog."""
if g.unitTesting:
return False
self.in_dialog = True
val = utilNotify.notify_ok_cancel(message=message, title=title)
self.in_dialog = False
return 'yes' if val else 'no'
#@+node:ekr.20171126182120.9: *5* CGui.runOpenFileDialog
def runOpenFileDialog(self, c, title, filetypes, defaultextension, multiple=False, startpath=None):
if not g.unitTesting:
g.trace('not ready yet', title)
#@+node:ekr.20171126182120.10: *5* CGui.runPropertiesDialog
def runPropertiesDialog(self,
title='Properties',
data=None,
callback=None,
buttons=None,
):
"""Dispay a modal TkPropertiesDialog"""
if not g.unitTesting:
g.trace('not ready yet', title)
#@+node:ekr.20171126182120.11: *5* CGui.runSaveFileDialog
def runSaveFileDialog(self, c, title, filetypes, defaultextension):
if g.unitTesting:
return None
# Not tested.
from leo.external.npyscreen.fmFileSelector import selectFile
self.in_dialog = True
s = selectFile(
select_dir=False,
must_exist=False,
confirm_if_exists=True,
sort_by_extension=True,
)
self.in_dialog = False
s = s or ''
if s:
c.last_dir = g.os_path_dirname(s)
return s
#@+node:ekr.20170430114709.1: *4* CGui.do_key
def do_key(self, ch_i):
# Ignore all printable characters.
if not self.in_dialog and 32 <= ch_i < 128:
g.trace('ignoring', chr(ch_i))
return True
return self.key_handler.do_key(ch_i)
#@+node:ekr.20170526051256.1: *4* CGui.dump_keys
def dump_keys(self):
"""Show all defined curses.KEY_ constants."""
if 0:
aList = ['%3s %s' % (getattr(curses, z), z)
for z in dir(curses)
if isinstance(getattr(curses, z), int)]
g.trace()
g.printList(sorted(aList))
#@+node:ekr.20170522005855.1: *4* CGui.event_generate
def event_generate(self, c, char, shortcut, w):
k = c.k
event = KeyEvent(
c=c,
char=char,
event=g.NullObject(),
shortcut=shortcut,
w=w,
)
k.masterKeyHandler(event)
g.app.gui.show_label(c)
c.outerUpdate()
#@+node:ekr.20171128041920.1: *4* CGui.Focus
#@+node:ekr.20171127171659.1: *5* CGui.focus_to_body
def focus_to_body(self, c):
"""Put focus in minibuffer text widget."""
w = self.set_focus(c, c.frame.body)
assert w
# w.edit()
#@+node:ekr.20171202092838.1: *5* CGui.focus_to_head
def focus_to_head(self, c, p):
"""Put focus in minibuffer text widget."""
w = self.set_focus(c, c.frame.tree)
assert w
# w.edit()
#@+node:ekr.20171127162649.1: *5* CGui.focus_to_minibuffer
def focus_to_minibuffer(self, c):
"""Put focus in minibuffer text widget."""
w = self.set_focus(c, c.frame.miniBufferWidget)
assert w
# w.edit()
#@+node:ekr.20170502101347.1: *5* CGui.get_focus
def get_focus(self, c=None, raw=False, at_idle=False):
"""
Return the Leo wrapper for the npyscreen widget that is being edited.
"""
# Careful during startup.
trace = 'focus' in g.app.debug
editw = getattr(g.app.gui.curses_form, 'editw', None)
if editw is None:
if trace:
g.trace('(CursesGui) no editw')
return None
widget = self.curses_form._widgets__[editw]
if hasattr(widget, 'leo_wrapper'):
if trace:
g.trace('(CursesGui)', widget.leo_wrapper.__class__.__name__)
g.trace(g.callers())
return widget.leo_wrapper
g.trace('(CursesGui) ===== no leo_wrapper', widget)
# At present, HeadWrappers have no widgets.
return None
#@+node:ekr.20171128041805.1: *5* CGui.set_focus & helpers
set_focus_fail: List[Any] = [] # List of widgets
def set_focus(self, c, w):
"""Given a Leo wrapper, set focus to the underlying npyscreen widget."""
new_focus = False
if new_focus:
return self.NEW_set_focus(c, w)
return self.OLD_set_focus(c, w)
#@+node:ekr.20171204040620.1: *6* CGui.NEW_set_focus & helper
def NEW_set_focus(self, c, w):
"""
Given a Leo wrapper w, set focus to the underlying npyscreen widget.
"""
trace = 'focus' in g.app.debug
verbose = True # verbose trace of callers.
# Get the wrapper's npyscreen widget.
widget = getattr(w, 'widget', None)
if trace:
g.trace('widget', widget.__class__.__name__)
g.trace(g.callers(verbose=verbose))
if not widget:
g.trace('no widget', repr(w))
return
if not isinstance(widget, npyscreen.wgwidget.Widget):
g.trace('not an npyscreen.Widget', repr(w))
return
form = self.curses_form
# Find the widget to be edited
for i, widget2 in enumerate(form._widgets__):
if widget == widget2:
# if trace: g.trace('FOUND', i, widget.__class__.__name__)
self.switch_editing(i, widget)
return
for j, widget3 in enumerate(getattr(widget2, '_my_widgets', [])):
if widget == widget3 or repr(widget) == repr(widget3):
# if trace: g.trace('FOUND INNER', i, j, widget2.__class__.__name__)
self.switch_editing(i, widget)
return
if trace and widget not in self.set_focus_fail:
self.set_focus_fail.append(widget)
g.trace('Fail\n%r\n%r' % (widget, w))
#@+node:ekr.20171204040620.2: *7* CGui.switch_editing
def switch_editing(self, i, w):
"""Clear editing for *all* widgets and set form.editw to i"""
trace = 'focus' in g.app.debug
how = None # 'leo-set-focus'
form = self.curses_form
if i == form.editw:
if trace:
g.trace('NO CHANGE', i, w.__class__.__name__)
return
if trace:
g.trace('-----', i, w.__class__.__name__)
# Select the widget for editing.
form.editw = i
if 0:
# Inject 'leo-set-focus' into form.how_exited_handers
def switch_focus_callback(form=form, i=i, w=w):
g.trace(i, w.__class__.__name__)
g.trace(g.callers(verbose=True))
w.display()
form.display()
form.how_exited_handers[how] = switch_focus_callback
if 1:
# Clear editing for the editw widget:
w = form._widgets__[i]
# if trace: g.trace('editing', getattr(w, 'editing', None))
if hasattr(w, 'editing'):
w.editing = False
w.how_exited = how
if 1:
# Clear editing for all widgets.
for i, w1 in enumerate(form._widgets__):
# if trace: g.trace('CLEAR', w.__class__.__name__)
if getattr(w1, 'editing', None):
if trace:
g.trace('End EDITING', w1.__class__.__name__)
w1.editing = False
# w1.how_exited = how
w1.display()
for j, w2 in enumerate(getattr(w, '_my_widgets', [])):
# if trace: g.trace('CLEAR INNER', w.__class__.__name__)
if getattr(w2, 'editing', None):
if trace:
g.trace('END EDITING', w2.__class__.__name__)
w2.editing = False
# w2.how_exited = how
w2.display()
# Start editing the widget.
w.editing = True
w.display()
form.display()
w.edit()
# Does not return
#@+node:ekr.20171204100910.1: *6* CGui.OLD_set_focus
def OLD_set_focus(self, c, w):
"""Given a Leo wrapper, set focus to the underlying npyscreen widget."""
trace = 'focus' in g.app.debug
verbose = True # Full trace of callers.
# Get the wrapper's npyscreen widget.
widget = getattr(w, 'widget', None)
if trace:
g.trace('widget', widget.__class__.__name__)
g.trace(g.callers(verbose=verbose))
if not widget:
if trace or not w:
g.trace('no widget', repr(w))
return
if not isinstance(widget, npyscreen.wgwidget.Widget):
g.trace('not an npyscreen.Widget', repr(w))
return
form = self.curses_form
if 1: # Seems to cause problems.
# End editing in the previous form.
i = form.editw
w = form._widgets__[i]
if trace and verbose:
g.trace('CLEAR FOCUS', i, w.__class__.__name__)
if w:
w.editing = False
w.how_exited = EXITED_ESCAPE
w.display()
for i, widget2 in enumerate(form._widgets__):
if widget == widget2:
if trace:
g.trace('FOUND', i, widget)
form.editw = i
form.display()
return
for j, widget3 in enumerate(getattr(widget2, '_my_widgets', [])):
if widget == widget3 or repr(widget) == repr(widget3):
if trace:
g.trace('FOUND INNER', i, j, widget2)
form.editw = i
# Select the *outer* widget.
# Like BoxTitle.edit.
if 1:
# So weird.
widget2.editing = True
widget2.display()
# widget2.entry_widget.edit()
widget3.edit()
widget2.how_exited = widget3.how_exited
widget2.editing = False
widget2.display()
form.display()
return
if trace and widget not in self.set_focus_fail:
self.set_focus_fail.append(widget)
g.trace('Fail\n%r\n%r' % (widget, w))
#@+node:ekr.20170514060742.1: *4* CGui.Fonts
def getFontFromParams(self, family, size, slant, weight, defaultSize=12):
return None
#@+node:ekr.20170504052119.1: *4* CGui.isTextWrapper
def isTextWrapper(self, w):
"""Return True if w is a Text widget suitable for text-oriented commands."""
return w and getattr(w, 'supportsHighLevelInterface', None)
#@+node:ekr.20170504052042.1: *4* CGui.oops
def oops(self):
"""Ignore do-nothing methods."""
g.pr("CursesGui oops:", g.callers(4), "should be overridden in subclass")
#@+node:ekr.20170612063102.1: *4* CGui.put_help
def put_help(self, c, s, short_title):
"""Put a help message in a dialog."""
if not g.unitTesting:
utilNotify.notify_confirm(
message=s,
title=short_title or 'Help',
)
#@+node:ekr.20171130195357.1: *4* CGui.redraw_in_context
def redraw_in_context(self, c):
"""Redraw p in context."""
w = c.frame.tree.widget
c.expandAllAncestors(c.p)
g.app.gui.show_label(c)
w.values.clear_cache()
w.select_leo_node(c.p)
w.update(forceInit=True)
g.app.gui.curses_form.display()
#@+node:ekr.20171130181722.1: *4* CGui.repeatComplexCommand (commandName, event)
def repeatComplexCommand(self, c):
"""An override of the 'repeat-complex-command' command."""
trace = False and not g.unitTesting
k = c.k
if k.mb_history:
commandName = k.mb_history[0]
if trace:
g.trace(commandName)
g.printObj(k.mb_history)
k.masterCommand(
commandName=commandName,
event=KeyEvent(c, char='', event='', shortcut='', w=None),
func=None,
stroke=None,
)
else:
g.warning('no previous command')
#@+node:ekr.20171201084211.1: *4* CGui.set_minibuffer_label
def set_minibuffer_label(self, c, s):
"""Remember the minibuffer label."""
self.minibuffer_label = s
self.show_label(c)
#@+node:ekr.20171202092230.1: *4* CGui.show_find_success
def show_find_success(self, c, in_headline, insert, p):
"""Handle a successful find match."""
trace = False and not g.unitTesting
if in_headline:
if trace:
g.trace('HEADLINE', p.h)
c.frame.tree.widget.select_leo_node(p)
self.focus_to_head(c, p)
# Does not return.
else:
w = c.frame.body.widget
row, col = g.convertPythonIndexToRowCol(p.b, insert)
if trace:
g.trace('BODY ROW', row, p.h)
w.cursor_line = row
self.focus_to_body(c)
# Does not return.
#@+node:ekr.20171201081700.1: *4* CGui.show_label
def show_label(self, c):
"""
Set the minibuffer's label the value set by set_minibuffer_label.
"""
trace = False and not g.unitTesting
wrapper = c.frame.miniBufferWidget
if not wrapper:
return
box = wrapper.box
if not box:
return
s = self.minibuffer_label
if trace:
g.trace(repr(s))
box.name = 'Mini-buffer: %s' % s.strip()
box.update()
g.app.gui.curses_form.display()
#@+node:ekr.20171126192144.1: *4* CGui.startSearch
def startSearch(self, event):
c = event.get('c')
if not c:
return
# This does not work because the console doesn't show the message!
# if not isinstance(w, MiniBufferWrapper):
# g.es_print('Sorry, Ctrl-F must be run from the minibuffer.')
# return
fc = c.findCommands
ftm = c.frame.ftm
c.inCommand = False
c.inFindCommand = True
# A new flag.
fc.minibuffer_mode = True
if 0: # Allow hard settings, for tests.
table = (
('pattern_match', ftm.check_box_regexp, True),
)
for setting_name, w, val in table:
assert hasattr(fc, setting_name), setting_name
setattr(fc, setting_name, val)
w.setCheckState(val)
c.findCommands.startSearch(event)
options = fc.computeFindOptionsInStatusArea()
c.frame.statusLine.put(options)
self.focus_to_minibuffer(c)
# Does not return!
#@-others
#@+node:ekr.20170524124010.1: ** Leo widget classes
# Most are subclasses Leo's base gui classes.
# All classes have a "c" ivar.
#@+node:ekr.20170501024433.1: *3* class CoreBody (leoFrame.LeoBody)
class CoreBody(leoFrame.LeoBody):
"""
A class that represents curses body pane.
This is c.frame.body.
"""
def __init__(self, c):
super().__init__(frame=c.frame, parentFrame=None)
# Init the base class.
self.c = c
self.colorizer = leoFrame.NullColorizer(c)
self.widget = None
self.wrapper = None # Set in createCursesBody.
#@+node:ekr.20170419105852.1: *3* class CoreFrame (leoFrame.LeoFrame)
class CoreFrame(leoFrame.LeoFrame):
"""The LeoFrame when --gui=curses is in effect."""
#@+others
#@+node:ekr.20170501155347.1: *4* CFrame.birth
def __init__(self, c, title):
leoFrame.LeoFrame.instances += 1 # Increment the class var.
super().__init__(c, gui=g.app.gui)
# Init the base class.
assert c and self.c == c
c.frame = self # Bug fix: 2017/05/10.
self.log = CoreLog(c)
g.app.gui.log = self.log
self.title = title
# Standard ivars.
self.ratio = self.secondary_ratio = 0.5
# Widgets
self.top = TopFrame(c)
self.body = CoreBody(c)
self.menu = CoreMenu(c)
self.miniBufferWidget = None
# Set later.
self.statusLine = g.NullObject() # For unit tests.
assert self.tree is None, self.tree
self.tree = CoreTree(c)
# Official ivars...
# self.iconBar = None
# self.iconBarClass = None # self.QtIconBarClass
# self.initComplete = False # Set by initCompleteHint().
# self.minibufferVisible = True
# self.statusLineClass = None # self.QtStatusLineClass
#
# Config settings.
# self.trace_status_line = c.config.getBool('trace_status_line')
# self.use_chapters = c.config.getBool('use_chapters')
# self.use_chapter_tabs = c.config.getBool('use_chapter_tabs')
#
# self.set_ivars()
#
# "Official ivars created in createLeoFrame and its allies.
# self.bar1 = None
# self.bar2 = None
# self.f1 = self.f2 = None
# self.findPanel = None # Inited when first opened.
# self.iconBarComponentName = 'iconBar'
# self.iconFrame = None
# self.canvas = None
# self.outerFrame = None
# self.statusFrame = None
# self.statusLineComponentName = 'statusLine'
# self.statusText = None
# self.statusLabel = None
# self.top = None # This will be a class Window object.
# Used by event handlers...
# self.controlKeyIsDown = False # For control-drags
# self.isActive = True
# self.redrawCount = 0
# self.wantedWidget = None
# self.wantedCallbackScheduled = False
# self.scrollWay = None
#@+node:ekr.20170420163932.1: *5* CFrame.finishCreate
def finishCreate(self):
c = self.c
g.app.windowList.append(self)
ftm = StringFindTabManager(c)
c.findCommands.ftm = ftm
self.ftm = ftm
self.createFindTab()
self.createFirstTreeNode()
# Call the base-class method.
#@+node:ekr.20171128052121.1: *5* CFrame.createFindTab & helpers
def createFindTab(self):
"""Create a Find Tab in the given parent."""
# Like DynamicWindow.createFindTab.
ftm = self.ftm
assert ftm
self.create_find_findbox()
self.create_find_replacebox()
self.create_find_checkboxes()
# Official ivars (in addition to checkbox ivars).
self.leo_find_widget = None
ftm.init_widgets()
#@+node:ekr.20171128052121.4: *6* CFrame.create_find_findbox
def create_find_findbox(self):
"""Create the Find: label and text area."""
c = self.c
fc = c.findCommands
ftm = self.ftm
assert ftm
assert ftm.find_findbox is None
ftm.find_findbox = self.createLineEdit('findPattern', disabled=fc.expert_mode)
#@+node:ekr.20171128052121.5: *6* CFrame.create_find_replacebox
def create_find_replacebox(self):
"""Create the Replace: label and text area."""
c = self.c
fc = c.findCommands
ftm = self.ftm
assert ftm
assert ftm.find_replacebox is None
ftm.find_replacebox = self.createLineEdit('findChange', disabled=fc.expert_mode)
#@+node:ekr.20171128052121.6: *6* CFrame.create_find_checkboxes
def create_find_checkboxes(self):
"""Create check boxes and radio buttons."""
# c = self.c
ftm = self.ftm
def mungeName(kind, label):
# The returned value is the name of an ivar.
kind = 'check_box_' if kind == 'box' else 'radio_button_'
name = label.replace(' ', '_').replace('&', '').lower()
return '%s%s' % (kind, name)
d = {
'box': self.createCheckBox,
'rb': self.createRadioButton,
}
table = (
# First row.
('box', 'whole &Word'),
('rb', '&Entire outline'),
# Second row.
('box', '&Ignore case'),
('rb', '&Suboutline only'),
# Third row.
# ('box', 'wrap &Around'), # #1824.
('rb', '&Node only'),
# Fourth row.
('box', 'rege&Xp'),
('box', 'search &Headline'),
# Fifth row.
('box', 'mark &Finds'),
('box', 'search &Body'),
# Sixth row.
('box', 'mark &Changes'),
)
for kind, label in table:
name = mungeName(kind, label)
func = d.get(kind)
assert func
label = label.replace('&', '')
w = func(name, label)
assert getattr(ftm, name) is None
setattr(ftm, name, w)
#@+node:ekr.20171128053531.3: *6* CFrame.createCheckBox
def createCheckBox(self, name, label):
return leoGui.StringCheckBox(name, label)
#@+node:ekr.20171128053531.8: *6* CFrame.createLineEdit
def createLineEdit(self, name, disabled=True):
return leoGui.StringLineEdit(name, disabled)
#@+node:ekr.20171128053531.9: *6* CFrame.createRadioButton
def createRadioButton(self, name, label):
return leoGui.StringRadioButton(name, label)
#@+node:ekr.20170501161029.1: *4* CFrame.do nothings
def bringToFront(self):
pass
def contractPane(self, event=None):
pass
def deiconify(self):
pass
def destroySelf(self):
pass
def forceWrap(self, p):
pass
def get_window_info(self):
"""Return width, height, left, top."""
return 700, 500, 50, 50
def iconify(self):
pass
def lift(self):
pass
def getShortCut(self, *args, **kwargs):
return None
def getTitle(self):
return self.title
def minimizeAll(self, event=None):
pass
def oops(self):
"""Ignore do-nothing methods."""
g.pr("CoreFrame oops:", g.callers(4), "should be overridden in subclass")
def resizePanesToRatio(self, ratio, secondary_ratio):
"""Resize splitter1 and splitter2 using the given ratios."""
# self.divideLeoSplitter1(ratio)
# self.divideLeoSplitter2(secondary_ratio)
def resizeToScreen(self, event=None):
pass
def setInitialWindowGeometry(self):
pass
def setTitle(self, title):
self.title = g.toUnicode(title)
def setTopGeometry(self, w, h, x, y):
pass
def setWrap(self, p):
pass
def update(self, *args, **keys):
pass
#@+node:ekr.20170524144717.1: *4* CFrame.get_focus
def getFocus(self):
return g.app.gui.get_focus()
#@+node:ekr.20170522015906.1: *4* CFrame.pasteText (cursesGui2)
@frame_cmd('paste-text')
def pasteText(self, event=None, middleButton=False):
"""
Paste the clipboard into a widget.
If middleButton is True, support x-windows middle-mouse-button easter-egg.
"""
trace = False and not g.unitTesting
c, p, u = self.c, self.c.p, self.c.undoer
w = event and event.widget
if not isinstance(w, leoFrame.StringTextWrapper):
g.trace('not a StringTextWrapper', repr(w))
return
bunch = u.beforeChangeBody(p)
wname = c.widget_name(w)
i, j = w.getSelectionRange()
# Returns insert point if no selection.
s = g.app.gui.getTextFromClipboard()
s = g.toUnicode(s)
if trace:
g.trace('wname', wname, 'len(s)', len(s))
single_line = any(wname.startswith(z) for z in ('head', 'minibuffer'))
if single_line:
# Strip trailing newlines so the truncation doesn't cause confusion.
while s and s[-1] in ('\n', '\r'):
s = s[:-1]
# Update the widget.
if i != j:
w.delete(i, j)
w.insert(i, s)
if wname.startswith('body'):
p.v.b = w.getAllText()
u.afterChangeBody(p, 'Paste', bunch)
elif wname.startswith('head'):
c.frame.tree.onHeadChanged(c.p, s=w.getAllText(), undoType='Paste')
# New for Curses gui.
OnPasteFromMenu = pasteText
#@-others
#@+node:ekr.20170419143731.1: *3* class CoreLog (leoFrame.LeoLog)
class CoreLog(leoFrame.LeoLog):
"""
A class that represents curses log pane.
This is c.frame.log.
"""
#@+others
#@+node:ekr.20170419143731.4: *4* CLog.__init__
def __init__(self, c):
"""Ctor for CLog class."""
super().__init__(frame=None, parentFrame=None)
self.c = c
self.enabled = True
# Required by Leo's core.
self.isNull = False
# Required by Leo's core.
self.widget = None
# The npyscreen log widget. Queue all output until set.
# Set in CApp.main.
#
self.contentsDict = {}
# Keys are tab names. Values are widgets.
self.logDict = {}
# Keys are tab names text widgets. Values are the widgets.
self.tabWidget = None
#@+node:ekr.20170419143731.7: *4* CLog.clearLog
@log_cmd('clear-log')
def clearLog(self, event=None):
"""Clear the log pane."""
#@+node:ekr.20170420035717.1: *4* CLog.enable/disable
def disable(self):
self.enabled = False
def enable(self, enabled=True):
self.enabled = enabled
#@+node:ekr.20170420041119.1: *4* CLog.finishCreate
def finishCreate(self):
"""CoreLog.finishCreate."""
#@+node:ekr.20170513183826.1: *4* CLog.isLogWidget
def isLogWidget(self, w):
return w == self or w in list(self.contentsDict.values())
#@+node:ekr.20170513184115.1: *4* CLog.orderedTabNames
def orderedTabNames(self, LeoLog=None): # Unused: LeoLog
"""Return a list of tab names in the order in which they appear in the QTabbedWidget."""
return []
# w = self.tabWidget
#return [w.tabText(i) for i in range(w.count())]
#@+node:ekr.20170419143731.15: *4* CLog.put
def put(self, s, color=None, tabName='Log', from_redirect=False):
"""All output to the log stream eventually comes here."""
c, w = self.c, self.widget
if not c or not c.exists or not w:
# logging.info('CLog.put: no c: %r' % s)
return
assert isinstance(w, npyscreen.MultiLineEditable), repr(w)
# Fix #508: Part 1: Handle newlines correctly.
lines = s.split('\n')
for line in lines:
w.values.append(line)
# Fix #508: Part 2: Scroll last line into view.
w.cursor_line += len(lines)
w.start_display_at += len(lines)
w.update()
#@+node:ekr.20170419143731.16: *4* CLog.putnl
def putnl(self, tabName='Log'):
"""Put a newline to the Qt log."""
# This is not called normally.
# print('CLog.put: %s' % g.callers())
if g.app.quitting:
return
#@-others
#@+node:ekr.20170419111515.1: *3* class CoreMenu (leoMenu.LeoMenu)
class CoreMenu(leoMenu.LeoMenu):
def __init__(self, c):
dummy_frame = g.Bunch(c=c)
super().__init__(dummy_frame)
self.c = c
self.d = {}
def oops(self):
"""Ignore do-nothing methods."""
# g.pr("CoreMenu oops:", g.callers(4), "should be overridden in subclass")
#@+node:ekr.20170501024424.1: *3* class CoreTree (leoFrame.LeoTree)
class CoreTree(leoFrame.LeoTree):
"""
A class that represents curses tree pane.
This is the c.frame.tree instance.
"""
#@+others
#@+node:ekr.20170511111242.1: *4* CTree.ctor
class DummyFrame:
def __init__(self, c):
self.c = c
def __init__(self, c):
dummy_frame = self.DummyFrame(c)
super().__init__(dummy_frame)
# Init the base class.
assert self.c
assert not hasattr(self, 'widget')
self.redrawCount = 0 # For unit tests.
self.widget = None
# A LeoMLTree set by CGui.createCursesTree.
# self.setConfigIvars()
#
# Status flags, for busy()
self.contracting = False
self.expanding = False
self.redrawing = False
self.selecting = False
#@+node:ekr.20170511094217.1: *4* CTree.Drawing
#@+node:ekr.20170511094217.3: *5* CTree.redraw
def redraw(self, p=None, scroll=True, forceDraw=False):
"""
Redraw all visible nodes of the tree.
Preserve the vertical scrolling unless scroll is True.
"""
trace = False and not g.unitTesting
if g.unitTesting:
return # There is no need. At present, the tests hang.
if trace:
g.trace(g.callers())
if self.widget and not self.busy():
self.redrawCount += 1 # To keep a unit test happy.
self.widget.update()
# Compatibility
full_redraw = redraw
redraw_now = redraw
repaint = redraw
#@+node:ekr.20170511100356.1: *5* CTree.redraw_after...
def redraw_after_contract(self, p=None):
self.redraw(p, scroll=False)
def redraw_after_expand(self, p=None):
self.redraw(p)
def redraw_after_head_changed(self):
self.redraw()
def redraw_after_icons_changed(self):
self.redraw()
def redraw_after_select(self, p=None):
"""Redraw the entire tree when an invisible node is selected."""
# Prevent the selecting lockout from disabling the redraw.
oldSelecting = self.selecting
self.selecting = False
try:
if not self.busy():
self.redraw(p=p, scroll=False)
finally:
self.selecting = oldSelecting
# Do *not* call redraw_after_select here!
#@+node:ekr.20170511104032.1: *4* CTree.error
def error(self, s):
if not g.unitTesting:
g.trace('LeoQtTree Error: %s' % (s), g.callers())
#@+node:ekr.20170511104533.1: *4* CTree.Event handlers
#@+node:ekr.20170511104533.10: *5* CTree.busy
def busy(self):
"""Return True (actually, a debugging string)
if any lockout is set."""
trace = False
table = ('contracting', 'expanding', 'redrawing', 'selecting')
kinds = ','.join([z for z in table if getattr(self, z)])
if kinds and trace:
g.trace(kinds)
return kinds # Return the string for debugging
#@+node:ekr.20170511104533.12: *5* CTree.onHeadChanged (cursesGui2)
# Tricky code: do not change without careful thought and testing.
def onHeadChanged(self, p, s=None, undoType='Typing'):
"""
Officially change a headline.
This is c.frame.tree.onHeadChanged.
"""
trace = False
c, u = self.c, self.c.undoer
if not c.frame.body.wrapper:
if trace:
g.trace('NO wrapper')
return # Startup.
w = self.edit_widget(p)
if not w:
if trace:
g.trace('****** no w for p: %s', repr(p))
return
ch = '\n' # New in 4.4: we only report the final keystroke.
if s is None:
s = w.getAllText()
# if trace: g.trace('CoreTree: %r ==> %r' % (p and p.h, s))
#@+<< truncate s if it has multiple lines >>
#@+node:ekr.20170511104533.13: *6* << truncate s if it has multiple lines >>
# Remove trailing newlines before warning of truncation.
while s and s[-1] == '\n':
s = s[:-1]
# Warn if there are multiple lines.
i = s.find('\n')
if i > -1:
s = s[:i]
# if s != oldHead:
# g.warning("truncating headline to one line")
limit = 1000
if len(s) > limit:
s = s[:limit]
# if s != oldHead:
# g.warning("truncating headline to", limit, "characters")
#@-<< truncate s if it has multiple lines >>
# Make the change official, but undo to the *old* revert point.
changed = s != p.h
if not changed:
return # Leo 6.4: only call hooks if the headline has changed.
if trace:
g.trace('changed', changed, 'new', repr(s))
if g.doHook("headkey1", c=c, p=p, ch=ch, changed=changed):
return # The hook claims to have handled the event.
#
# Handle undo
undoData = u.beforeChangeHeadline(p)
p.initHeadString(s) # Change p.h *after* calling the undoer's before method.
if not c.changed:
c.setChanged()
# New in Leo 4.4.5: we must recolor the body because
# the headline may contain directives.
# c.frame.scanForTabWidth(p)
# c.frame.body.recolor(p)
p.setDirty()
u.afterChangeHeadline(p, undoType, undoData)
# if changed:
# c.redraw_after_head_changed()
# Fix bug 1280689: don't call the non-existent c.treeEditFocusHelper
g.doHook("headkey2", c=c, p=p, ch=ch, changed=changed)
#@+node:ekr.20170511104121.1: *4* CTree.Scroll bars
#@+node:ekr.20170511104121.2: *5* Ctree.getScroll
def getScroll(self):
"""Return the hPos,vPos for the tree's scrollbars."""
return 0, 0
#@+node:ekr.20170511104121.4: *5* Ctree.setH/VScroll
def setHScroll(self, hPos):
pass
# w = self.widget
# hScroll = w.horizontalScrollBar()
# hScroll.setValue(hPos)
def setVScroll(self, vPos):
pass
# w = self.widget
# vScroll = w.verticalScrollBar()
# vScroll.setValue(vPos)
#@+node:ekr.20170511105355.1: *4* CTree.Selecting & editing
#@+node:ekr.20170511105355.4: *5* CTree.edit_widget
def edit_widget(self, p):
"""Returns the edit widget for position p."""
wrapper = HeadWrapper(c=self.c, name='head', p=p)
return wrapper
#@+node:ekr.20170511095353.1: *5* CTree.editLabel (cursesGui2) (not used)
def editLabel(self, p, selectAll=False, selection=None):
"""Start editing p's headline."""
return None, None
#@+node:ekr.20170511105355.7: *5* CTree.endEditLabel (cursesGui2)
def endEditLabel(self):
"""Override LeoTree.endEditLabel.
End editing of the presently-selected headline.
"""
c = self.c
p = c.currentPosition()
self.onHeadChanged(p)
#@+node:ekr.20170511105355.8: *5* CTree.getSelectedPositions (called from Leo's core)
def getSelectedPositions(self):
"""This can be called from Leo's core."""
# Not called from unit tests.
return [self.c.p]
#@+node:ekr.20170511105355.9: *5* CTree.setHeadline
def setHeadline(self, p, s):
"""Force the actual text of the headline widget to p.h."""
trace = False and not g.unitTesting
# This is used by unit tests to force the headline and p into alignment.
if not p:
if trace:
g.trace('*** no p')
return
# Don't do this here: the caller should do it.
# p.setHeadString(s)
e = self.edit_widget(p)
assert isinstance(e, HeadWrapper), repr(e)
e.setAllText(s)
if trace:
g.trace(e)
#@+node:ekr.20170523115818.1: *5* CTree.set_body_text_after_select
def set_body_text_after_select(self, p, old_p):
"""Set the text after selecting a node."""
c = self.c
wrapper = c.frame.body.wrapper
widget = c.frame.body.widget
c.setCurrentPosition(p)
# Important: do this *before* setting text,
# so that the colorizer will have the proper c.p.
s = p.v.b
wrapper.setAllText(s)
widget.values = g.splitLines(s)
widget.update()
# Now done after c.p has been changed.
# p.restoreCursorAndScroll()
#@-others
#@+node:ekr.20171129200050.1: *3* class CoreStatusLine
class CoreStatusLine:
"""A do-nothing status line."""
def __init__(self, c, parentFrame):
"""Ctor for CoreStatusLine class."""
# g.trace('(CoreStatusLine)', c)
self.c = c
self.enabled = False
self.parentFrame = parentFrame
self.textWidget = None
# The official ivars.
c.frame.statusFrame = None
c.frame.statusLabel = None
c.frame.statusText = None
#@+others
#@-others
#@+node:ekr.20170502093200.1: *3* class TopFrame
class TopFrame:
"""A representation of c.frame.top."""
def __init__(self, c):
self.c = c
def select(self, *args, **kwargs):
pass
def findChild(self, *args, **kwargs):
# Called by nested_splitter.py.
return g.NullObject()
def finishCreateLogPane(self, *args, **kwargs):
pass
#@+node:ekr.20170524124449.1: ** Npyscreen classes
# These are subclasses of npyscreen base classes.
# These classes have "leo_c" ivars.
#@+node:ekr.20170420054211.1: *3* class LeoApp (npyscreen.NPSApp)
class LeoApp(npyscreen.NPSApp):
"""
The *anonymous* npyscreen application object, created from
CGui.runMainLoop. This is *not* g.app.
"""
# No ctor needed.
# def __init__(self):
# super().__init__()
def main(self):
"""
Called automatically from the ctor.
Create and start Leo's singleton npyscreen window.
"""
g.app.gui.run()
#@+node:ekr.20170526054750.1: *3* class LeoBody (npyscreen.MultiLineEditable)
class LeoBody(npyscreen.MultiLineEditable):
continuation_line = "- more -" # value of contination line.
_contained_widgets = LeoBodyTextfield
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.leo_box = None
self.leo_c = None
self.leo_wrapper = None
self.set_handlers()
# createCursesBody sets the leo_box and leo_c ivars.
#@+others
#@+node:ekr.20170604183231.1: *4* LeoBody handlers
#@+node:ekr.20170526114040.4: *5* LeoBody.h_cursor_line_down
def h_cursor_line_down(self, ch_i):
"""
From MultiLine.h_cursor_line_down. Never exit.
"""
# pylint: disable=access-member-before-definition
#
# Reset editing mode.
self.set_box_name('Body Pane')
# Boilerplate...
i = self.cursor_line
j = self.start_display_at
self.cursor_line = min(len(self.values) - 1, i + 1)
if self._my_widgets[i - j].task == self.continuation_line:
if self.slow_scroll:
self.start_display_at += 1
else:
self.start_display_at = self.cursor_line
#@+node:ekr.20170526114040.5: *5* LeoBody.h_cursor_line_up
def h_cursor_line_up(self, ch_i):
"""From MultiLine.h_cursor_line_up. Never exit here."""
# Reset editing mode.
self.set_box_name('Body Pane')
self.cursor_line = max(0, self.cursor_line - 1)
#@+node:ekr.20170604181755.1: *5* LeoBody.h_exit_down
def h_exit_down(self, ch_i):
"""Called when user leaves the widget to the next widget"""
if ch_i in (curses.ascii.CR, curses.ascii.NL):
return False
self.set_box_name('Body Pane')
if not self._test_safe_to_exit():
return False
self.editing = False
self.how_exited = EXITED_DOWN
return None
#@+node:ekr.20170604181821.1: *5* LeoBody.h_exit_up
def h_exit_up(self, ch_i):
self.set_box_name('Body Pane')
if not self._test_safe_to_exit():
return False
# Called when the user leaves the widget to the previous widget
self.editing = False
self.how_exited = EXITED_UP
return None
#@+node:ekr.20170526114452.2: *5* LeoBody.h_edit_cursor_line_value
def h_edit_cursor_line_value(self, ch_i):
"""From MultiLineEditable.h_edit_cursor_line_value"""
self.set_box_name('Body Pane (Editing)')
continue_line = self.edit_cursor_line_value()
if continue_line and self.CONTINUE_EDITING_AFTER_EDITING_ONE_LINE:
self._continue_editing()
#@+node:ekr.20170604185028.1: *4* LeoBody.delete_line_value
def delete_line_value(self, ch_i=None):
c = self.leo_c
if self.values:
del self.values[self.cursor_line]
self.display()
# #1224:
c.p.b = ''.join(self.values)
#@+node:ekr.20170602103122.1: *4* LeoBody.make_contained_widgets
def make_contained_widgets(self):
"""
LeoBody.make_contained_widgets.
Make widgets and inject the leo_parent ivar for later access to leo_c.
"""
# pylint: disable=no-member
trace_widgets = False
self._my_widgets = []
height = self.height // self.__class__._contained_widget_height
# g.trace(self.__class__.__name__, height)
for h in range(height):
self._my_widgets.append(
self._contained_widgets(
self.parent,
rely=(h * self._contained_widget_height) + self.rely,
relx=self.relx,
max_width=self.width,
max_height=self.__class__._contained_widget_height
))
# Inject leo_parent ivar so the contained widgets can get leo_c later.
for w in self._my_widgets:
w.leo_parent = self
if trace and trace_widgets:
g.printList(self._my_widgets)
g.printList(['value: %r' % (z.value) for z in self._my_widgets])
#@+node:ekr.20170604073733.1: *4* LeoBody.set_box_name
def set_box_name(self, name):
"""Update the title of the Form surrounding the Leo Body."""
box = self.leo_box
box.name = name
box.update()
#@+node:ekr.20170526064136.1: *4* LeoBody.set_handlers
#@@nobeautify
def set_handlers(self):
"""LeoBody.set_handlers."""
# pylint: disable=no-member
self.handlers = {
# From InputHandler...
curses.KEY_BTAB: self.h_exit_up,
curses.ascii.TAB: self.h_exit_down,
curses.ascii.ESC: self.h_exit_escape,
curses.KEY_MOUSE: self.h_exit_mouse,
# From MultiLine...
curses.KEY_DOWN: self.h_cursor_line_down,
curses.KEY_END: self.h_cursor_end,
curses.KEY_HOME: self.h_cursor_beginning,
curses.KEY_NPAGE: self.h_cursor_page_down,
curses.KEY_PPAGE: self.h_cursor_page_up,
curses.KEY_UP: self.h_cursor_line_up,
# From MultiLineEditable...
# ord('i'): self.h_insert_value,
# ord('o'): self.h_insert_next_line,
# New bindings...
ord('d'): self.delete_line_value,
ord('e'): self.h_edit_cursor_line_value,
}
# self.dump_handlers()
#@+node:ekr.20170606100707.1: *4* LeoBody.update_body (cursesGui2)
def update_body(self, ins, s):
"""
Update self.values and p.b and vnode ivars after the present line changes.
"""
# pylint: disable=no-member,access-member-before-definition
trace = False and not g.unitTesting
c = self.leo_c
p, u, v = c.p, c.undoer, c.p.v
undoType = 'update-body'
bunch = u.beforeChangeBody(p)
i = self.cursor_line
wrapper = c.frame.body.wrapper
assert isinstance(wrapper, BodyWrapper), repr(wrapper)
lines = self.values
if trace:
g.trace(i, len(lines), s.endswith('\n'), repr(s))
head = lines[:i]
tail = lines[i + 1 :]
if i < len(lines):
if not s.endswith('\n'):
s = s + '\n'
aList = head + [s] + tail
self.values = aList
c.p.b = ''.join(aList)
v.selectionLength = 0
v.selectionStart = ins
wrapper.ins = ins
wrapper.sel = ins, ins
u.afterChangeBody(p, undoType, bunch)
elif i == len(lines):
aList = head + [s]
self.values = aList
c.p.b = ''.join(aList)
v.selectionLength = 0
v.selectionStart = ins
wrapper.ins = ins
wrapper.sel = ins, ins
u.afterChangeBody(p, undoType, bunch)
else:
g.trace('Can not happen', i, len(lines), repr(s))
v.selectionLength = 0
v.selectionStart = 0
if g.splitLines(c.p.b) != self.values:
g.trace('self.values')
g.printList(self.values)
g.trace('g.splitLines(c.p.b)')
g.printList(g.splitLines(c.p.b))
#@-others
#@+node:ekr.20170603103946.1: *3* class LeoLog (npyscreen.MultiLineEditable)
class LeoLog(npyscreen.MultiLineEditable):
continuation_line = "- more -" # value of contination line.
_contained_widgets = LeoLogTextfield
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.set_handlers()
self.leo_box = None
self.leo_c = None
# createCursesLog sets the leo_c and leo_box ivars.
#@+others
#@+node:ekr.20170604184928.2: *4* LeoLog.delete_line_value
def delete_line_value(self, ch_i=None):
if self.values:
del self.values[self.cursor_line]
self.display()
#@+node:ekr.20170604183417.1: *4* LeoLog handlers
#@+node:ekr.20170603103946.32: *5* LeoLog.h_cursor_line_down
def h_cursor_line_down(self, ch_i):
"""
From MultiLine.h_cursor_line_down. Never exit.
"""
# pylint: disable=no-member,access-member-before-definition
trace = False and not g.unitTesting
self.set_box_name('Log Pane')
i = self.cursor_line
j = self.start_display_at
n = len(self.values)
n2 = len(self._my_widgets)
# Scroll only if there are more lines left.
if i < n - 2:
# Update self.cursor_line
self.cursor_line = i2 = max(0, min(i + 1, n - 1))
# Update self.start_display_at.
if self._my_widgets[i - j].task == self.continuation_line:
self.start_display_at = min(j, max(i2 + 1, n2 - 1))
if trace:
g.trace('n: %s, start: %s, line: %s' % (
n, self.start_display_at, self.cursor_line))
#@+node:ekr.20170603103946.31: *5* LeoLog.h_cursor_line_up
def h_cursor_line_up(self, ch_i):
"""From MultiLine.h_cursor_line_up. Never exit here."""
self.set_box_name('Log Pane')
self.cursor_line = max(0, self.cursor_line - 1)
#@+node:ekr.20170604061933.4: *5* LeoLog.h_edit_cursor_line_value
def h_edit_cursor_line_value(self, ch_i):
"""From MultiLineEditable.h_edit_cursor_line_value"""
self.set_box_name('Log Pane (Editing)')
continue_line = self.edit_cursor_line_value()
if continue_line and self.CONTINUE_EDITING_AFTER_EDITING_ONE_LINE:
self._continue_editing()
#@+node:ekr.20170604113733.2: *5* LeoLog.h_exit_down
def h_exit_down(self, ch_i):
"""Called when user leaves the widget to the next widget"""
trace = False and not g.unitTesting
if ch_i in (curses.ascii.CR, curses.ascii.NL):
return False
if trace:
g.trace('(LeoLog) safe:', self._test_safe_to_exit())
g.trace(g.callers())
self.set_box_name('Log Pane')
if not self._test_safe_to_exit():
return False
self.editing = False
self.how_exited = EXITED_DOWN
return None
#@+node:ekr.20170604113733.4: *5* LeoLog.h_exit_up
def h_exit_up(self, ch_i):
self.set_box_name('Log Pane')
if not self._test_safe_to_exit():
return False
# Called when the user leaves the widget to the previous widget
self.editing = False
self.how_exited = EXITED_UP
return None
#@+node:ekr.20170603103946.34: *4* LeoLog.make_contained_widgets
def make_contained_widgets(self):
"""
LeoLog.make_contained_widgets.
Make widgets and inject the leo_parent ivar for later access to leo_c.
"""
# pylint: disable=no-member
trace = False
trace_widgets = False
self._my_widgets = []
height = self.height // self.__class__._contained_widget_height
if trace:
g.trace(self.__class__.__name__, height)
for h in range(height):
self._my_widgets.append(
self._contained_widgets(
self.parent,
rely=(h * self._contained_widget_height) + self.rely,
relx=self.relx,
max_width=self.width,
max_height=self.__class__._contained_widget_height
))
# Inject leo_parent ivar so the contained widgets can get leo_c later.
for w in self._my_widgets:
w.leo_parent = self
if trace and trace_widgets:
g.printList(self._my_widgets)
g.printList(['value: %r' % (z.value) for z in self._my_widgets])
#@+node:ekr.20170604073322.1: *4* LeoLog.set_box_name
def set_box_name(self, name):
"""Update the title of the Form surrounding the Leo Log."""
box = self.leo_box
box.name = name
box.update()
#@+node:ekr.20170603103946.33: *4* LeoLog.set_handlers
def set_handlers(self):
"""LeoLog.set_handlers."""
# pylint: disable=no-member
self.handlers = {
# From InputHandler...
curses.KEY_BTAB: self.h_exit_up,
curses.KEY_MOUSE: self.h_exit_mouse,
curses.ascii.CR: self.h_exit_down,
curses.ascii.ESC: self.h_exit_escape,
curses.ascii.NL: self.h_exit_down,
curses.ascii.TAB: self.h_exit_down,
# From MultiLine...
curses.KEY_DOWN: self.h_cursor_line_down,
curses.KEY_END: self.h_cursor_end,
curses.KEY_HOME: self.h_cursor_beginning,
curses.KEY_NPAGE: self.h_cursor_page_down,
curses.KEY_PPAGE: self.h_cursor_page_up,
curses.KEY_UP: self.h_cursor_line_up,
# From MultiLineEditable...
# ord('i'): self.h_insert_value,
# ord('o'): self.h_insert_next_line,
# New bindings...
ord('d'): self.delete_line_value,
ord('e'): self.h_edit_cursor_line_value,
}
# dump_handlers(self)
#@+node:ekr.20170708181422.1: *4* LeoLog.firstScroll
def firstScroll(self):
"""Scroll the log pane so the last lines are in view."""
# Fix #508: Part 0.
n = len(self.values)
self.cursor_line = max(0, n - 2)
self.start_display_at = max(0, n - len(self._my_widgets))
self.update()
#@-others
#@+node:ekr.20170507194035.1: *3* class LeoForm (npyscreen.Form)
class LeoForm(npyscreen.Form):
OK_BUTTON_TEXT = 'Quit Leo'
OKBUTTON_TYPE = QuitButton
how_exited = None
def display(self, *args, **kwargs):
changed = any(z.c.isChanged() for z in g.app.windowList)
c = g.app.log.c
self.name = 'Welcome to Leo: %s%s' % (
'(changed) ' if changed else '',
c.fileName() if c else '')
super().display(*args, **kwargs)
#@+node:ekr.20170510092721.1: *3* class LeoMiniBuffer (npyscreen.Textfield)
class LeoMiniBuffer(npyscreen.Textfield):
"""An npyscreen class representing Leo's minibuffer, with binding."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.leo_c = None # Set later
self.leo_wrapper = None # Set later.
self.leo_completion_index = 0
self.leo_completion_list = []
self.leo_completion_prefix = ''
self.set_handlers()
#@+others
#@+node:ekr.20170510172335.1: *4* LeoMiniBuffer.Handlers
#@+node:ekr.20171201054825.1: *5* LeoMiniBuffer.do_tab_completion
def do_tab_completion(self):
"""Perform tab completion."""
trace = False and not g.unitTesting
c = self.leo_c
command = self.value
i = self.leo_completion_index
if trace:
g.trace('command: %r prefix: %r' % (command, self.leo_completion_prefix))
# Restart the completions if necessary.
if not command.startswith(self.leo_completion_prefix):
i = 0
if i == 0:
# Compute new completions.
self.leo_completion_prefix = command
command_list = sorted(c.k.c.commandsDict.keys())
tab_list, common_prefix = g.itemsMatchingPrefixInList(command, command_list)
self.leo_completion_list = tab_list
if trace:
g.printObj(tab_list)
# Update the index and the widget.
if self.leo_completion_list:
tab_list = self.leo_completion_list
self.value = tab_list[i]
i = 0 if i + 1 >= len(tab_list) else i + 1
self.leo_completion_index = i
self.update()
elif trace:
g.trace('no completions for', command)
#@+node:ekr.20170510095136.2: *5* LeoMiniBuffer.h_cursor_beginning
def h_cursor_beginning(self, ch):
self.cursor_position = 0
#@+node:ekr.20170510095136.3: *5* LeoMiniBuffer.h_cursor_end
def h_cursor_end(self, ch):
self.cursor_position = len(self.value)
#@+node:ekr.20170510095136.4: *5* LeoMiniBuffer.h_cursor_left
def h_cursor_left(self, ch):
self.cursor_position = max(0, self.cursor_position - 1)
#@+node:ekr.20170510095136.5: *5* LeoMiniBuffer.h_cursor_right
def h_cursor_right(self, ch):
self.cursor_position = min(len(self.value), self.cursor_position + 1)
#@+node:ekr.20170510095136.6: *5* LeoMiniBuffer.h_delete_left
def h_delete_left(self, ch):
n = self.cursor_position
s = self.value
if n == 0:
# Delete the character under the cursor.
self.value = s[1:]
else:
# Delete the character to the left of the cursor
self.value = s[: n - 1] + s[n:]
self.cursor_position -= 1
#@+node:ekr.20171201053817.1: *5* LeoMiniBuffer.h_exit_down
def h_exit_down(self, ch):
"""LeoMiniBuffer.h_exit_down. Override InputHandler.h_exit_down."""
trace = False and not g.unitTesting
c = self.leo_c
if trace:
g.trace('(LeoMiniBuffer)', repr(ch))
if c and self.value.strip():
self.do_tab_completion()
else:
# Restart completion cycling.
self.leo_completion_index = 0
# The code in InputHandler.h_exit_down.
if not self._test_safe_to_exit():
return False
self.editing = False
self.how_exited = EXITED_DOWN
return None
#@+node:ekr.20170510095136.7: *5* LeoMiniBuffer.h_insert
def h_insert(self, ch):
n = self.cursor_position + 1
s = self.value
self.value = s[:n] + chr(ch) + s[n:]
self.cursor_position += 1
#@+node:ekr.20170510100003.1: *5* LeoMiniBuffer.h_return (executes command) (complex kwargs!)
def h_return(self, ch):
"""
Handle the return key in the minibuffer.
Send the contents to k.masterKeyHandler.
"""
c = self.leo_c
k = c.k
val = self.value.strip()
self.value = ''
self.update()
# g.trace('===== inState: %r val: %r' % (k.inState(), val))
commandName = val
c.frame.tree.set_status_line(c.p)
# This may be changed by the command.
if k.inState():
# Handle the key.
k.w = self.leo_wrapper
k.arg = val
g.app.gui.curses_gui_arg = val
k.masterKeyHandler(
event=KeyEvent(c, char='\n', event='', shortcut='\n', w=None))
g.app.gui.curses_gui_arg = None
k.clearState()
elif commandName == 'repeat-complex-command':
g.app.gui.repeatComplexCommand(c)
else:
# All other alt-x command
event = KeyEvent(c, char='', event='', shortcut='', w=None)
c.doCommandByName(commandName, event)
# Support repeat-complex-command.
c.setComplexCommand(commandName=commandName)
c.redraw()
# Do a full redraw, with c.p as the first visible node.
# g.trace('----- after command')
g.app.gui.redraw_in_context(c)
#@+node:ekr.20170510094104.1: *5* LeoMiniBuffer.set_handlers
def set_handlers(self):
# pylint: disable=no-member
# Override *all* other complex handlers.
self.complex_handlers = [
(curses.ascii.isprint, self.h_insert),
]
self.handlers.update({
# All other keys are passed on.
# curses.ascii.TAB: self.h_exit_down,
# curses.KEY_BTAB: self.h_exit_up,
curses.ascii.NL: self.h_return,
curses.ascii.CR: self.h_return,
curses.KEY_HOME: self.h_cursor_beginning, # 262
curses.KEY_END: self.h_cursor_end, # 358.
curses.KEY_LEFT: self.h_cursor_left,
curses.KEY_RIGHT: self.h_cursor_right,
curses.ascii.BS: self.h_delete_left,
curses.KEY_BACKSPACE: self.h_delete_left,
})
#@-others
#@+node:ekr.20171129194909.1: *3* class LeoStatusLine (npyscreen.Textfield)
class LeoStatusLine(npyscreen.Textfield):
"""An npyscreen class representing Leo's status line"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# These are injected later.
self.leo_c = None
self.leo_wrapper = None
# Use the default handlers.
# self.set_handlers()
#@+others
#@-others
#@+node:ekr.20170506035146.1: *3* class LeoMLTree (npyscreen.MLTree, object)
class LeoMLTree(npyscreen.MLTree):
# pylint: disable=used-before-assignment
_contained_widgets = LeoTreeLine
continuation_line = "- more -" # value of contination line.
# Note: The startup sequence sets leo_c and the value property/ivar.
#@+others
#@+node:ekr.20170510171826.1: *4* LeoMLTree.Entries
#@+node:ekr.20170506044733.6: *5* LeoMLTree.delete_line
def delete_line(self):
trace = False
trace_values = True
node = self.values[self.cursor_line]
assert isinstance(node, LeoTreeData), repr(node)
if trace:
g.trace('before', node.content)
if trace_values:
self.dump_values()
if native:
p = node.content
assert p and isinstance(p, leoNodes.Position), repr(p)
if p.hasParent() or p.hasNext() or p.hasBack():
p.doDelete()
self.values.clear_cache()
else:
g.trace('Can not delete the last top-level node')
return
else:
parent = node.get_parent()
grand_parent = parent and parent._parent
if not grand_parent and len(parent._children) == 1:
g.trace('Can not delete the last top-level node')
return
# Remove node and all its descendants.
i = self.cursor_line
nodes = [(i, node)]
j = i + 1
while j < len(self.values):
node2 = self.values[j]
if node.is_ancestor_of(node2):
nodes.append((j, node2),)
j += 1
else:
break
for j, node2 in reversed(nodes):
del self.values[j]
# Update the parent.
parent._children = [z for z in parent._children if z != node]
# Clearing these caches suffice to do a proper redraw
self._last_values = None
self._last_value = None
if trace and trace_values:
g.trace('after')
self.dump_values()
self.display()
# This is widget.display:
# (when not self.hidden)
#self.update()
# LeoMLTree.update or MultiLine.update
# self.parent.refresh()
# LeoForm.refresh
#@+node:ekr.20170507171518.1: *5* LeoMLTree.dump_code/values/widgets
def dump_code(self, code):
d = {
-2: 'left', -1: 'up', 1: 'down', 2: 'right',
127: 'escape', 130: 'mouse',
}
return d.get(code) or 'unknown how_exited: %r' % code
def dump_values(self):
def info(z):
return '%15s: %s' % (z._parent.get_content(), z.get_content())
g.printList([info(z) for z in self.values])
def dump_widgets(self):
def info(z):
return '%s.%s' % (id(z), z.__class__.__name__)
g.printList([info(z) for z in self._my_widgets])
#@+node:ekr.20170506044733.4: *5* LeoMLTree.edit_headline
def edit_headline(self):
trace = False and not g.unitTesting
assert self.values, g.callers()
try:
active_line = self._my_widgets[(self.cursor_line - self.start_display_at)]
assert isinstance(active_line, LeoTreeLine)
if trace:
g.trace('LeoMLTree.active_line: %r' % active_line)
except IndexError:
# pylint: disable=pointless-statement
self._my_widgets[0]
# Does this have something to do with weakrefs?
self.cursor_line = 0
self.insert_line()
return True
active_line.highlight = False
active_line.edit()
if native:
self.values.clear_cache()
else:
try:
# pylint: disable=unsupported-assignment-operation
self.values[self.cursor_line] = active_line.value
except IndexError:
self.values.append(active_line.value)
if not self.cursor_line:
self.cursor_line = 0
self.cursor_line = len(self.values) - 1
self.reset_display_cache()
self.display()
return True
#@+node:ekr.20170523113530.1: *5* LeoMLTree.get_nth_visible_position
def get_nth_visible_position(self, n):
"""Return the n'th visible position."""
c = self.leo_c
limit, junk = c.visLimit()
p = limit.copy() if limit else c.rootPosition()
i = 0
while p:
if i == n:
return p
p.moveToVisNext(c)
i += 1
g.trace('Can not happen', n)
return None
#@+node:ekr.20171128191134.1: *5* LeoMLTree.select_leo_node
def select_leo_node(self, p):
"""
Set .start_display_at and .cursor_line ivars to display node p, with 2
lines of preceding context if possible.
"""
trace = False and not g.unitTesting
c = self.leo_c
limit, junk = c.visLimit()
p2 = limit.copy() if limit else c.rootPosition()
i = 0
while p2:
if p2 == p:
if trace:
g.trace('FOUND', i, p.h)
# Provide context if possible.
self.cursor_line = i
for j in range(2):
if p.hasVisBack(c):
p.moveToVisBack(c)
i -= 1
self.start_display_at = i
return
p2.moveToVisNext(c)
i += 1
if trace:
# Can happen during unit tests.
g.trace('Not found', p and p.h)
#@+node:ekr.20170514065422.1: *5* LeoMLTree.intraFileDrop
def intraFileDrop(self, fn, p1, p2):
pass
#@+node:ekr.20170506044733.2: *5* LeoMLTree.new_mltree_node
def new_mltree_node(self):
"""
Insert a new outline TreeData widget at the current line.
As with Leo, insert as the first child of the current line if
the current line is expanded. Otherwise insert after the current line.
"""
trace = False
trace_values = True
node = self.values[self.cursor_line]
headline = 'New headline'
if node.has_children() and node.expanded:
node = node.new_child_at(index=0, content=headline)
elif node.get_parent():
parent = node.get_parent()
node = parent.new_child(content=headline)
else:
parent = self.hidden_root_node
index = parent._children.index(node)
node = parent.new_child_at(index=index, content=headline)
if trace:
g.trace('LeoMLTree: line: %s %s' % (self.cursor_line, headline))
if trace_values:
self.dump_values()
return node
#@+node:ekr.20170506044733.5: *5* LeoMLTree.insert_line
def insert_line(self):
"""Insert an MLTree line and mark c changed."""
trace = False
c = self.leo_c
c.changed = True # Just set the changed bit.
# c.p.setDirty()
n = 0 if self.cursor_line is None else self.cursor_line
if trace:
g.trace('line: %r', n)
if native:
data = self.values[n] # data is a LeoTreeData
p = data.content
assert p and isinstance(p, leoNodes.Position)
if p.hasChildren() and p.isExpanded():
p2 = p.insertAsFirstChild()
else:
p2 = p.insertAfter()
p2.h = 'New Headline'
self.cursor_line += 1
c.selectPosition(p2)
g.app.gui.redraw_in_context(c)
else:
self.values.insert(n + 1, self.new_mltree_node())
self.cursor_line += 1
self.display()
self.edit_headline()
#@+node:ekr.20170506045346.1: *4* LeoMLTree.Handlers
# These insert or delete entire outline nodes.
#@+node:ekr.20170523112839.1: *5* LeoMLTree.handle_mouse_event
def handle_mouse_event(self, mouse_event):
"""Called from InputHandler.h_exit_mouse."""
# pylint: disable=no-member
#
# From MultiLine...
data = self.interpret_mouse_event(mouse_event)
mouse_id, rel_x, rel_y, z, bstate = data
self.cursor_line = (
rel_y //
self._contained_widget_height + self.start_display_at
)
# Now, set the correct position.
if native:
c = self.leo_c
p = self.get_nth_visible_position(self.cursor_line)
c.frame.tree.select(p)
#@+node:ekr.20170516055435.4: *5* LeoMLTree.h_collapse_all
def h_collapse_all(self, ch):
if native:
c = self.leo_c
for p in c.all_unique_positions():
p.v.contract()
self.values.clear_cache()
else:
for v in self._walk_tree(self._myFullValues, only_expanded=True):
v.expanded = False
self._cached_tree = None
self.cursor_line = 0
self.display()
#@+node:ekr.20170516055435.2: *5* LeoMLTree.h_collapse_tree
def h_collapse_tree(self, ch):
node = self.values[self.cursor_line]
if native:
p = node.content
assert p and isinstance(p, leoNodes.Position), repr(p)
p.contract()
self.values.clear_cache()
else:
if node.expanded and self._has_children(node):
# Collapse the node.
node.expanded = False
elif 0: # Optional.
# Collapse all the children.
depth = self._find_depth(node) - 1
cursor_line = self.cursor_line - 1
while cursor_line >= 0:
if depth == self._find_depth(node):
self.cursor_line = cursor_line
node.expanded = False
break
else:
cursor_line -= 1
self._cached_tree = None
# Invalidate the display cache.
self.display()
#@+node:ekr.20170513091821.1: *5* LeoMLTree.h_cursor_line_down
def h_cursor_line_down(self, ch):
c = self.leo_c
self.cursor_line = min(len(self.values) - 1, self.cursor_line + 1)
if native:
p = self.get_nth_visible_position(self.cursor_line)
c.frame.tree.select(p)
#@+node:ekr.20170513091928.1: *5* LeoMLTree.h_cursor_line_up
def h_cursor_line_up(self, ch):
c = self.leo_c
self.cursor_line = max(0, self.cursor_line - 1)
if native:
p = self.get_nth_visible_position(self.cursor_line)
c.frame.tree.select(p)
#@+node:ekr.20170506044733.12: *5* LeoMLTree.h_delete
def h_delete(self, ch):
c = self.leo_c
c.changed = True # Just set the changed bit.
self.delete_line()
if native:
p = self.get_nth_visible_position(self.cursor_line)
c.frame.tree.select(p)
#@+node:ekr.20170506044733.10: *5* LeoMLTree.h_edit_headline
def h_edit_headline(self, ch):
"""Called when the user types "h"."""
# Remember the starting headline, for CTree.onHeadChanged.
self.edit_headline()
#@+node:ekr.20170516055435.5: *5* LeoMLTree.h_expand_all
def h_expand_all(self, ch):
if native:
c = self.leo_c
for p in c.all_unique_positions():
p.v.expand()
self.values.clear_cache()
else:
for v in self._walk_tree(self._myFullValues, only_expanded=False):
v.expanded = True
self._cached_tree = None
self.cursor_line = 0
self.display()
#@+node:ekr.20170516055435.3: *5* LeoMLTree.h_expand_tree
def h_expand_tree(self, ch):
node = self.values[self.cursor_line]
if native:
p = node.content
assert p and isinstance(p, leoNodes.Position), repr(p)
p.expand() # Don't use p.v.expand()
self.values.clear_cache()
else:
# First, expand the node.
if not node.expanded:
node.expanded = True
elif 0: # Optional.
# Next, expand all children.
for z in self._walk_tree(node, only_expanded=False):
z.expanded = True
self._cached_tree = None
# Invalidate the cache.
self.display()
#@+node:ekr.20170506044733.11: *5* LeoMLTree.h_insert
def h_insert(self, ch):
self.insert_line()
if native:
c = self.leo_c
p = self.get_nth_visible_position(self.cursor_line)
c.frame.tree.select(p)
#@+node:ekr.20170506035413.1: *5* LeoMLTree.h_move_left
def h_move_left(self, ch):
trace = False and not g.unitTesting
node = self.values[self.cursor_line]
if not node:
g.trace('no node', self.cursor_line, repr(node))
return
if native:
c = self.leo_c
p = node.content
assert p and isinstance(p, leoNodes.Position), repr(p)
if p.hasChildren() and p.isExpanded():
self.h_collapse_tree(ch)
self.values.clear_cache()
elif p.hasParent():
parent = p.parent()
parent.contract() # Don't use parent.v.contract.
# Set the cursor to the parent's index.
i = self.cursor_line - 1
while i >= 0:
node2 = self.values[i]
if node2 is None:
g.trace('oops: no node2', i)
break
p2 = node2.content
if p2 == parent:
break
i -= 1
self.cursor_line = max(0, i)
if trace:
g.trace('new line', self.cursor_line)
self.values.clear_cache()
self._cached_tree = None
# Invalidate the cache.
self.display()
c.frame.tree.select(parent)
elif trace:
g.trace('no parent')
# This is what Leo does.
else:
if self._has_children(node) and node.expanded:
self.h_collapse_tree(ch)
else:
self.h_cursor_line_up(ch)
#@+node:ekr.20170506035419.1: *5* LeoMLTree.h_move_right
def h_move_right(self, ch):
node = self.values[self.cursor_line]
if not node:
g.trace('no node')
return
if native:
p = node.content
assert p and isinstance(p, leoNodes.Position), repr(p)
if p.hasChildren():
if p.isExpanded():
self.h_cursor_line_down(ch)
else:
self.h_expand_tree(ch)
else:
pass # This is what Leo does.
else:
if self._has_children(node):
if node.expanded:
self.h_cursor_line_down(ch)
else:
self.h_expand_tree(ch)
else:
self.h_cursor_line_down(ch)
#@+node:ekr.20170507175304.1: *5* LeoMLTree.set_handlers
#@@nobeautify
def set_handlers(self):
# pylint: disable=no-member
d = {
curses.KEY_MOUSE: self.h_exit_mouse,
curses.KEY_BTAB: self.h_exit_up,
curses.KEY_DOWN: self.h_cursor_line_down,
curses.KEY_LEFT: self.h_move_left,
curses.KEY_RIGHT: self.h_move_right,
curses.KEY_UP: self.h_cursor_line_up,
curses.ascii.TAB: self.h_exit_down,
ord('d'): self.h_delete,
ord('e'): self.h_edit_headline,
ord('i'): self.h_insert,
# curses.ascii.CR: self.h_edit_cursor_line_value,
# curses.ascii.NL: self.h_edit_cursor_line_value,
# curses.ascii.SP: self.h_edit_cursor_line_value,
# curses.ascii.DEL: self.h_delete_line_value,
# curses.ascii.BS: self.h_delete_line_value,
# curses.KEY_BACKSPACE: self.h_delete_line_value,
# ord('<'): self.h_collapse_tree,
# ord('>'): self.h_expand_tree,
# ord('['): self.h_collapse_tree,
# ord(']'): self.h_expand_tree,
# ord('{'): self.h_collapse_all,
# ord('}'): self.h_expand_all,
# ord('h'): self.h_collapse_tree,
# ord('l'): self.h_expand_tree,
}
# self.handlers.update(d)
# dump_handlers(self)
self.handlers = d
#@+node:ekr.20170516100256.1: *5* LeoMLTree.set_up_handlers
def set_up_handlers(self):
super().set_up_handlers()
assert not hasattr(self, 'hidden_root_node'), repr(self)
self.leo_c = None # Set later.
self.currentItem = None
# Used by CoreTree class.
self.hidden_root_node = None
self.set_handlers()
#@+node:ekr.20170513032502.1: *4* LeoMLTree.update & helpers
def update(self, clear=True, forceInit=False):
"""Redraw the tree."""
# This is a major refactoring of MultiLine.update.
trace = False and not g.unitTesting
c = self.leo_c
if trace:
g.trace('(LeoMLTree)', c.p and c.p.h)
g.trace(g.callers())
self.select_leo_node(c.p)
# Ensures that the selected node is always highlighted.
if self.editing or forceInit:
self._init_update()
if self._must_redraw(clear):
self._redraw(clear)
# Remember the previous values.
self._last_start_display_at = self.start_display_at
self._last_cursor_line = self.cursor_line
if native:
pass
else:
self._last_values = copy.copy(self.values)
self._last_value = copy.copy(self.value)
#@+node:ekr.20170513122253.1: *5* LeoMLTree._init_update
def _init_update(self):
"""Put self.cursor_line and self.start_display_at in range."""
# pylint: disable=access-member-before-definition,consider-using-max-builtin
display_length = len(self._my_widgets)
self.cursor_line = max(0, min(len(self.values) - 1, self.cursor_line))
if self.slow_scroll:
# Scroll by lines.
if self.cursor_line > self.start_display_at + display_length - 1:
self.start_display_at = self.cursor_line - (display_length - 1)
if self.cursor_line < self.start_display_at:
self.start_display_at = self.cursor_line
else:
# Scroll by pages.
if self.cursor_line > self.start_display_at + (display_length - 2):
self.start_display_at = self.cursor_line
if self.cursor_line < self.start_display_at:
self.start_display_at = self.cursor_line - (display_length - 2)
if self.start_display_at < 0:
self.start_display_at = 0
#@+node:ekr.20170513123010.1: *5* LeoMLTree._must_redraw
def _must_redraw(self, clear):
"""Return a list of reasons why we must redraw."""
trace = False and not g.unitTesting
table = (
('cache', not self._safe_to_display_cache or self.never_cache),
('value', self._last_value is not self.value),
('values', self.values != self._last_values),
('start', self.start_display_at != self._last_start_display_at),
('clear', not clear),
('cursor', self._last_cursor_line != self.cursor_line),
('filter', self._last_filter != self._filter),
('editing', not self.editing),
)
reasons = (reason for (reason, cond) in table if cond)
if trace:
g.trace('line: %2s %-20s %s' % (
self.cursor_line,
','.join(reasons),
self.values[self.cursor_line].content))
return reasons
#@+node:ekr.20170513122427.1: *5* LeoMLTree._redraw & helpers
def _redraw(self, clear):
"""Do the actual redraw."""
trace = False and not g.unitTesting
# pylint: disable=no-member
#
# self.clear is Widget.clear. It does *not* use _myWidgets.
if trace:
g.trace('start: %r cursor: %r' % (self.start_display_at, self.cursor_line))
if (clear is True or
clear is None and self._last_start_display_at != self.start_display_at
):
self.clear()
self._last_start_display_at = start = self.start_display_at
i = self.start_display_at
for line in self._my_widgets[:-1]:
assert isinstance(line, LeoTreeLine), repr(line)
self._print_line(line, i)
line.update(clear=True)
i += 1
# Do the last line
line = self._my_widgets[-1]
if len(self.values) <= i + 1:
self._print_line(line, i)
line.update(clear=False)
elif len((self._my_widgets) * self._contained_widget_height) < self.height:
self._print_line(line, i)
line.update(clear=False)
self._put_continuation_line()
else:
line.clear() # This is Widget.clear.
self._put_continuation_line()
# Assert that print_line leaves start_display_at unchanged.
assert start == self.start_display_at, (start, self.start_display_at)
# Finish
if self.editing:
line = self._my_widgets[(self.cursor_line - start)]
line.highlight = True
line.update(clear=True)
#@+node:ekr.20170513032717.1: *6* LeoMLTree._print_line
def _print_line(self, line, i):
# if self.widgets_inherit_color and self.do_colors():
# line.color = self.color
self._set_line_values(line, i)
# Sets line.value
if line.value is not None:
assert isinstance(line.value, LeoTreeData), repr(line.value)
self._set_line_highlighting(line, i)
#@+node:ekr.20170513102428.1: *6* LeoMLTree._put_continuation_line
def _put_continuation_line(self):
"""Print the line indicating there are more lines left."""
s = self.continuation_line
x = self.relx
y = self.rely + self.height - 1
if self.do_colors():
style = self.parent.theme_manager.findPair(self, 'CONTROL')
self.parent.curses_pad.addstr(y, x, s, style)
else:
self.parent.curses_pad.addstr(y, x, s)
#@+node:ekr.20170513075423.1: *6* LeoMLTree._set_line_values
def _set_line_values(self, line, i):
"""Set internal values of line using self.values[i] and self.values[i+1]"""
trace = False
trace_ok = True
trace_empty = True
line.leo_c = self.leo_c
# Inject the ivar.
values = self.values
n = len(values)
val = values[i] if 0 <= i < n else None
if trace:
g.trace(repr(val))
if val is None:
line._tree_depth = False
line._tree_depth_next = False
line._tree_expanded = False
line._tree_has_children = False
line._tree_ignore_root = None
line._tree_last_line = True #
line._tree_real_value = None
line._tree_sibling_next = False
line.value = None
if trace and trace_empty:
g.trace(i, n, '<empty>', repr(val))
return
assert isinstance(val, LeoTreeData), repr(val)
# Aliases
val1 = values[i + 1] if i + 1 < n else None
val1_depth = val1.find_depth() if val1 else False
# Common settings.
line._tree_depth = val.find_depth()
line._tree_depth_next = val1_depth
line._tree_ignore_root = self._get_ignore_root(self._myFullValues)
line._tree_sibling_next = line._tree_depth == val1_depth
line._tree_real_value = val
line.value = val
if native:
p = val.content
assert p and isinstance(p, leoNodes.Position), repr(p)
line._tree_expanded = p.isExpanded()
line._tree_has_children = p.hasChildren()
line._tree_last_line = not p.hasNext()
else:
line._tree_expanded = val.expanded
line._tree_has_children = bool(val._children)
line._tree_last_line = not bool(line._tree_sibling_next)
if trace and trace_ok:
content = line.value.content
s = content.h if native else content
g.trace(i, n, s)
#@+node:ekr.20170516101203.1: *4* LeoMLTree.values
if native:
_myFullValues = LeoTreeData()
values = None
else:
#
# This property converts the (possibly cached) result of converting
# the root node (_myFullValues) and its *visible* decendants to a list.
# To invalidate the cache, set __cached_tree = None
#@+others
#@+node:ekr.20170517142822.1: *5* _getValues
def _getValues(self):
"""
Return the (possibly cached) list returned by self._myFullValues.get_tree_as_list().
Setting _cached_tree to None invalidates the cache.
"""
# pylint: disable=access-member-before-definition
if getattr(self, '_cached_tree', None):
return self._cached_tree_as_list
self._cached_tree = self._myFullValues
self._cached_tree_as_list = self._myFullValues.get_tree_as_list()
return self._cached_tree_as_list
#@+node:ekr.20170518054457.1: *5* _setValues
def _setValues(self, tree):
self._myFullValues = tree or LeoTreeData()
#@-others
values = property(_getValues, _setValues)
#@-others
#@+node:ekr.20170517072429.1: *3* class LeoValues (npyscreen.TreeData)
class LeoValues(npyscreen.TreeData):
"""
A class to replace the MLTree.values property.
This is formally an subclass of TreeData.
"""
#@+others
#@+node:ekr.20170619070717.1: *4* values.__init__
def __init__(self, c, tree):
"""Ctor for LeoValues class."""
super().__init__()
# Init the base class.
self.c = c
# The commander of this outline.
self.data_cache = {}
# Keys are ints, values are LeoTreeData objects.
self.last_generation = -1
# The last value of c.frame.tree.generation.
self.last_len = 0
# The last computed value of the number of visible nodes.
self.n_refreshes = 0
# Number of calls to refresh_cache.
self.tree = tree
# A LeoMLTree. (not used here)
#@+node:ekr.20170517090738.1: *4* values.__getitem__ and get_data
def __getitem__(self, n):
"""Called from LeoMLTree._setLineValues."""
return self.get_data(n)
def get_data(self, n):
"""Return a LeoTreeData for the n'th visible position of the outline."""
c = self.c
# This will almost always be true, because __len__ updates the cache.
if self.last_len > -1 and c.frame.tree.generation == self.last_generation:
return self.data_cache.get(n)
self.refresh_cache()
data = self.data_cache.get(n)
g.trace('uncached', data)
return data
#@+node:ekr.20170518060014.1: *4* values.__len__
def __len__(self):
"""
Return the putative length of the values array,
that is, the number of visible nodes in the outline.
Return self.last_len if the tree generations match.
Otherwise, find and cache all visible node.
This is called often from the npyscreen core.
"""
c = self.c
tree_gen = c.frame.tree.generation
if self.last_len > -1 and tree_gen == self.last_generation:
return self.last_len
self.last_len = self.refresh_cache()
return self.last_len
#@+node:ekr.20170519041459.1: *4* values.clear_cache
def clear_cache(self):
"""Called only from this file."""
self.data_cache = {}
self.last_len = -1
#@+node:ekr.20170619072048.1: *4* values.refresh_cache
def refresh_cache(self):
"""Update all cached values."""
trace = False
c = self.c
self.n_refreshes += 1
self.clear_cache()
self.last_generation = c.frame.tree.generation
n, p = 0, c.rootPosition()
while p:
self.data_cache[n] = LeoTreeData(p)
n += 1
p.moveToVisNext(c)
self.last_len = n
if trace:
g.trace('%3s vis: %3s generation: %s' % (
self.n_refreshes, n, c.frame.tree.generation))
return n
#@-others
#@+node:ekr.20170522081122.1: ** Wrapper classes
#@+others
#@+node:ekr.20170511053143.1: *3* class TextMixin
class TextMixin:
"""A minimal mixin class for QTextEditWrapper and QScintillaWrapper classes."""
#@+others
#@+node:ekr.20170511053143.2: *4* tm.ctor & helper
def __init__(self, c=None):
"""Ctor for TextMixin class"""
self.c = c
self.changingText = False
# A lockout for onTextChanged.
self.enabled = True
self.supportsHighLevelInterface = True
# A flag for k.masterKeyHandler and isTextWrapper.
self.tags = {}
self.configDict = {}
# Keys are tags, values are colors (names or values).
self.configUnderlineDict = {}
# Keys are tags, values are True
self.virtualInsertPoint = None
if c:
self.injectIvars(c)
#@+node:ekr.20170511053143.3: *5* tm.injectIvars
def injectIvars(self, name='1', parentFrame=None):
"""Inject standard leo ivars into the QTextEdit or QsciScintilla widget."""
p = self.c.currentPosition()
if name == '1':
self.leo_p = None # Will be set when the second editor is created.
else:
self.leo_p = p and p.copy()
self.leo_active = True
# Inject the scrollbar items into the text widget.
self.leo_bodyBar = None
self.leo_bodyXBar = None
self.leo_chapter = None
self.leo_frame = None
self.leo_name = name
self.leo_label = None
return self
#@+node:ekr.20170511053143.4: *4* tm.getName
def getName(self):
return self.name # Essential.
#@+node:ekr.20170511053143.8: *4* tm.Generic high-level interface
# These call only wrapper methods.
#@+node:ekr.20170511053143.13: *5* tm.appendText
def appendText(self, s):
"""TextMixin"""
s2 = self.getAllText()
self.setAllText(s2 + s)
self.setInsertPoint(len(s2))
#@+node:ekr.20170511053143.10: *5* tm.clipboard_clear/append
def clipboard_append(self, s):
s1 = g.app.gui.getTextFromClipboard()
g.app.gui.replaceClipboardWith(s1 + s)
def clipboard_clear(self):
g.app.gui.replaceClipboardWith('')
#@+node:ekr.20170511053143.14: *5* tm.delete
def delete(self, i, j=None):
"""TextMixin"""
i = self.toPythonIndex(i)
if j is None:
j = i + 1
j = self.toPythonIndex(j)
# This allows subclasses to use this base class method.
if i > j:
i, j = j, i
s = self.getAllText()
self.setAllText(s[:i] + s[j:])
# Bug fix: Significant in external tests.
self.setSelectionRange(i, i, insert=i)
#@+node:ekr.20170511053143.15: *5* tm.deleteTextSelection
def deleteTextSelection(self):
"""TextMixin"""
i, j = self.getSelectionRange()
self.delete(i, j)
#@+node:ekr.20170511053143.9: *5* tm.Enable/disable
def disable(self):
self.enabled = False
def enable(self, enabled=True):
self.enabled = enabled
#@+node:ekr.20170511053143.16: *5* tm.get
def get(self, i, j=None):
"""TextMixin"""
# 2012/04/12: fix the following two bugs by using the vanilla code:
# https://bugs.launchpad.net/leo-editor/+bug/979142
# https://bugs.launchpad.net/leo-editor/+bug/971166
s = self.getAllText()
i = self.toPythonIndex(i)
j = self.toPythonIndex(j)
return s[i:j]
#@+node:ekr.20170511053143.17: *5* tm.getLastPosition & getLength
def getLastPosition(self, s=None):
"""TextMixin"""
return len(self.getAllText()) if s is None else len(s)
def getLength(self, s=None):
"""TextMixin"""
return len(self.getAllText()) if s is None else len(s)
#@+node:ekr.20170511053143.18: *5* tm.getSelectedText
def getSelectedText(self):
"""TextMixin"""
i, j = self.getSelectionRange()
if i == j:
return ''
s = self.getAllText()
return s[i:j]
#@+node:ekr.20170511053143.19: *5* tm.insert
def insert(self, i, s):
"""TextMixin"""
s2 = self.getAllText()
i = self.toPythonIndex(i)
self.setAllText(s2[:i] + s + s2[i:])
self.setInsertPoint(i + len(s))
return i
#@+node:ekr.20170511053143.24: *5* tm.rememberSelectionAndScroll
def rememberSelectionAndScroll(self):
v = self.c.p.v # Always accurate.
v.insertSpot = self.getInsertPoint()
i, j = self.getSelectionRange()
if i > j:
i, j = j, i
assert i <= j
v.selectionStart = i
v.selectionLength = j - i
v.scrollBarSpot = self.getYScrollPosition()
#@+node:ekr.20170511053143.20: *5* tm.seeInsertPoint
def seeInsertPoint(self):
"""Ensure the insert point is visible."""
self.see(self.getInsertPoint())
# getInsertPoint defined in client classes.
#@+node:ekr.20170511053143.21: *5* tm.selectAllText
def selectAllText(self, s=None):
"""TextMixin."""
self.setSelectionRange(0, self.getLength(s))
#@+node:ekr.20170511053143.11: *5* tm.setFocus
def setFocus(self):
"""TextMixin.setFocus"""
g.app.gui.set_focus(self)
#@+node:ekr.20170511053143.25: *5* tm.tag_configure
def tag_configure(self, *args, **keys):
trace = False and not g.unitTesting
if trace:
g.trace(args, keys)
if len(args) == 1:
key = args[0]
self.tags[key] = keys
val = keys.get('foreground')
underline = keys.get('underline')
if val:
self.configDict[key] = val
if underline:
self.configUnderlineDict[key] = True
else:
g.trace('oops', args, keys)
tag_config = tag_configure
#@+node:ekr.20170511053143.22: *5* tm.toPythonIndex
def toPythonIndex(self, index, s=None):
"""TextMixin"""
if s is None:
s = self.getAllText()
i = g.toPythonIndex(s, index)
return i
#@+node:ekr.20170511053143.23: *5* tm.toPythonIndexRowCol
def toPythonIndexRowCol(self, index):
"""TextMixin"""
s = self.getAllText()
i = self.toPythonIndex(index)
row, col = g.convertPythonIndexToRowCol(s, i)
return i, row, col
#@-others
#@+node:ekr.20170504034655.1: *3* class BodyWrapper (leoFrame.StringTextWrapper)
class BodyWrapper(leoFrame.StringTextWrapper):
"""
A Wrapper class for Leo's body.
This is c.frame.body.wrapper.
"""
def __init__(self, c, name, w):
"""Ctor for BodyWrapper class"""
super().__init__(c, name)
self.changingText = False
# A lockout for onTextChanged.
self.widget = w
self.injectIvars(c)
# These are used by Leo's core.
#@+others
#@+node:ekr.20170504034655.3: *4* bw.injectIvars
def injectIvars(self, name='1', parentFrame=None):
"""Inject standard leo ivars into the QTextEdit or QsciScintilla widget."""
p = self.c.currentPosition()
if name == '1':
self.leo_p = None # Will be set when the second editor is created.
else:
self.leo_p = p and p.copy()
self.leo_active = True
# Inject the scrollbar items into the text widget.
self.leo_bodyBar = None
self.leo_bodyXBar = None
self.leo_chapter = None
self.leo_frame = None
self.leo_name = name
self.leo_label = None
#@+node:ekr.20170504034655.6: *4* bw.onCursorPositionChanged
def onCursorPositionChanged(self, event=None):
if 0:
g.trace('=====', event)
#@-others
#@+node:ekr.20170522002403.1: *3* class HeadWrapper (leoFrame.StringTextWrapper)
class HeadWrapper(leoFrame.StringTextWrapper):
"""
A Wrapper class for headline widgets, returned by c.edit_widget(p)
"""
def __init__(self, c, name, p):
"""Ctor for HeadWrapper class"""
super().__init__(c, name)
self.trace = False # For tracing in base class.
self.p = p.copy()
self.s = p.v._headString
#@+others
#@+node:ekr.20170522014009.1: *4* hw.setAllText
def setAllText(self, s):
"""HeadWrapper.setAllText"""
# Don't allow newlines.
self.s = s.replace('\n', '').replace('\r', '')
i = len(self.s)
self.ins = i
self.sel = i, i
self.p.v._headString = self.s
#@-others
#@+node:ekr.20170525062512.1: *3* class LogWrapper (leoFrame.StringTextWrapper)
class LogWrapper(leoFrame.StringTextWrapper):
"""A Wrapper class for the log pane."""
def __init__(self, c, name, w):
"""Ctor for LogWrapper class"""
super().__init__(c, name)
self.trace = False # For tracing in base class.
self.widget = w
#@+others
#@-others
#@+node:ekr.20170525105707.1: *3* class MiniBufferWrapper (leoFrame.StringTextWrapper)
class MiniBufferWrapper(leoFrame.StringTextWrapper):
"""A Wrapper class for the minibuffer."""
def __init__(self, c, name, w):
"""Ctor for MiniBufferWrapper class"""
super().__init__(c, name)
self.trace = False # For tracing in base class.
self.box = None # Injected
self.widget = w
#@+node:ekr.20171129194610.1: *3* class StatusLineWrapper (leoFrame.StringTextWrapper)
class StatusLineWrapper(leoFrame.StringTextWrapper):
"""A Wrapper class for the status line."""
def __init__(self, c, name, w):
"""Ctor for StatusLineWrapper class"""
super().__init__(c, name)
self.trace = False # For tracing in base class.
self.widget = w
def isEnabled(self):
return True
#@+others
#@+node:ekr.20171129204751.1: *4* StatusLineWrapper.do nothings
def disable(self, *args, **kwargs):
pass
def enable(self, *args, **kwargs):
pass
def setFocus(self):
pass
#@+node:ekr.20171129204736.1: *4* StatusLineWrapper.redirectors
def clear(self):
self.widget.value = ''
self.widget.display()
def get(self):
return self.widget.value
def put(self, s, *args, **kwargs):
i = s.find('#')
if i > -1:
s = s[i + 1 :]
self.widget.value = s
self.widget.display()
def update(self, *args, **kwargs):
self.widget.update()
#@-others
#@-others
#@-others
#@@language python
#@@tabwidth -4
#@-leo
| [
"[email protected]"
]
| |
097f90f0262110b4a39fec200710fa8f135f45a9 | db61f1b3db18ef698f08e456c60e2162a5479807 | /experiments/timit/data/test_load_dataset_joint_ctc_attention.py | 5825b2d4d7443ffef8d010fe251f20028c20fa14 | [
"MIT"
]
| permissive | fresty/tensorflow_end2end_speech_recognition | 00aa1d827aa9b04862389ff1a8169259adcd6db9 | a95ba6a29208e70d6ea102bbca2b03ea492c708c | refs/heads/master | 2021-01-01T06:14:25.378685 | 2017-07-10T11:35:05 | 2017-07-10T11:35:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,269 | py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
import sys
import unittest
import tensorflow as tf
sys.path.append('../../../')
from experiments.timit.data.load_dataset_joint_ctc_attention import Dataset
from experiments.utils.labels.character import num2char
from experiments.utils.labels.phone import num2phone
from experiments.utils.sparsetensor import sparsetensor2list
from experiments.utils.measure_time_func import measure_time
class TestLoadDatasetJointCTCAttention(unittest.TestCase):
def test(self):
self.check_loading(label_type='character', num_gpu=1, is_sorted=True)
self.check_loading(label_type='character', num_gpu=1, is_sorted=False)
self.check_loading(label_type='phone61', num_gpu=1, is_sorted=True)
self.check_loading(label_type='phone61', num_gpu=1, is_sorted=False)
# self.check_loading(label_type='character', num_gpu=2, is_sorted=True)
# self.check_loading(label_type='character', num_gpu=2, is_sorted=False)
# self.check_loading(label_type='phone61', num_gpu=2, is_sorted=True)
# self.check_loading(label_type='phone61', num_gpu=2, is_sorted=False)
# For many GPUs
# self.check_loading(label_type='character', num_gpu=7, is_sorted=True)
def check_loading(self, label_type, num_gpu, is_sorted):
print('----- label_type: ' + label_type + ', num_gpu: ' +
str(num_gpu) + ', is_sorted: ' + str(is_sorted) + ' -----')
batch_size = 64
eos_index = 2 if label_type == 'character' else 1
dataset = Dataset(data_type='train', label_type=label_type,
batch_size=batch_size, eos_index=eos_index,
is_sorted=is_sorted, is_progressbar=True,
num_gpu=num_gpu)
tf.reset_default_graph()
with tf.Session().as_default() as sess:
print('=> Loading mini-batch...')
if label_type == 'character':
att_map_file_path = '../metrics/mapping_files/attention/char2num.txt'
ctc_map_file_path = '../metrics/mapping_files/ctc/char2num.txt'
map_fn = num2char
else:
att_map_file_path = '../metrics/mapping_files/attention/phone2num_' + \
label_type[5:7] + '.txt'
ctc_map_file_path = '../metrics/mapping_files/ctc/phone2num_' + \
label_type[5:7] + '.txt'
map_fn = num2phone
mini_batch = dataset.next_batch(session=sess)
iter_per_epoch = int(dataset.data_num /
(batch_size * num_gpu)) + 1
for i in range(iter_per_epoch + 1):
return_tuple = mini_batch.__next__()
inputs = return_tuple[0]
att_labels = return_tuple[1]
ctc_labels_st = return_tuple[2]
att_labels_seq_len = return_tuple[4]
if num_gpu > 1:
for inputs_gpu in inputs:
print(inputs_gpu.shape)
inputs = inputs[0]
att_labels = att_labels[0]
ctc_labels_st = ctc_labels_st[0]
att_labels_seq_len = att_labels_seq_len[0]
ctc_labels = sparsetensor2list(
ctc_labels_st, batch_size=len(inputs))
if num_gpu == 1:
for inputs_i, labels_i in zip(inputs, ctc_labels):
if len(inputs_i) < len(labels_i):
print(len(inputs_i))
print(len(labels_i))
raise ValueError
att_str_true = map_fn(
att_labels[0][0: att_labels_seq_len[0]], att_map_file_path)
ctc_str_true = map_fn(ctc_labels[0], ctc_map_file_path)
att_str_true = re.sub(r'_', ' ', att_str_true)
ctc_str_true = re.sub(r'_', ' ', ctc_str_true)
# print(att_str_true)
# print(ctc_str_true)
# print('-----')
if __name__ == '__main__':
unittest.main()
| [
"[email protected]"
]
| |
1204cb5de1ac2f1d3306c831671aeefb0c4286c2 | 1b9075ffea7d4b846d42981b41be44238c371202 | /tags/2007-EOL/applications/editors/qt_xhtmledit/actions.py | e00311a209fc6a3d1204dd6195e524b1ba17a2e5 | []
| no_license | pars-linux/contrib | bf630d4be77f4e484b8c6c8b0698a5b34b3371f4 | 908210110796ef9461a1f9b080b6171fa022e56a | refs/heads/master | 2020-05-26T20:35:58.697670 | 2011-07-11T11:16:38 | 2011-07-11T11:16:38 | 82,484,996 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 846 | py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU General Public License, version 2.
# See the file http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt
from pisi.actionsapi import autotools
from pisi.actionsapi import shelltools
from pisi.actionsapi import pisitools
WorkDir = "htmledit"
def setup():
shelltools.system("lrelease-qt4 src/locale/edit_tr.ts -qm src/locale/edit_tr.qm")
shelltools.system("qmake-qt4 htmledit.pro")
def build():
autotools.make()
def install():
pisitools.dobin("edithtml")
pisitools.insinto("/usr/share/qt_xhtmledit/locale", "src/locale/*.qm")
pisitools.insinto("/usr/share/qt_xhtmledit","src/img")
pisitools.insinto("/usr/share/pixmaps/", "wp.png", "qt_xhtmledit.png")
pisitools.remove("/usr/share/qt_xhtmledit/img/Thumbs.db")
pisitools.dodoc("LICENSE")
| [
"[email protected]"
]
| |
0bbcecd2761b1b9dbb8ba24462c8f20153c402a6 | 41d9b92ef2a74a4ba05d27ffbe3beb87884c4ce7 | /supervised_learning/0x06-keras/0-sequential.py | e0175875bc17bcbc0416647a5a71d94f1109cf53 | []
| no_license | JosephK89/holbertonschool-machine_learning | 3f96d886c61d8de99a23e4348fb045b9c930740e | aa5c500f7d8ebeec951f9ab5ec017cae64007c25 | refs/heads/main | 2023-08-14T18:42:53.481354 | 2021-10-10T19:53:40 | 2021-10-10T19:53:40 | 386,248,140 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 921 | py | #!/usr/bin/env python3
"""build nn with keras"""
import tensorflow.keras as K
def build_model(nx, layers, activations, lambtha, keep_prob):
"""function that build nn with keras library"""
sequential = []
shape = (nx,)
reg_l2 = K.regularizers.l2(lambtha)
for i in range(len(layers)):
if i is 0:
sequential.append(K.layers.Dense(layers[i],
activation=activations[i],
kernel_regularizer=reg_l2,
input_shape=shape))
else:
sequential.append(K.layers.Dropout(1 - keep_prob))
sequential.append(K.layers.Dense(layers[i],
activation=activations[i],
kernel_regularizer=reg_l2))
model = K.Sequential(sequential)
return model
| [
"[email protected]"
]
| |
6594d4a0659814479070a0b970b49bb3945e2831 | d7532e2ac4983c042f50525aab564597db154719 | /day4/modules/6.py | 12722dbeb27f186c256891231e3732b72beb498c | []
| no_license | shobhit-nigam/qti_panda | d53195def05605ede24a5108de1dbfbe56cbffe7 | 35d52def5d8ef1874e795a407768fd4a02834418 | refs/heads/main | 2023-08-24T14:56:34.934694 | 2021-10-22T09:59:05 | 2021-10-22T09:59:05 | 418,381,871 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 47 | py | from colour import red, purple
red()
purple()
| [
"[email protected]"
]
| |
55066d351456806918e16de4f90fa5a40c4fc112 | 3ab97361bdc0c1b392d46c299a0293e16be577fa | /home/migrations/0002_load_initial_data.py | 206a0bf2e653e72367f7fdaa30d0dc0414a2394b | []
| no_license | crowdbotics-apps/mason-21411 | 2f191039aedb0f66c2acc9fb5c6e022a00a1ba5a | 1456b83bde0c15151ac78218ae2fd3391ddb8c31 | refs/heads/master | 2022-12-30T03:26:44.899130 | 2020-10-12T19:05:12 | 2020-10-12T19:05:12 | 303,487,539 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,274 | py | from django.db import migrations
def create_customtext(apps, schema_editor):
CustomText = apps.get_model("home", "CustomText")
customtext_title = "mason"
CustomText.objects.create(title=customtext_title)
def create_homepage(apps, schema_editor):
HomePage = apps.get_model("home", "HomePage")
homepage_body = """
<h1 class="display-4 text-center">mason</h1>
<p class="lead">
This is the sample application created and deployed from the Crowdbotics app.
You can view list of packages selected for this application below.
</p>"""
HomePage.objects.create(body=homepage_body)
def create_site(apps, schema_editor):
Site = apps.get_model("sites", "Site")
custom_domain = "mason-21411.botics.co"
site_params = {
"name": "mason",
}
if custom_domain:
site_params["domain"] = custom_domain
Site.objects.update_or_create(defaults=site_params, id=1)
class Migration(migrations.Migration):
dependencies = [
("home", "0001_initial"),
("sites", "0002_alter_domain_unique"),
]
operations = [
migrations.RunPython(create_customtext),
migrations.RunPython(create_homepage),
migrations.RunPython(create_site),
]
| [
"[email protected]"
]
| |
efbac9d802b7d3a3214f5eec619b410d173accbd | 9451bdaa89cef69a8216c9ca9c7ac8e5b7d7c22e | /7multi_process/multi_process.py | fd1f8d9b8081f0ec4d63fc57aa3c2eb7a24339e0 | []
| no_license | PaulYoung1024/lou-plus-python | 87c97334a5b2aa4c8dc3bc0071a7ab41fe553682 | 7cc8e85eb25bb72e79a7dd9d25046bc1b4f9f3c6 | refs/heads/master | 2020-04-30T08:36:36.466716 | 2019-03-20T11:57:47 | 2019-03-20T11:57:47 | 176,721,830 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 565 | py | import time
from multiprocessing import Process
def io_task():
time.sleep(1)
def main():
start_time=time.time()
'''
for i in range(5):
io_task()
'''
#child task list
process_list=[]
for i in range(5):
process_list.append(Process(target=io_task))
#start all child process
for process in process_list:
process.start()
for process in process_list:
process.join()
end_time=time.time()
print("program run time:{:.2f}".format(end_time-start_time))
if __name__=='__main__':
main()
| [
"[email protected]"
]
| |
f7d80ab14dcfc2d779e2db1b661da9f1babd6043 | 1415fa90c4d86e76d76ead544206d73dd2617f8b | /venv/Lib/site-packages/direct/tkpanels/AnimPanel.py | 12bc1feefdfe0d55b84968966a35a0b33dfa86af | [
"MIT"
]
| permissive | Darpra27/Juego-senales | 84ea55aea7c61308ec1821dac9f5a29d2e0d75de | e94bc819e05eff1e0126c094d21ae1ec2a1ef46d | refs/heads/main | 2023-04-04T07:27:53.878785 | 2021-04-09T00:00:44 | 2021-04-09T00:00:44 | 353,472,016 | 0 | 1 | MIT | 2021-04-09T00:04:31 | 2021-03-31T19:46:14 | Python | UTF-8 | Python | false | false | 28,209 | py | """DIRECT Animation Control Panel"""
__all__ = ['AnimPanel', 'ActorControl']
### SEE END OF FILE FOR EXAMPLE USEAGE ###
# Import Tkinter, Pmw, and the floater code from this directory tree.
from direct.tkwidgets.AppShell import *
from direct.showbase.TkGlobal import *
import Pmw, sys, os
from direct.task import Task
from panda3d.core import Filename, getModelPath
if sys.version_info >= (3, 0):
from tkinter.simpledialog import askfloat
from tkinter.filedialog import askopenfilename
else:
from tkSimpleDialog import askfloat
from tkFileDialog import askopenfilename
FRAMES = 0
SECONDS = 1
class AnimPanel(AppShell):
# Override class variables
appname = 'Anim Panel'
frameWidth = 675
frameHeight = 250
usecommandarea = 0
usestatusarea = 0
index = 0
def __init__(self, aList = [], parent = None, session = None, **kw):
INITOPT = Pmw.INITOPT
if isinstance(aList, (list, tuple)):
kw['actorList'] = aList
else:
kw['actorList'] = [aList]
optiondefs = (
('title', self.appname, None),
('actorList', [], None),
('Actor_label_width', 12, None),
)
self.defineoptions(kw, optiondefs)
# direct session that spawned me, if any, used
# for certain interactions with the session such
# as being able to see selected objects/actors
self.session = session
self.frameHeight = 60 + (50 * len(self['actorList']))
self.playList = []
self.id = 'AnimPanel_%d' % AnimPanel.index
AnimPanel.index += 1
# current index used for creating new actor controls
self.actorControlIndex = 0
# Initialize the superclass
AppShell.__init__(self)
# Execute option callbacks
self.initialiseoptions(AnimPanel)
# We need to know when AnimPanel is closed
self.destroyCallBack = None
def createInterface(self):
# Handle to the toplevels interior
interior = self.interior()
menuBar = self.menuBar
menuBar.addmenu('AnimPanel', 'Anim Panel Operations')
# Actor control status
menuBar.addcascademenu('AnimPanel', 'Control Status',
'Enable/disable actor control panels')
menuBar.addmenuitem('Control Status', 'command',
'Enable all actor controls',
label = 'Enable all',
command = self.enableActorControls)
menuBar.addmenuitem('Control Status', 'command',
'Disable all actor controls',
label = 'Disable all',
command = self.disableActorControls)
# Frame Slider units
menuBar.addcascademenu('AnimPanel', 'Display Units',
'Select display units')
menuBar.addmenuitem('Display Units', 'command',
'Display frame counts', label = 'Frame count',
command = self.displayFrameCounts)
menuBar.addmenuitem('Display Units', 'command',
'Display seconds', label = 'Seconds',
command = self.displaySeconds)
# Reset all actor controls
menuBar.addmenuitem('AnimPanel', 'command',
'Set actor controls to t = 0.0',
label = 'Jump all to zero',
command = self.resetAllToZero)
menuBar.addmenuitem('AnimPanel', 'command',
'Set Actor controls to end time',
label = 'Jump all to end time',
command = self.resetAllToEnd)
# Add some buttons to update all Actor Controls
self.fToggleAll = 1
b = self.createcomponent(
'toggleEnableButton', (), None,
Button, (self.menuFrame,),
text = 'Toggle Enable',
command = self.toggleAllControls)
b.pack(side = RIGHT, expand = 0)
b = self.createcomponent(
'showSecondsButton', (), None,
Button, (self.menuFrame,),
text = 'Show Seconds',
command = self.displaySeconds)
b.pack(side = RIGHT, expand = 0)
b = self.createcomponent(
'showFramesButton', (), None,
Button, (self.menuFrame,),
text = 'Show Frames',
command = self.displayFrameCounts)
b.pack(side = RIGHT, expand = 0)
self.actorFrame = None
self.createActorControls()
# Create a frame to hold the playback controls
controlFrame = Frame(interior)
self.toStartButton = self.createcomponent(
'toStart', (), None,
Button, (controlFrame,),
text = '<<',
width = 4,
command = self.resetAllToZero)
self.toStartButton.pack(side = LEFT, expand = 1, fill = X)
self.toPreviousFrameButton = self.createcomponent(
'toPreviousFrame', (), None,
Button, (controlFrame,),
text = '<',
width = 4,
command = self.previousFrame)
self.toPreviousFrameButton.pack(side = LEFT, expand = 1, fill = X)
self.playButton = self.createcomponent(
'playButton', (), None,
Button, (controlFrame,),
text = 'Play', width = 8,
command = self.playActorControls)
self.playButton.pack(side = LEFT, expand = 1, fill = X)
self.stopButton = self.createcomponent(
'stopButton', (), None,
Button, (controlFrame,),
text = 'Stop', width = 8,
command = self.stopActorControls)
self.stopButton.pack(side = LEFT, expand = 1, fill = X)
self.toNextFrameButton = self.createcomponent(
'toNextFrame', (), None,
Button, (controlFrame,),
text = '>',
width = 4,
command = self.nextFrame)
self.toNextFrameButton.pack(side = LEFT, expand = 1, fill = X)
self.toEndButton = self.createcomponent(
'toEnd', (), None,
Button, (controlFrame,),
text = '>>',
width = 4,
command = self.resetAllToEnd)
self.toEndButton.pack(side = LEFT, expand = 1, fill = X)
self.loopVar = IntVar()
self.loopVar.set(0)
self.loopButton = self.createcomponent(
'loopButton', (), None,
Checkbutton, (controlFrame,),
text = 'Loop', width = 8,
variable = self.loopVar)
self.loopButton.pack(side = LEFT, expand = 1, fill = X)
# add actors and animations, only allowed if a direct
# session has been specified since these currently require
# interaction with selected objects
if (self.session):
menuBar.addmenuitem('File', 'command',
'Set currently selected group of objects as actors to animate.',
label = 'Set Actors',
command = self.setActors)
menuBar.addmenuitem('File', 'command',
'Load animation file',
label = 'Load Anim',
command = self.loadAnim)
controlFrame.pack(fill = X)
def createActorControls(self):
# Create a frame to hold all the actor controls
self.actorFrame = Frame(self.interior())
# Create a control for each actor
self.actorControlList = []
for actor in self['actorList']:
anims = actor.getAnimNames()
print("actor animnames: %s"%anims)
topAnims = []
if 'neutral' in anims:
i = anims.index('neutral')
del(anims[i])
topAnims.append('neutral')
if 'walk' in anims:
i = anims.index('walk')
del(anims[i])
topAnims.append('walk')
if 'run' in anims:
i = anims.index('run')
del(anims[i])
topAnims.append('run')
anims.sort()
anims = topAnims + anims
if (len(anims)== 0):
# no animations set for this actor, don't
# display the control panel
continue
# currComponents = self.components()
# if ('actorControl%d' % index in currComponents):
# self.destroycomponent('actorControl%d' % index)
# ac = self.component('actorControl%d' % index)
# if (ac == None):
ac = self.createcomponent(
'actorControl%d' % self.actorControlIndex, (), 'Actor',
ActorControl, (self.actorFrame,),
animPanel = self,
text = actor.getName(),
animList = anims,
actor = actor)
ac.pack(expand = 1, fill = X)
self.actorControlList.append(ac)
self.actorControlIndex = self.actorControlIndex + 1
# Now pack the actor frame
self.actorFrame.pack(expand = 1, fill = BOTH)
def clearActorControls(self):
if (self.actorFrame):
self.actorFrame.forget()
self.actorFrame.destroy()
self.actorFrame = None
def setActors(self):
self.stopActorControls()
actors = self.session.getSelectedActors()
# make sure selected objects are actors, if not don't
# use?
aList = []
for currActor in actors:
aList.append(currActor)
self['actorList'] = aList
self.clearActorControls()
self.createActorControls()
def loadAnim(self):
# bring up file open box to allow selection of an
# animation file
animFilename = askopenfilename(
defaultextension = '.mb',
filetypes = (('Maya Models', '*.mb'),
('All files', '*')),
initialdir = '/i/beta',
title = 'Load Animation',
parent = self.component('hull')
)
if not animFilename or animFilename == 'None':
# no file selected, canceled
return
# add directory where animation was loaded from to the
# current model path so any further searches for the file
# can find it
fileDirName = os.path.dirname(animFilename)
fileBaseName = os.path.basename(animFilename)
fileBaseNameBase = os.path.splitext(fileBaseName)[0]
fileDirNameFN = Filename(fileDirName)
fileDirNameFN.makeCanonical()
getModelPath().prependDirectory(fileDirNameFN)
for currActor in self['actorList']:
# replace all currently loaded anims with specified one
# currActor.unloadAnims(None, None, None)
currActor.loadAnims({fileBaseNameBase:fileBaseNameBase})
self.clearActorControls()
self.createActorControls()
def playActorControls(self):
self.stopActorControls()
self.lastT = globalClock.getFrameTime()
self.playList = self.actorControlList[:]
taskMgr.add(self.play, self.id + '_UpdateTask')
def play(self, task):
if not self.playList:
return Task.done
fLoop = self.loopVar.get()
currT = globalClock.getFrameTime()
deltaT = currT - self.lastT
self.lastT = currT
for actorControl in self.playList:
# scale time by play rate value
actorControl.play(deltaT * actorControl.playRate, fLoop)
return Task.cont
def stopActorControls(self):
taskMgr.remove(self.id + '_UpdateTask')
def getActorControlAt(self, index):
return self.actorControlList[index]
def enableActorControlAt(self, index):
self.getActorControlAt(index).enableControl()
def toggleAllControls(self):
if self.fToggleAll:
self.disableActorControls()
else:
self.enableActorControls()
self.fToggleAll = 1 - self.fToggleAll
def enableActorControls(self):
for actorControl in self.actorControlList:
actorControl.enableControl()
def disableActorControls(self):
for actorControl in self.actorControlList:
actorControl.disableControl()
def disableActorControlAt(self, index):
self.getActorControlAt(index).disableControl()
def displayFrameCounts(self):
for actorControl in self.actorControlList:
actorControl.displayFrameCounts()
def displaySeconds(self):
for actorControl in self.actorControlList:
actorControl.displaySeconds()
def resetAllToZero(self):
for actorControl in self.actorControlList:
actorControl.resetToZero()
def resetAllToEnd(self):
for actorControl in self.actorControlList:
actorControl.resetToEnd()
def nextFrame(self):
for actorControl in self.actorControlList:
actorControl.nextFrame()
def previousFrame(self):
for actorControl in self.actorControlList:
actorControl.previousFrame()
def setDestroyCallBack(self, callBack):
self.destroyCallBack = callBack
def destroy(self):
# First clean up
taskMgr.remove(self.id + '_UpdateTask')
if self.destroyCallBack is not None:
self.destroyCallBack()
self.destroyCallBack = None
AppShell.destroy(self)
class ActorControl(Pmw.MegaWidget):
def __init__(self, parent = None, **kw):
INITOPT = Pmw.INITOPT
DEFAULT_FONT = (('MS', 'Sans', 'Serif'), 12, 'bold')
DEFAULT_ANIMS = ('neutral', 'run', 'walk')
animList = kw.get('animList', DEFAULT_ANIMS)
if len(animList) > 0:
initActive = animList[0]
else:
initActive = DEFAULT_ANIMS[0]
optiondefs = (
('text', 'Actor', self._updateLabelText),
('animPanel', None, None),
('actor', None, None),
('animList', DEFAULT_ANIMS, None),
('active', initActive, None),
('sLabel_width', 5, None),
('sLabel_font', DEFAULT_FONT, None),
)
self.defineoptions(kw, optiondefs)
# Initialize the superclass
Pmw.MegaWidget.__init__(self, parent)
# Handle to the toplevels hull
interior = self.interior()
interior.configure(relief = RAISED, bd = 2)
# Instance variables
self.fps = 24
self.offset = 0.0
self.maxSeconds = 1.0
self.currT = 0.0
self.fScaleCommand = 0
self.fOneShot = 0
# Create component widgets
self._label = self.createcomponent(
'label', (), None,
Menubutton, (interior,),
font=('MSSansSerif', 14, 'bold'),
relief = RAISED, bd = 1,
activebackground = '#909090',
text = self['text'])
# Top level menu
labelMenu = Menu(self._label, tearoff = 0)
# Menu to select display mode
self.unitsVar = IntVar()
self.unitsVar.set(FRAMES)
displayMenu = Menu(labelMenu, tearoff = 0)
displayMenu.add_radiobutton(label = 'Frame count',
value = FRAMES,
variable = self.unitsVar,
command = self.updateDisplay)
displayMenu.add_radiobutton(label = 'Seconds',
value = SECONDS,
variable = self.unitsVar,
command = self.updateDisplay)
# Items for top level menu
labelMenu.add_cascade(label = 'Display Units', menu = displayMenu)
# labelMenu.add_command(label = 'Set Offset', command = self.setOffset)
labelMenu.add_command(label = 'Jump To Zero',
command = self.resetToZero)
labelMenu.add_command(label = 'Jump To End Time',
command = self.resetToEnd)
# Now associate menu with menubutton
self._label['menu'] = labelMenu
self._label.pack(side = LEFT, fill = X)
# Combo box to select current animation
self.animMenu = self.createcomponent(
'animMenu', (), None,
Pmw.ComboBox, (interior,),
labelpos = W, label_text = 'Anim:',
entry_width = 12, selectioncommand = self.selectAnimNamed,
scrolledlist_items = self['animList'])
self.animMenu.selectitem(self['active'])
self.animMenu.pack(side = 'left', padx = 5, expand = 0)
# Combo box to select frame rate
playRateList = ['1/24.0', '0.1', '0.5', '1.0', '2.0', '5.0', '10.0']
playRate = '%0.1f' % self['actor'].getPlayRate(self['active'])
if playRate not in playRateList:
def strCmp(a, b):
return cmp(eval(a), eval(b))
playRateList.append(playRate)
playRateList.sort(strCmp)
playRateMenu = self.createcomponent(
'playRateMenu', (), None,
Pmw.ComboBox, (interior,),
labelpos = W, label_text = 'Play Rate:',
entry_width = 4, selectioncommand = self.setPlayRate,
scrolledlist_items = playRateList)
playRateMenu.selectitem(playRate)
playRateMenu.pack(side = LEFT, padx = 5, expand = 0)
# Scale to control animation
frameFrame = Frame(interior, relief = SUNKEN, bd = 1)
self.minLabel = self.createcomponent(
'minLabel', (), 'sLabel',
Label, (frameFrame,),
text = 0)
self.minLabel.pack(side = LEFT)
self.frameControl = self.createcomponent(
'scale', (), None,
Scale, (frameFrame,),
from_ = 0, to = 24, resolution = 1.0,
command = self.goTo,
orient = HORIZONTAL, showvalue = 1)
self.frameControl.pack(side = LEFT, expand = 1)
self.frameControl.bind('<Button-1>', self.__onPress)
self.frameControl.bind('<ButtonRelease-1>', self.__onRelease)
self.maxLabel = self.createcomponent(
'maxLabel', (), 'sLabel',
Label, (frameFrame,),
text = 24)
self.maxLabel.pack(side = LEFT)
frameFrame.pack(side = LEFT, expand = 1, fill = X)
# Checkbutton to enable/disable control
self.frameActiveVar = IntVar()
self.frameActiveVar.set(1)
frameActive = self.createcomponent(
'checkbutton', (), None,
Checkbutton, (interior,),
variable = self.frameActiveVar)
frameActive.pack(side = LEFT, expand = 1)
# Execute option callbacks
self.initialiseoptions(ActorControl)
self.playRate = 1.0
self.updateDisplay()
def _updateLabelText(self):
self._label['text'] = self['text']
def updateDisplay(self):
actor = self['actor']
active = self['active']
self.fps = actor.getFrameRate(active)
if (self.fps == None):
# there was probably a problem loading the
# active animation, set default anim properties
print("unable to get animation fps, zeroing out animation info")
self.fps = 24
self.duration = 0
self.maxFrame = 0
self.maxSeconds = 0
else:
self.duration = actor.getDuration(active)
self.maxFrame = actor.getNumFrames(active) - 1
self.maxSeconds = self.offset + self.duration
# switch between showing frame counts and seconds
if self.unitsVar.get() == FRAMES:
# these are approximate due to discrete frame size
fromFrame = 0
toFrame = self.maxFrame
self.minLabel['text'] = fromFrame
self.maxLabel['text'] = toFrame
self.frameControl.configure(from_ = fromFrame,
to = toFrame,
resolution = 1.0)
else:
self.minLabel['text'] = '0.0'
self.maxLabel['text'] = "%.2f" % self.duration
self.frameControl.configure(from_ = 0.0,
to = self.duration,
resolution = 0.01)
def __onPress(self, event):
# Enable slider command
self.fScaleCommand = 1
def __onRelease(self, event):
# Disable slider command
self.fScaleCommand = 0
def selectAnimNamed(self, name):
# Update active anim
self['active'] = name
# Reset play rate
self.component('playRateMenu').selectitem('1.0')
self.setPlayRate('1.0')
# Move slider to zero
self.resetToZero()
def setPlayRate(self, rate):
# set play rate on the actor, although for the AnimPanel
# purpose we don't use the actor's play rate, but rather
# the self.playRate value since we drive the animation
# playback ourselves
self['actor'].setPlayRate(eval(rate), self['active'])
self.playRate = eval(rate)
self.updateDisplay()
def setOffset(self):
newOffset = askfloat(parent = self.interior(),
title = self['text'],
prompt = 'Start offset (seconds):')
if newOffset != None:
self.offset = newOffset
self.updateDisplay()
def enableControl(self):
self.frameActiveVar.set(1)
def disableControl(self):
self.frameActiveVar.set(0)
def displayFrameCounts(self):
self.unitsVar.set(FRAMES)
self.updateDisplay()
def displaySeconds(self):
self.unitsVar.set(SECONDS)
self.updateDisplay()
def play(self, deltaT, fLoop):
if self.frameActiveVar.get():
# Compute new time
self.currT = self.currT + deltaT
if fLoop and self.duration:
# If its looping compute modulo
loopT = self.currT % self.duration
self.goToT(loopT)
else:
if (self.currT > self.maxSeconds):
# Clear this actor control from play list
self['animPanel'].playList.remove(self)
else:
self.goToT(self.currT)
else:
# Clear this actor control from play list
self['animPanel'].playList.remove(self)
def goToF(self, f):
if self.unitsVar.get() == FRAMES:
self.frameControl.set(f)
else:
self.frameControl.set(f/self.fps)
def goToT(self, t):
if self.unitsVar.get() == FRAMES:
self.frameControl.set(t * self.fps)
else:
self.frameControl.set(t)
def goTo(self, t):
# Convert scale value to float
t = float(t)
# Now convert t to seconds for offset calculations
if self.unitsVar.get() == FRAMES:
t = t / self.fps
# Update currT
if self.fScaleCommand or self.fOneShot:
self.currT = t
self.fOneShot = 0
# Now update actor (pose specifed as frame count)
self['actor'].pose(self['active'],
min(self.maxFrame, int(t * self.fps)))
def resetToZero(self):
# This flag forces self.currT to be updated to new value
self.fOneShot = 1
self.goToT(0)
def resetToEnd(self):
# This flag forces self.currT to be updated to new value
self.fOneShot = 1
self.goToT(self.duration)
def nextFrame(self):
"""
There needed to be a better way to select an exact frame number
as the control slider doesn't have the desired resolution
"""
self.fOneShot = 1
self.goToT((self.currT+(1/self.fps))%self.duration)
def previousFrame(self):
"""
There needed to be a better way to select an exact frame number
as the control slider doesn't have the desired resolution
"""
self.fOneShot = 1
self.goToT((self.currT-(1/self.fps))%self.duration)
"""
# EXAMPLE CODE
from direct.actor import Actor
import AnimPanel
a = Actor.Actor({250:{"head":"phase_3/models/char/dogMM_Shorts-head-250",
"torso":"phase_3/models/char/dogMM_Shorts-torso-250",
"legs":"phase_3/models/char/dogMM_Shorts-legs-250"},
500:{"head":"phase_3/models/char/dogMM_Shorts-head-500",
"torso":"phase_3/models/char/dogMM_Shorts-torso-500",
"legs":"phase_3/models/char/dogMM_Shorts-legs-500"},
1000:{"head":"phase_3/models/char/dogMM_Shorts-head-1000",
"torso":"phase_3/models/char/dogMM_Shorts-torso-1000",
"legs":"phase_3/models/char/dogMM_Shorts-legs-1000"}},
{"head":{"walk":"phase_3/models/char/dogMM_Shorts-head-walk", \
"run":"phase_3/models/char/dogMM_Shorts-head-run"}, \
"torso":{"walk":"phase_3/models/char/dogMM_Shorts-torso-walk", \
"run":"phase_3/models/char/dogMM_Shorts-torso-run"}, \
"legs":{"walk":"phase_3/models/char/dogMM_Shorts-legs-walk", \
"run":"phase_3/models/char/dogMM_Shorts-legs-run"}})
a.attach("head", "torso", "joint-head", 250)
a.attach("torso", "legs", "joint-hips", 250)
a.attach("head", "torso", "joint-head", 500)
a.attach("torso", "legs", "joint-hips", 500)
a.attach("head", "torso", "joint-head", 1000)
a.attach("torso", "legs", "joint-hips", 1000)
a.drawInFront("joint-pupil?", "eyes*", -1, lodName=250)
a.drawInFront("joint-pupil?", "eyes*", -1, lodName=500)
a.drawInFront("joint-pupil?", "eyes*", -1, lodName=1000)
a.setLOD(250, 250, 75)
a.setLOD(500, 75, 15)
a.setLOD(1000, 15, 1)
a.fixBounds()
a.reparentTo(render)
a2 = Actor.Actor({250:{"head":"phase_3/models/char/dogMM_Shorts-head-250",
"torso":"phase_3/models/char/dogMM_Shorts-torso-250",
"legs":"phase_3/models/char/dogMM_Shorts-legs-250"},
500:{"head":"phase_3/models/char/dogMM_Shorts-head-500",
"torso":"phase_3/models/char/dogMM_Shorts-torso-500",
"legs":"phase_3/models/char/dogMM_Shorts-legs-500"},
1000:{"head":"phase_3/models/char/dogMM_Shorts-head-1000",
"torso":"phase_3/models/char/dogMM_Shorts-torso-1000",
"legs":"phase_3/models/char/dogMM_Shorts-legs-1000"}},
{"head":{"walk":"phase_3/models/char/dogMM_Shorts-head-walk", \
"run":"phase_3/models/char/dogMM_Shorts-head-run"}, \
"torso":{"walk":"phase_3/models/char/dogMM_Shorts-torso-walk", \
"run":"phase_3/models/char/dogMM_Shorts-torso-run"}, \
"legs":{"walk":"phase_3/models/char/dogMM_Shorts-legs-walk", \
"run":"phase_3/models/char/dogMM_Shorts-legs-run"}})
a2.attach("head", "torso", "joint-head", 250)
a2.attach("torso", "legs", "joint-hips", 250)
a2.attach("head", "torso", "joint-head", 500)
a2.attach("torso", "legs", "joint-hips", 500)
a2.attach("head", "torso", "joint-head", 1000)
a2.attach("torso", "legs", "joint-hips", 1000)
a2.drawInFront("joint-pupil?", "eyes*", -1, lodName=250)
a2.drawInFront("joint-pupil?", "eyes*", -1, lodName=500)
a2.drawInFront("joint-pupil?", "eyes*", -1, lodName=1000)
a2.setLOD(250, 250, 75)
a2.setLOD(500, 75, 15)
a2.setLOD(1000, 15, 1)
a2.fixBounds()
a2.reparentTo(render)
ap = AnimPanel.AnimPanel([a, a2])
# Alternately
ap = a.animPanel()
ap2 = a2.animPanel()
"""
| [
"[email protected]"
]
| |
376560457eb3efbaaf36dab94016bae01fc8b660 | 51f887286aa3bd2c3dbe4c616ad306ce08976441 | /pybind/slxos/v17s_1_02/overlay_class_map/__init__.py | a9b89983ee1e827bbef97d83bab5f884f6e9f073 | [
"Apache-2.0"
]
| permissive | b2220333/pybind | a8c06460fd66a97a78c243bf144488eb88d7732a | 44c467e71b2b425be63867aba6e6fa28b2cfe7fb | refs/heads/master | 2020-03-18T09:09:29.574226 | 2018-04-03T20:09:50 | 2018-04-03T20:09:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,624 | py |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from decimal import Decimal
from bitarray import bitarray
import __builtin__
import cmap_seq
class overlay_class_map(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module brocade-overlay-policy - based on the path /overlay-class-map. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: Define overlay-class-map[Packet Classification criteria
for overlay packets (outer packets).
"""
__slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_rest_name', '_extmethods', '__cmap_name','__cmap_seq',)
_yang_name = 'overlay-class-map'
_rest_name = 'overlay-class-map'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
path_helper_ = kwargs.pop("path_helper", None)
if path_helper_ is False:
self._path_helper = False
elif path_helper_ is not None and isinstance(path_helper_, xpathhelper.YANGPathHelper):
self._path_helper = path_helper_
elif hasattr(self, "_parent"):
path_helper_ = getattr(self._parent, "_path_helper", False)
self._path_helper = path_helper_
else:
self._path_helper = False
extmethods = kwargs.pop("extmethods", None)
if extmethods is False:
self._extmethods = False
elif extmethods is not None and isinstance(extmethods, dict):
self._extmethods = extmethods
elif hasattr(self, "_parent"):
extmethods = getattr(self._parent, "_extmethods", None)
self._extmethods = extmethods
else:
self._extmethods = False
self.__cmap_name = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'[a-zA-Z]{1}([-a-zA-Z0-9_]{0,62})'}), is_leaf=True, yang_name="cmap-name", rest_name="cmap-name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Overlay Class Map Name (Max Size - 63)'}}, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-overlay-policy', defining_module='brocade-overlay-policy', yang_type='map-name-type', is_config=True)
self.__cmap_seq = YANGDynClass(base=YANGListType("cmap_seq_num",cmap_seq.cmap_seq, yang_name="cmap-seq", rest_name="seq", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='cmap-seq-num', extensions={u'tailf-common': {u'info': u'Sequence number', u'cli-no-key-completion': None, u'alt-name': u'seq', u'cli-suppress-list-no': None, u'cli-full-no': None, u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-suppress-mode': None, u'cli-suppress-key-abbreviation': None, u'cli-incomplete-command': None, u'callpoint': u'OverlayClassMapRuleCallPoint'}}), is_container='list', yang_name="cmap-seq", rest_name="seq", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Sequence number', u'cli-no-key-completion': None, u'alt-name': u'seq', u'cli-suppress-list-no': None, u'cli-full-no': None, u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-suppress-mode': None, u'cli-suppress-key-abbreviation': None, u'cli-incomplete-command': None, u'callpoint': u'OverlayClassMapRuleCallPoint'}}, namespace='urn:brocade.com:mgmt:brocade-overlay-policy', defining_module='brocade-overlay-policy', yang_type='list', is_config=True)
load = kwargs.pop("load", None)
if args:
if len(args) > 1:
raise TypeError("cannot create a YANG container with >1 argument")
all_attr = True
for e in self._pyangbind_elements:
if not hasattr(args[0], e):
all_attr = False
break
if not all_attr:
raise ValueError("Supplied object did not have the correct attributes")
for e in self._pyangbind_elements:
nobj = getattr(args[0], e)
if nobj._changed() is False:
continue
setmethod = getattr(self, "_set_%s" % e)
if load is None:
setmethod(getattr(args[0], e))
else:
setmethod(getattr(args[0], e), load=load)
def _path(self):
if hasattr(self, "_parent"):
return self._parent._path()+[self._yang_name]
else:
return [u'overlay-class-map']
def _rest_path(self):
if hasattr(self, "_parent"):
if self._rest_name:
return self._parent._rest_path()+[self._rest_name]
else:
return self._parent._rest_path()
else:
return [u'overlay-class-map']
def _get_cmap_name(self):
"""
Getter method for cmap_name, mapped from YANG variable /overlay_class_map/cmap_name (map-name-type)
"""
return self.__cmap_name
def _set_cmap_name(self, v, load=False):
"""
Setter method for cmap_name, mapped from YANG variable /overlay_class_map/cmap_name (map-name-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_cmap_name is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_cmap_name() directly.
"""
parent = getattr(self, "_parent", None)
if parent is not None and load is False:
raise AttributeError("Cannot set keys directly when" +
" within an instantiated list")
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'[a-zA-Z]{1}([-a-zA-Z0-9_]{0,62})'}), is_leaf=True, yang_name="cmap-name", rest_name="cmap-name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Overlay Class Map Name (Max Size - 63)'}}, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-overlay-policy', defining_module='brocade-overlay-policy', yang_type='map-name-type', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """cmap_name must be of a type compatible with map-name-type""",
'defined-type': "brocade-overlay-policy:map-name-type",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'[a-zA-Z]{1}([-a-zA-Z0-9_]{0,62})'}), is_leaf=True, yang_name="cmap-name", rest_name="cmap-name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Overlay Class Map Name (Max Size - 63)'}}, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-overlay-policy', defining_module='brocade-overlay-policy', yang_type='map-name-type', is_config=True)""",
})
self.__cmap_name = t
if hasattr(self, '_set'):
self._set()
def _unset_cmap_name(self):
self.__cmap_name = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'[a-zA-Z]{1}([-a-zA-Z0-9_]{0,62})'}), is_leaf=True, yang_name="cmap-name", rest_name="cmap-name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Overlay Class Map Name (Max Size - 63)'}}, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-overlay-policy', defining_module='brocade-overlay-policy', yang_type='map-name-type', is_config=True)
def _get_cmap_seq(self):
"""
Getter method for cmap_seq, mapped from YANG variable /overlay_class_map/cmap_seq (list)
"""
return self.__cmap_seq
def _set_cmap_seq(self, v, load=False):
"""
Setter method for cmap_seq, mapped from YANG variable /overlay_class_map/cmap_seq (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_cmap_seq is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_cmap_seq() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("cmap_seq_num",cmap_seq.cmap_seq, yang_name="cmap-seq", rest_name="seq", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='cmap-seq-num', extensions={u'tailf-common': {u'info': u'Sequence number', u'cli-no-key-completion': None, u'alt-name': u'seq', u'cli-suppress-list-no': None, u'cli-full-no': None, u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-suppress-mode': None, u'cli-suppress-key-abbreviation': None, u'cli-incomplete-command': None, u'callpoint': u'OverlayClassMapRuleCallPoint'}}), is_container='list', yang_name="cmap-seq", rest_name="seq", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Sequence number', u'cli-no-key-completion': None, u'alt-name': u'seq', u'cli-suppress-list-no': None, u'cli-full-no': None, u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-suppress-mode': None, u'cli-suppress-key-abbreviation': None, u'cli-incomplete-command': None, u'callpoint': u'OverlayClassMapRuleCallPoint'}}, namespace='urn:brocade.com:mgmt:brocade-overlay-policy', defining_module='brocade-overlay-policy', yang_type='list', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """cmap_seq must be of a type compatible with list""",
'defined-type': "list",
'generated-type': """YANGDynClass(base=YANGListType("cmap_seq_num",cmap_seq.cmap_seq, yang_name="cmap-seq", rest_name="seq", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='cmap-seq-num', extensions={u'tailf-common': {u'info': u'Sequence number', u'cli-no-key-completion': None, u'alt-name': u'seq', u'cli-suppress-list-no': None, u'cli-full-no': None, u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-suppress-mode': None, u'cli-suppress-key-abbreviation': None, u'cli-incomplete-command': None, u'callpoint': u'OverlayClassMapRuleCallPoint'}}), is_container='list', yang_name="cmap-seq", rest_name="seq", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Sequence number', u'cli-no-key-completion': None, u'alt-name': u'seq', u'cli-suppress-list-no': None, u'cli-full-no': None, u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-suppress-mode': None, u'cli-suppress-key-abbreviation': None, u'cli-incomplete-command': None, u'callpoint': u'OverlayClassMapRuleCallPoint'}}, namespace='urn:brocade.com:mgmt:brocade-overlay-policy', defining_module='brocade-overlay-policy', yang_type='list', is_config=True)""",
})
self.__cmap_seq = t
if hasattr(self, '_set'):
self._set()
def _unset_cmap_seq(self):
self.__cmap_seq = YANGDynClass(base=YANGListType("cmap_seq_num",cmap_seq.cmap_seq, yang_name="cmap-seq", rest_name="seq", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='cmap-seq-num', extensions={u'tailf-common': {u'info': u'Sequence number', u'cli-no-key-completion': None, u'alt-name': u'seq', u'cli-suppress-list-no': None, u'cli-full-no': None, u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-suppress-mode': None, u'cli-suppress-key-abbreviation': None, u'cli-incomplete-command': None, u'callpoint': u'OverlayClassMapRuleCallPoint'}}), is_container='list', yang_name="cmap-seq", rest_name="seq", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Sequence number', u'cli-no-key-completion': None, u'alt-name': u'seq', u'cli-suppress-list-no': None, u'cli-full-no': None, u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-suppress-mode': None, u'cli-suppress-key-abbreviation': None, u'cli-incomplete-command': None, u'callpoint': u'OverlayClassMapRuleCallPoint'}}, namespace='urn:brocade.com:mgmt:brocade-overlay-policy', defining_module='brocade-overlay-policy', yang_type='list', is_config=True)
cmap_name = __builtin__.property(_get_cmap_name, _set_cmap_name)
cmap_seq = __builtin__.property(_get_cmap_seq, _set_cmap_seq)
_pyangbind_elements = {'cmap_name': cmap_name, 'cmap_seq': cmap_seq, }
| [
"[email protected]"
]
| |
7d4489bec75756fcdc079f5f14ff4f709be1837b | 5fa91971a552de35422698ad3e371392fd5eb48a | /docs/mcpi/algorytmy/mcpi-lpi02.py | 5881d83e5b722c10f474aaac3deba06ea22d8b2e | [
"MIT",
"CC-BY-SA-4.0"
]
| permissive | koduj-z-klasa/python101 | 64b0bf24da6c7fc29c0d3c5a74ce7975d648b760 | accfca2a8a0f2b9eba884bffe31be6d1e73fb615 | refs/heads/master | 2022-06-06T09:29:01.688553 | 2022-05-22T19:50:09 | 2022-05-22T19:50:09 | 23,770,911 | 45 | 182 | MIT | 2022-03-31T10:40:13 | 2014-09-07T21:01:09 | Python | UTF-8 | Python | false | false | 2,565 | py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import random
from time import sleep
import mcpi.minecraft as minecraft # import modułu minecraft
import mcpi.block as block # import modułu block
import local.minecraftstuff as mcstuff
os.environ["USERNAME"] = "Steve" # nazwa użytkownika
os.environ["COMPUTERNAME"] = "mykomp" # nazwa komputera
mc = minecraft.Minecraft.create("192.168.1.10") # połączenie z serwerem
def plac(x, y, z, roz=10, gracz=False):
"""Funkcja wypełnia sześcienny obszar od podanej pozycji
powietrzem i opcjonalnie umieszcza gracza w środku.
Parametry: x, y, z - współrzędne pozycji początkowej,
roz - rozmiar wypełnianej przestrzeni,
gracz - czy umieścić gracza w środku
Wymaga: globalnych obiektów mc i block.
"""
podloga = block.STONE
wypelniacz = block.AIR
# kamienna podłoże
mc.setBlocks(x, y - 1, z, x + roz, y - 1, z + roz, podloga)
# czyszczenie
mc.setBlocks(x, y, z, x + roz, y + roz, z + roz, wypelniacz)
# umieść gracza w środku
if gracz:
mc.player.setPos(x + roz / 2, y + roz / 2, z + roz / 2)
def model(promien, x, y, z):
"""
Fukcja buduje obrys kwadratu, którego środek to punkt x, y, z
oraz koło wpisane w ten kwadrat
"""
mcfig = mcstuff.MinecraftDrawing(mc)
obrys = block.SANDSTONE
wypelniacz = block.AIR
mc.setBlocks(x - promien, y, z - promien, x +
promien, y, z + promien, obrys)
mc.setBlocks(x - promien + 1, y, z - promien + 1, x +
promien - 1, y, z + promien - 1, wypelniacz)
mcfig.drawHorizontalCircle(0, 0, 0, promien, block.GRASS)
def liczbaPi():
r = float(raw_input("Podaj promień koła: "))
model(r, 0, 0, 0)
# pobieramy ilość punktów w kwadracie
ileKw = int(raw_input("Podaj ilość losowanych punktów: "))
ileKo = 0 # ilość punktów w kole
blok = block.SAND
for i in range(ileKw):
x = round(random.uniform(-r, r))
y = round(random.uniform(-r, r))
print x, y
if abs(x)**2 + abs(y)**2 <= r**2:
ileKo += 1
# umieść blok w MC Pi
mc.setBlock(x, 10, y, blok)
mc.postToChat("W kole = " + str(ileKo) + " W Kwadracie = " + str(ileKw))
pi = 4 * ileKo / float(ileKw)
mc.postToChat("Pi w przyblizeniu: {:.10f}".format(pi))
def main():
mc.postToChat("LiczbaPi") # wysłanie komunikatu do mc
plac(-50, 0, -50, 100)
mc.player.setPos(20, 20, 0)
liczbaPi()
return 0
if __name__ == '__main__':
main()
| [
"[email protected]"
]
| |
41348a2dd0b811a9e5820c028fb4d84d67ede459 | 7ee1fd7584f8770cd2381d85f797bf85cb9b4b67 | /usuarios/applications/users/functions.py | 7518ab24ad5b24eb53709d36fd01737178f8f777 | []
| no_license | neunapp/usuariosdj | 3171160fdf6898d07d6b353d034c70801e4bc21b | 3fe69b7357757baa5d799b614f232d75ed659502 | refs/heads/master | 2022-12-01T16:51:00.432272 | 2020-09-17T14:28:21 | 2020-09-17T14:28:21 | 237,993,639 | 4 | 2 | null | 2022-11-22T05:17:26 | 2020-02-03T15:10:33 | Python | UTF-8 | Python | false | false | 206 | py | # funciones extra de la aplicacion users
import random
import string
def code_generator(size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size)) | [
"[email protected]"
]
| |
03a11a480258f5444025f7b60cf63fcf26362edb | c33844f13a625f9b3c908ea8816696a0b38abbac | /expenditure/migrations/0001_initial.py | dc5f3853c79d4d290e1e897dfb0381cd9729c7c3 | []
| no_license | jkimuli/clinica | d6ddb72b4ba56e142f12b77593d2c4e68b3e3237 | 03cf956781ff5a50d692ca07799a73c36111a0aa | refs/heads/master | 2022-12-21T20:13:39.454392 | 2020-11-09T08:13:25 | 2020-11-09T08:13:25 | 21,300,924 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,097 | py | # Generated by Django 2.2.5 on 2020-06-17 16:16
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Expense',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('expense_date', models.DateField(auto_now_add=True, verbose_name='Date Expense Incurred')),
('particulars', models.TextField(verbose_name='Particulars')),
('amount', models.DecimalField(decimal_places=2, max_digits=12, verbose_name='Amount')),
('incurred_by', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='Employee Name')),
],
options={
'verbose_name_plural': 'Expenses',
},
),
]
| [
"[email protected]"
]
| |
e4e82580ad98bbcb298532c026df83965c2ea339 | 05148c0ea223cfc7ed9d16234ab3e6bb40885e9d | /Packages/matplotlib-2.2.2/lib/mpl_examples/images_contours_and_fields/triplot_demo.py | d3a65762d021e09952a9512f7aa6c3df6982239b | [
"MIT"
]
| permissive | NightKirie/NCKU_NLP_2018_industry3 | 9ee226e194287fd9088429f87c58c874e050a8b3 | 23ac13644b140587e23cfeffb114c7c6f46f17a2 | refs/heads/master | 2021-06-05T05:33:09.510647 | 2018-07-05T10:19:47 | 2018-07-05T10:19:47 | 133,680,341 | 1 | 4 | MIT | 2020-05-20T16:29:54 | 2018-05-16T14:43:38 | Python | UTF-8 | Python | false | false | 4,772 | py | """
============
Triplot Demo
============
Creating and plotting unstructured triangular grids.
"""
import matplotlib.pyplot as plt
import matplotlib.tri as tri
import numpy as np
###############################################################################
# Creating a Triangulation without specifying the triangles results in the
# Delaunay triangulation of the points.
# First create the x and y coordinates of the points.
n_angles = 36
n_radii = 8
min_radius = 0.25
radii = np.linspace(min_radius, 0.95, n_radii)
angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False)
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
angles[:, 1::2] += np.pi / n_angles
x = (radii * np.cos(angles)).flatten()
y = (radii * np.sin(angles)).flatten()
# Create the Triangulation; no triangles so Delaunay triangulation created.
triang = tri.Triangulation(x, y)
# Mask off unwanted triangles.
triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),
y[triang.triangles].mean(axis=1))
< min_radius)
###############################################################################
# Plot the triangulation.
plt.figure()
plt.gca().set_aspect('equal')
plt.triplot(triang, 'bo-', lw=1)
plt.title('triplot of Delaunay triangulation')
###############################################################################
# You can specify your own triangulation rather than perform a Delaunay
# triangulation of the points, where each triangle is given by the indices of
# the three points that make up the triangle, ordered in either a clockwise or
# anticlockwise manner.
xy = np.asarray([
[-0.101, 0.872], [-0.080, 0.883], [-0.069, 0.888], [-0.054, 0.890],
[-0.045, 0.897], [-0.057, 0.895], [-0.073, 0.900], [-0.087, 0.898],
[-0.090, 0.904], [-0.069, 0.907], [-0.069, 0.921], [-0.080, 0.919],
[-0.073, 0.928], [-0.052, 0.930], [-0.048, 0.942], [-0.062, 0.949],
[-0.054, 0.958], [-0.069, 0.954], [-0.087, 0.952], [-0.087, 0.959],
[-0.080, 0.966], [-0.085, 0.973], [-0.087, 0.965], [-0.097, 0.965],
[-0.097, 0.975], [-0.092, 0.984], [-0.101, 0.980], [-0.108, 0.980],
[-0.104, 0.987], [-0.102, 0.993], [-0.115, 1.001], [-0.099, 0.996],
[-0.101, 1.007], [-0.090, 1.010], [-0.087, 1.021], [-0.069, 1.021],
[-0.052, 1.022], [-0.052, 1.017], [-0.069, 1.010], [-0.064, 1.005],
[-0.048, 1.005], [-0.031, 1.005], [-0.031, 0.996], [-0.040, 0.987],
[-0.045, 0.980], [-0.052, 0.975], [-0.040, 0.973], [-0.026, 0.968],
[-0.020, 0.954], [-0.006, 0.947], [ 0.003, 0.935], [ 0.006, 0.926],
[ 0.005, 0.921], [ 0.022, 0.923], [ 0.033, 0.912], [ 0.029, 0.905],
[ 0.017, 0.900], [ 0.012, 0.895], [ 0.027, 0.893], [ 0.019, 0.886],
[ 0.001, 0.883], [-0.012, 0.884], [-0.029, 0.883], [-0.038, 0.879],
[-0.057, 0.881], [-0.062, 0.876], [-0.078, 0.876], [-0.087, 0.872],
[-0.030, 0.907], [-0.007, 0.905], [-0.057, 0.916], [-0.025, 0.933],
[-0.077, 0.990], [-0.059, 0.993]])
x = np.degrees(xy[:, 0])
y = np.degrees(xy[:, 1])
triangles = np.asarray([
[67, 66, 1], [65, 2, 66], [ 1, 66, 2], [64, 2, 65], [63, 3, 64],
[60, 59, 57], [ 2, 64, 3], [ 3, 63, 4], [ 0, 67, 1], [62, 4, 63],
[57, 59, 56], [59, 58, 56], [61, 60, 69], [57, 69, 60], [ 4, 62, 68],
[ 6, 5, 9], [61, 68, 62], [69, 68, 61], [ 9, 5, 70], [ 6, 8, 7],
[ 4, 70, 5], [ 8, 6, 9], [56, 69, 57], [69, 56, 52], [70, 10, 9],
[54, 53, 55], [56, 55, 53], [68, 70, 4], [52, 56, 53], [11, 10, 12],
[69, 71, 68], [68, 13, 70], [10, 70, 13], [51, 50, 52], [13, 68, 71],
[52, 71, 69], [12, 10, 13], [71, 52, 50], [71, 14, 13], [50, 49, 71],
[49, 48, 71], [14, 16, 15], [14, 71, 48], [17, 19, 18], [17, 20, 19],
[48, 16, 14], [48, 47, 16], [47, 46, 16], [16, 46, 45], [23, 22, 24],
[21, 24, 22], [17, 16, 45], [20, 17, 45], [21, 25, 24], [27, 26, 28],
[20, 72, 21], [25, 21, 72], [45, 72, 20], [25, 28, 26], [44, 73, 45],
[72, 45, 73], [28, 25, 29], [29, 25, 31], [43, 73, 44], [73, 43, 40],
[72, 73, 39], [72, 31, 25], [42, 40, 43], [31, 30, 29], [39, 73, 40],
[42, 41, 40], [72, 33, 31], [32, 31, 33], [39, 38, 72], [33, 72, 38],
[33, 38, 34], [37, 35, 38], [34, 38, 35], [35, 37, 36]])
###############################################################################
# Rather than create a Triangulation object, can simply pass x, y and triangles
# arrays to triplot directly. It would be better to use a Triangulation object
# if the same triangulation was to be used more than once to save duplicated
# calculations.
plt.figure()
plt.gca().set_aspect('equal')
plt.triplot(x, y, triangles, 'go-', lw=1.0)
plt.title('triplot of user-specified triangulation')
plt.xlabel('Longitude (degrees)')
plt.ylabel('Latitude (degrees)')
plt.show()
| [
"[email protected]"
]
| |
4b596fb862cd2f289858a3f819e22893131b53cb | 713f9168a7ba68740bb9b4ea6994e853a56d2d5c | /2022-05-30-python/day2/average_demo.py | e6b23121568eb162e8625c15b056b32811bde7b2 | []
| no_license | marko-knoebl/courses-code | ba7723c9a61861b037422670b98276fed41060e2 | faeaa31c9a156a02e4e9169bc16f229cdaee085d | refs/heads/master | 2022-12-29T02:13:12.653745 | 2022-12-16T09:21:18 | 2022-12-16T09:21:18 | 142,756,698 | 16 | 10 | null | 2022-03-08T22:30:11 | 2018-07-29T11:51:04 | Jupyter Notebook | UTF-8 | Python | false | false | 109 | py | import average
print(average.average(1, 2))
print(average.average(1, 3))
print(average.average_short(2, 3))
| [
"[email protected]"
]
| |
56cbe3a325b7e39dbfcee37c3ce40d0b704f5713 | e23a4f57ce5474d468258e5e63b9e23fb6011188 | /120_design_patterns/006_adapter/examples/adapter_005.py | f7aff08228bdda9c77bd6d64d410d32bb64c4da1 | []
| no_license | syurskyi/Python_Topics | 52851ecce000cb751a3b986408efe32f0b4c0835 | be331826b490b73f0a176e6abed86ef68ff2dd2b | refs/heads/master | 2023-06-08T19:29:16.214395 | 2023-05-29T17:09:11 | 2023-05-29T17:09:11 | 220,583,118 | 3 | 2 | null | 2023-02-16T03:08:10 | 2019-11-09T02:58:47 | Python | UTF-8 | Python | false | false | 4,088 | py | """
The Adapter pattern is a structural design pattern. It allows a Client to access
functionalities of a Supplier.
Without an Adapter the Client can not access such functionalities.
This pattern can be implemented with an OBJECT approach or a CLASS approach.
"""
# Client
class Smartphone(object):
max_input_voltage = 5
@classmethod
def outcome(cls, input_voltage):
if input_voltage > cls.max_input_voltage:
print("Input voltage: {}V -- BURNING!!!".format(input_voltage))
else:
print("Input voltage: {}V -- Charging...".format(input_voltage))
def charge(self, input_voltage):
"""Charge the phone with the given input voltage."""
self.outcome(input_voltage)
# Supplier
class Socket(object):
output_voltage = None
class EUSocket(Socket):
output_voltage = 230
class USSocket(Socket):
output_voltage = 120
################################################################################
# Approach A: OBJECT Adapter. The adapter encapsulates client and supplier.
################################################################################
class EUAdapter(object):
"""EUAdapter encapsulates client (Smartphone) and supplier (EUSocket)."""
input_voltage = EUSocket.output_voltage
output_voltage = Smartphone.max_input_voltage
class USAdapter(object):
"""USAdapter encapsulates client (Smartphone) and supplier (USSocket)."""
input_voltage = USSocket.output_voltage
output_voltage = Smartphone.max_input_voltage
################################################################################
# Approach B: CLASS Adapter. Adapt the Client through multiple inheritance.
################################################################################
class CannotTransformVoltage(Exception):
"""Exception raised by the SmartphoneAdapter.
This exception represents the fact that an adapter could not provide the
right voltage to the Smartphone if the voltage of the Socket is wrong."""
pass
class SmartphoneAdapter(Smartphone, Socket):
@classmethod
def transform_voltage(cls, input_voltage):
if input_voltage == cls.output_voltage:
return cls.max_input_voltage
else:
raise CannotTransformVoltage(
"Can\'t transform {0}-{1}V. This adapter transforms {2}-{1}V.".format(
input_voltage, cls.max_input_voltage, cls.output_voltage
)
)
@classmethod
def charge(cls, input_voltage):
try:
voltage = cls.transform_voltage(input_voltage)
cls.outcome(voltage)
except CannotTransformVoltage as e:
print(e)
class SmartphoneEUAdapter(SmartphoneAdapter, EUSocket):
"""System (smartphone + adapter) for a European Socket.
Note: SmartphoneAdapter already inherited from Smartphone and Socket, but by
re-inheriting from EUSocket we redefine all the stuff inherited from Socket.
"""
pass
class SmartphoneUSAdapter(SmartphoneAdapter, USSocket):
"""System (smartphone + adapter) for an American Socket."""
pass
def main():
print("Smartphone without adapter")
smartphone = Smartphone()
smartphone.charge(EUSocket.output_voltage)
smartphone.charge(USSocket.output_voltage)
print("\nSmartphone with EU adapter (object adapter approach)")
smartphone.charge(EUAdapter.output_voltage)
print("\nSmartphone with US adapter (object adapter approach)")
smartphone.charge(USAdapter.output_voltage)
print("\nSmartphone with EU adapter (class adapter approach)")
smarthone_with_eu_adapter = SmartphoneEUAdapter()
smarthone_with_eu_adapter.charge(EUSocket.output_voltage)
smarthone_with_eu_adapter.charge(USSocket.output_voltage)
print("\nSmartphone with US adapter (class adapter approach)")
smarthone_with_us_adapter = SmartphoneUSAdapter()
smarthone_with_us_adapter.charge(EUSocket.output_voltage)
smarthone_with_us_adapter.charge(USSocket.output_voltage)
if __name__ == "__main__":
main()
| [
"[email protected]"
]
| |
76705674841dca7e1c0fdbec51fb4f0b7f989140 | 49f61714a6f78d984fd2194d6064d84e891bc5b7 | /2019-1/220/users/2882/codes/1736_2496.py | 34aaeee55371a5a36435ec18f6e128cfa904b6b2 | []
| no_license | psbarros/Variaveis3 | b5c4e1517e7d94a846ee03791d25d5821a1c651c | 3dcf6f810709ce03c78335acf9533e008a2ae125 | refs/heads/master | 2023-06-13T07:05:00.878430 | 2021-07-06T17:51:37 | 2021-07-06T17:51:37 | 383,549,597 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 131 | py | num=int(input("Numero: "))
i=0
soma=0
while (num != -1):
soma=soma+num
num=int(input("Numero: "))
i=i+1
print(soma)
| [
"[email protected]"
]
| |
29ab49aa05b4049510072ab0452bce50284ecf40 | ea1373d9a58ad198c15d35a6daddb4e06d21aa39 | /application-code/show3d_balls.py | 4d086af1e8e3e1d75769cd87bd256539b3669351 | []
| no_license | screnary/VoxSegNet | bb2778dfc460dfafdbd923f79755f7f0776dc36f | 264f2efc0a589018a1fc68c111626beacbe095a5 | refs/heads/master | 2020-09-04T03:41:47.067129 | 2019-11-07T06:34:29 | 2019-11-07T06:34:29 | 219,649,857 | 5 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,889 | py | """ Original Author: Haoqiang Fan """
import numpy as np
import ctypes as ct
import cv2
import sys
import os
import pdb
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
showsz=800
mousex,mousey=0.5,0.5
ix,iy=-1,-1
zoom=1.0
changed=True
dragging=False
def onmouse(event,x,y,flags,param): # *args
# args=[event,x,y,flags,param]
global mousex,mousey,changed,dragging,ix,iy
# pdb.set_trace()
if event == cv2.EVENT_LBUTTONDOWN:
dragging = True
# init ix,iy when push down left button
iy = y
ix = x
# pdb.set_trace()
#当左键按下并移动时旋转图形,event可以查看移动,flag查看是否按下
elif event==cv2.EVENT_MOUSEMOVE and flags==cv2.EVENT_FLAG_LBUTTON:
if dragging == True:
dx=y-iy
dy=x-ix
mousex+=dx/float(showsz) # 控制旋转角
mousey+=dy/float(showsz)
changed=True
#当鼠标松开时停止绘图
elif event == cv2.EVENT_LBUTTONUP:
dragging == False
cv2.namedWindow('show3d')
cv2.moveWindow('show3d',0,0)
cv2.setMouseCallback('show3d',onmouse)
# dll=np.ctypeslib.load_library(os.path.join(BASE_DIR, 'render_balls_so'),'.')
# pdb.set_trace()
dll=np.ctypeslib.load_library(os.path.join(BASE_DIR, 'render'),'.')
def showpoints(xyz,c_gt=None, c_pred=None ,waittime=0,showrot=False,
magnifyBlue=0,freezerot=False,background=(0,0,0),
normalizecolor=True,ballradius=8,savedir='show3d.png'):
global showsz,mousex,mousey,zoom,changed
xyz=xyz-xyz.mean(axis=0)
radius=((xyz**2).sum(axis=-1)**0.5).max()
xyz/=(radius*2.2)/showsz
if c_gt is None:
c0=np.zeros((len(xyz),),dtype='float32')+255 # green
c1=np.zeros((len(xyz),),dtype='float32')+255 # red
c2=np.zeros((len(xyz),),dtype='float32')+255 # blue
else:
c0=c_gt[:,0]
c1=c_gt[:,1]
c2=c_gt[:,2]
if normalizecolor:
c0/=(c0.max()+1e-14)/255.0
c1/=(c1.max()+1e-14)/255.0
c2/=(c2.max()+1e-14)/255.0
c0=np.require(c0,'float32','C')
c1=np.require(c1,'float32','C')
c2=np.require(c2,'float32','C')
show=np.zeros((showsz,showsz,3),dtype='uint8')
def render():
rotmat=np.eye(3)
if not freezerot:
xangle=(mousey-0.5)*np.pi*0.25
# xangle=(mousey-0.5)*np.pi*1.2
else:
xangle=0
rotmat=rotmat.dot(np.array([
[1.0,0.0,0.0],
[0.0,np.cos(xangle),-np.sin(xangle)],
[0.0,np.sin(xangle),np.cos(xangle)],
]))
if not freezerot:
yangle=(mousex-0.5)*np.pi*0.25
# yangle=(mousex-0.5)*np.pi*1.2
else:
yangle=0
rotmat=rotmat.dot(np.array([
[np.cos(yangle),0.0,-np.sin(yangle)],
[0.0,1.0,0.0],
[np.sin(yangle),0.0,np.cos(yangle)],
]))
rotmat*=zoom
nxyz=xyz.dot(rotmat)+[showsz/2,showsz/2,0]
ixyz=nxyz.astype('int32')
show[:]=background
dll.render_ball(
ct.c_int(show.shape[0]),
ct.c_int(show.shape[1]),
show.ctypes.data_as(ct.c_void_p),
ct.c_int(ixyz.shape[0]),
ixyz.ctypes.data_as(ct.c_void_p),
c0.ctypes.data_as(ct.c_void_p),
c1.ctypes.data_as(ct.c_void_p),
c2.ctypes.data_as(ct.c_void_p),
ct.c_int(ballradius)
)
if magnifyBlue>0:
show[:,:,0]=np.maximum(show[:,:,0],np.roll(show[:,:,0],1,axis=0))
if magnifyBlue>=2:
show[:,:,0]=np.maximum(show[:,:,0],np.roll(show[:,:,0],-1,axis=0))
show[:,:,0]=np.maximum(show[:,:,0],np.roll(show[:,:,0],1,axis=1))
if magnifyBlue>=2:
show[:,:,0]=np.maximum(show[:,:,0],np.roll(show[:,:,0],-1,axis=1))
if showrot:
# cv2.putText(show,'xangle %d' % (int(xangle/np.pi*180)),(30,showsz-30),0,0.5,cv2.cv.CV_RGB(255,0,0))
# cv2.putText(show,'yangle %d' % (int(yangle/np.pi*180)),(30,showsz-50),0,0.5,cv2.cv.CV_RGB(255,0,0))
# cv2.putText(show,'zoom %d%%' % (int(zoom*100)),(30,showsz-70),0,0.5,cv2.cv.CV_RGB(255,0,0))
cv2.putText(show,'xangle %d' % (int(xangle/np.pi*180)),(30,showsz-30),0,0.5,(255,0,0))
cv2.putText(show,'yangle %d' % (int(yangle/np.pi*180)),(30,showsz-50),0,0.5,(255,0,0))
cv2.putText(show,'zoom %d%%' % (int(zoom*100)),(30,showsz-70),0,0.5,(255,0,0))
changed=True
while True:
if changed:
render()
changed=False
cv2.imshow('show3d',show)
if waittime==0:
cmd=cv2.waitKey(10) % 256
else:
cmd=cv2.waitKey(waittime) % 256
if cmd==ord('q'):
break
elif cmd==ord('Q'):
sys.exit(0)
if cmd==ord('t') or cmd == ord('p'):
if cmd == ord('t'):
if c_gt is None:
c0=np.zeros((len(xyz),),dtype='float32')+255
c1=np.zeros((len(xyz),),dtype='float32')+255
c2=np.zeros((len(xyz),),dtype='float32')+255
else:
c0=c_gt[:,0]
c1=c_gt[:,1]
c2=c_gt[:,2]
else:
if c_pred is None:
c0=np.zeros((len(xyz),),dtype='float32')+255
c1=np.zeros((len(xyz),),dtype='float32')+255
c2=np.zeros((len(xyz),),dtype='float32')+255
else:
c0=c_pred[:,0]
c1=c_pred[:,1]
c2=c_pred[:,2]
if normalizecolor:
c0/=(c0.max()+1e-14)/255.0
c1/=(c1.max()+1e-14)/255.0
c2/=(c2.max()+1e-14)/255.0
c0=np.require(c0,'float32','C')
c1=np.require(c1,'float32','C')
c2=np.require(c2,'float32','C')
changed = True
if cmd==ord('j'): # rotate
mousey-=10/float(showsz)
changed=True
elif cmd==ord('l'):
mousey+=10/float(showsz)
changed=True
if cmd==ord('i'):
mousex-=10/float(showsz)
changed=True
elif cmd==ord('k'):
mousex+=10/float(showsz)
changed=True
if cmd==ord('n'): # near
zoom*=1.1
changed=True
elif cmd==ord('m'): # far
zoom/=1.1
changed=True
elif cmd==ord('r'):
zoom=1.0
changed=True
elif cmd==ord('s'):
cv2.imwrite(savedir,show)
if cmd==ord('f'):
freezerot = not freezerot
if waittime!=0:
break
return cmd
if __name__=='__main__':
np.random.seed(100)
showpoints(np.random.randn(2500,3))
| [
"[email protected]"
]
| |
3a3f131e46c372e5a1ffb23605dd5ea5ac592973 | 4652255cc1adaed1cf808f5475aa06265ee2016a | /fluiddb/security/test/test_oauth.py | d9a3fda028a68004273e684c46f1c20fd2a3f13a | [
"Apache-2.0"
]
| permissive | fluidinfo/fluiddb | ca55b640ce44be53614068caade373046bdf30e4 | b5a8c8349f3eaf3364cc4efba4736c3e33b30d96 | refs/heads/master | 2021-01-11T08:16:01.635285 | 2016-03-27T21:11:58 | 2016-03-27T21:11:58 | 54,848,235 | 3 | 2 | null | null | null | null | UTF-8 | Python | false | false | 4,626 | py | from random import sample
from fluiddb.data.exceptions import UnknownUserError
from fluiddb.data.system import createSystemData
from fluiddb.data.user import getUsers, ALPHABET
from fluiddb.model.oauth import (
OAuthAccessToken, OAuthRenewalToken, OAuthConsumerAPI,
UnknownConsumerError)
from fluiddb.model.user import UserAPI, getUser
from fluiddb.security.exceptions import InvalidOAuthTokenError
from fluiddb.security.oauth import SecureOAuthConsumerAPI
from fluiddb.testing.basic import FluidinfoTestCase
from fluiddb.testing.resources import (
ConfigResource, DatabaseResource, CacheResource)
class SecureOAuthConsumerAPITest(FluidinfoTestCase):
resources = [('cache', CacheResource()),
('config', ConfigResource()),
('store', DatabaseResource())]
def setUp(self):
super(SecureOAuthConsumerAPITest, self).setUp()
createSystemData()
secret = ''.join(sample(ALPHABET, 16))
self.config.set('oauth', 'access-secret', secret)
def testRenewToken(self):
"""
L{SecureOAuthConsumerAPI.renewToken} generates a new
L{OAuthRenewalToken} and L{OAuthAccessToken}, given a valid
L{OAuthRenewalToken}.
"""
UserAPI().create([
(u'consumer', u'secret', u'Consumer', u'[email protected]'),
(u'user', u'secret', u'User', u'[email protected]')])
consumer = getUser(u'consumer')
user = getUser(u'user')
api = OAuthConsumerAPI()
api.register(consumer)
token = api.getRenewalToken(consumer, user).encrypt()
encryptedRenewalToken, encryptedAccessToken = (
SecureOAuthConsumerAPI().renewToken(u'consumer', token))
renewalToken = OAuthRenewalToken.decrypt(consumer,
encryptedRenewalToken)
accessToken = OAuthAccessToken.decrypt(consumer, encryptedAccessToken)
self.assertTrue(isinstance(renewalToken, OAuthRenewalToken))
self.assertIdentical(consumer, renewalToken.consumer)
self.assertIdentical(user, renewalToken.user)
self.assertTrue(isinstance(accessToken, OAuthAccessToken))
self.assertIdentical(consumer, accessToken.consumer)
self.assertIdentical(user, accessToken.user)
def testRenewTokenWithUnknownConsumer(self):
"""
L{SecureOAuthConsumerAPI.renewToken} raises an L{UnknownConsumerError}
if an L{OAuthRenewalToken} for an unknown consumer is used to generate
a new L{OAuthAccessToken}.
"""
UserAPI().create([
(u'consumer', u'secret', u'Consumer', u'[email protected]'),
(u'user', u'secret', u'User', u'[email protected]')])
consumer = getUser(u'consumer')
user = getUser(u'user')
api = OAuthConsumerAPI()
api.register(consumer)
token = api.getRenewalToken(consumer, user).encrypt()
getUsers(usernames=[u'consumer']).remove()
self.assertRaises(UnknownConsumerError,
SecureOAuthConsumerAPI().renewToken, u'consumer',
token)
def testRenewTokenWithUnknownUser(self):
"""
L{SecureOAuthConsumerAPI.renewToken} raises an L{UnknownUserError} if
an L{OAuthRenewalToken} for an unknown L{User} is used to generate a
new L{OAuthAccessToken}.
"""
UserAPI().create([
(u'consumer', u'secret', u'Consumer', u'[email protected]'),
(u'user', u'secret', u'User', u'[email protected]')])
consumer = getUser(u'consumer')
user = getUser(u'user')
api = OAuthConsumerAPI()
api.register(consumer)
token = api.getRenewalToken(consumer, user).encrypt()
getUsers(usernames=[u'user']).remove()
self.assertRaises(UnknownUserError,
SecureOAuthConsumerAPI().renewToken, u'consumer',
token)
def testRenewTokenWithInvalidRenewalToken(self):
"""
L{SecureOAuthConsumerAPI.renewToken} raises an
L{InvalidOAuthTokenError} if the specified encrypted
L{OAuthRenewalToken} can't be decrypted.
"""
UserAPI().create([
(u'consumer', u'secret', u'Consumer', u'[email protected]'),
(u'user', u'secret', u'User', u'[email protected]')])
consumer = getUser(u'consumer')
OAuthConsumerAPI().register(consumer)
self.assertRaises(InvalidOAuthTokenError,
SecureOAuthConsumerAPI().renewToken, u'consumer',
'invalid')
| [
"[email protected]"
]
| |
166a8e18e0364eb38cc993b84b761ad183c899b9 | e534dcb324d03aa0c613f53e66d56d7c6c54364e | /ensemble/ccc_acc_nin.py | cbc127cc5466841aa4c8c5b7a79e38dbd3eeeacd | []
| no_license | kobeeraveendran/machine-learning | 4e2a3b1441852adcc7cc404bbb4afa46c40a153c | ca9d4310608a0df737e4482227c60db5d57a320f | refs/heads/master | 2021-03-27T12:43:27.401317 | 2019-04-03T16:09:12 | 2019-04-03T16:09:12 | 119,780,898 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,481 | py | from keras.models import Model, Input
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D, Activation, Average, Dropout
from keras.utils import to_categorical
from keras.metrics import categorical_accuracy
from keras.losses import categorical_crossentropy
from keras.callbacks import ModelCheckpoint, TensorBoard
from keras.optimizers import Adam
from keras.datasets import cifar10
from sklearn.metrics import accuracy_score
from keras import backend as K
import tensorflow as tf
import numpy as np
import time
import os
import matplotlib.pyplot as plt
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import keras.backend as K
config = K.tf.ConfigProto()
config.gpu_options.allow_growth = True
session = K.tf.Session(config = config)
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train = x_train / 255.0
x_test = x_test / 255.0
y_train = to_categorical(y_train, num_classes = 10)
print('x_train shape: ', x_train.shape)
print('y_train shape: ', y_train.shape)
print('x_test shape: ', x_test.shape)
print('y_test shape: ', y_test.shape)
# shape of an example (all models use the same input shapes)
input_shape = x_train[0, ...].shape
model_input = Input(shape = input_shape)
image_classes = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
# model 1: ConvPool - CNN - C
def conv_pool_cnn(model_input):
x = model_input
# "Striving for Simplicity: The All Convolutional Net"
x = Conv2D(96, kernel_size = (3, 3), activation = 'relu', padding = 'same')(x)
x = Conv2D(96, kernel_size = (3, 3), activation = 'relu', padding = 'same')(x)
x = Conv2D(96, kernel_size = (3, 3), activation = 'relu', padding = 'same')(x)
x = MaxPooling2D(pool_size = (3, 3), strides = 2)(x)
x = Conv2D(192, kernel_size = (3, 3), activation = 'relu', padding = 'same')(x)
x = Conv2D(192, kernel_size = (3, 3), activation = 'relu', padding = 'same')(x)
x = Conv2D(192, kernel_size = (3, 3), activation = 'relu', padding = 'same')(x)
x = MaxPooling2D(pool_size = (3, 3), strides = 2)(x)
x = Conv2D(192, kernel_size = (3, 3), activation = 'relu', padding = 'same')(x)
x = Conv2D(192, kernel_size = (1, 1), activation = 'relu', padding = 'same')(x)
x = Conv2D(10, kernel_size = (1, 1))(x)
x = GlobalAveragePooling2D()(x)
x = Activation(activation = 'softmax')(x)
model = Model(model_input, x, name = 'conv_pool_cnn')
return model
conv_pool_cnn_model = conv_pool_cnn(model_input)
def compile_and_train(model, num_epochs):
model.compile(loss = categorical_crossentropy, optimizer = Adam(), metrics = ['accuracy'])
filepath = 'weights/' + model.name + '.{epoch:02d}-{loss:.2f}.hdf5'
checkpoint = ModelCheckpoint(filepath, monitor = 'loss', verbose = 0, save_weights_only = True, save_best_only = True, mode = 'auto', period = 1)
tensor_board = TensorBoard(log_dir = 'logs/', histogram_freq = 0, batch_size = 32)
history = model.fit(x_train, y_train, batch_size = 32, epochs = num_epochs, verbose = 1, callbacks = [checkpoint, tensor_board], validation_split = 0.2)
return history
#start1 = time.time()
#_ = compile_and_train(conv_pool_cnn_model, 30)
#end1 = time.time()
#print('training time for ConvPool - CNN - C: {} s ({} mins.)'.format(end1 - start1, (end1 - start1) / 60.0))
def evaluate_error(model):
pred = model.predict(x_test, batch_size = 32)
pred = np.argmax(pred, axis = 1)
pred = np.expand_dims(pred, axis = 1)
error = np.sum(np.not_equal(pred, y_test)) / y_test.shape[0]
return error
#print('error for ConvPool - CNN: ', evaluate_error(conv_pool_cnn_model))
# model 2: ALL - CNN - C
def all_cnn(model_input):
x = model_input
x = Conv2D(96, kernel_size = (3, 3), activation = 'relu', padding = 'same')(x)
x = Conv2D(96, kernel_size = (3, 3), activation = 'relu', padding = 'same')(x)
x = Conv2D(96, kernel_size = (3, 3), strides = 2, activation = 'relu', padding = 'same')(x)
x = Conv2D(192, kernel_size = (3, 3), activation = 'relu', padding = 'same')(x)
x = Conv2D(192, kernel_size = (3, 3), activation = 'relu', padding = 'same')(x)
x = Conv2D(192, kernel_size = (3, 3), strides = 2, activation = 'relu', padding = 'same')(x)
x = Conv2D(192, kernel_size = (3, 3), activation = 'relu', padding = 'same')(x)
x = Conv2D(192, kernel_size = (1, 1), activation = 'relu')(x)
x = Conv2D(10, kernel_size = (1, 1))(x)
x = GlobalAveragePooling2D()(x)
x = Activation(activation = 'softmax')(x)
model = Model(model_input, x, name = 'all_cnn')
return model
all_cnn_model = all_cnn(model_input)
#start2 = time.time()
#_ = compile_and_train(all_cnn_model, 30)
#end2 = time.time()
#print('training time for All - CNN - C: {} s ({} mins.)'.format(end2 - start2, (end2 - start2) / 60.0))
#print('error for All - CNN: ', evaluate_error(all_cnn_model))
def nin_cnn(model_input):
# block 1
x = model_input
x = Conv2D(32, kernel_size = (5, 5), activation = 'relu', padding = 'valid')(x)
x = Conv2D(32, kernel_size = (1, 1), activation = 'relu')(x)
x = Conv2D(32, kernel_size = (1, 1), activation = 'relu')(x)
x = MaxPooling2D(pool_size = (2, 2))(x)
x = Dropout(0.5)(x)
# block 2
x = Conv2D(64, kernel_size = (3, 3), activation = 'relu', padding = 'valid')(x)
x = Conv2D(64, kernel_size = (1, 1), activation = 'relu')(x)
x = Conv2D(64, kernel_size = (1, 1), activation = 'relu')(x)
x = MaxPooling2D(pool_size = (2, 2))(x)
x = Dropout(0.5)(x)
# block 3
x = Conv2D(128, (3, 3), activation = 'relu', padding = 'valid')(x)
x = Conv2D(32, kernel_size = (1, 1), activation ='relu')(x)
x = Conv2D(10, kernel_size = (1, 1))(x)
x = GlobalAveragePooling2D()(x)
x = Activation(activation = 'softmax')(x)
model = Model(model_input, x, name = 'nin_cnn')
return model
nin_cnn_model = nin_cnn(model_input)
#start3 = time.time()
#_ = compile_and_train(nin_cnn_model, 30)
#end3 = time.time()
#print('training time for NIN - CNN: {} s ({} mins.)'.format(end3 - start3, (end3 - start3) / 60.0))
#print('error for NIN - CNN: ', evaluate_error(nin_cnn_model))
# ensemble of the three models above
conv_pool_cnn_model = conv_pool_cnn(model_input)
all_cnn_model = all_cnn(model_input)
nin_cnn_model = nin_cnn(model_input)
# load best weights for each model (see models folder)
# NOTE: adjust file path names as necessary after training on your own machine
conv_pool_cnn_model.load_weights('weights/conv_pool_cnn.27-0.10.hdf5')
all_cnn_model.load_weights('weights/all_cnn.30-0.07.hdf5')
nin_cnn_model.load_weights('weights/nin_cnn.30-0.86.hdf5')
models = [conv_pool_cnn_model, all_cnn_model, nin_cnn_model]
def ensemble(models, model_input):
outputs = [model.outputs[0] for model in models]
y = Average()(outputs)
model = Model(model_input, y, name = 'ensemble')
return model
ensemble_model = ensemble(models, model_input)
print('error for ensemble of the three models: ', evaluate_error(ensemble_model))
ensemble_preds = ensemble_model.predict(x_test)
ensemble_preds = np.argmax(ensemble_preds, axis = 1)
y_test = y_test.reshape(y_test.shape[0], )
similarity = np.equal(ensemble_preds, y_test)
accuracy = np.sum(similarity) / len(y_test)
print('predictions shape: ', ensemble_preds.shape)
print('target shape: ', y_test.shape)
#equal = K.equal(y_test, np.argmax(ensemble_preds, axis = 1))
#accuracy = tf.reduce_mean(tf.cast(equal, 'float'))
#accuracy = categorical_accuracy(y_test, np.expand_dims(np.argmax(ensemble_preds, axis = 1), axis = 1))
#print('accuracy: ', accuracy)
print('3-model ensemble accuracy: {}%'.format(accuracy * 100))
def targeted_predict(index, predictions, targets):
print('\n\n---------------------------\n\n')
print('predicted: {} ({})'.format(image_classes[predictions[index]], predictions[index]))
print('actual: {} ({})'.format(image_classes[targets[index]], targets[index]))
plt.imshow(x_test[index])
plt.show()
# tests
targeted_predict(10, ensemble_preds, y_test)
targeted_predict(233, ensemble_preds, y_test)
targeted_predict(5679, ensemble_preds, y_test)
targeted_predict(4832, ensemble_preds, y_test)
targeted_predict(4911, ensemble_preds, y_test)
targeted_predict(6082, ensemble_preds, y_test)
targeted_predict(9262, ensemble_preds, y_test)
targeted_predict(2072, ensemble_preds, y_test)
targeted_predict(8112, ensemble_preds, y_test)
targeted_predict(3034, ensemble_preds, y_test) | [
"[email protected]"
]
| |
b129a9f14e65ef5524a7b3b9c62c43528fa7a56e | 8df1237388352d29c894403feaf91e800edef6bf | /Algorithms/717.1-bit-and-2-bit-characters/1-bit-and-2-bit-characters_1.py | c29bf6ba7a65751ccf0ecf07f91a5fd4ce738556 | [
"MIT"
]
| permissive | GaLaPyPy/leetcode-solutions | 8cfa5d220516683c6e18ff35c74d84779975d725 | 40920d11c584504e805d103cdc6ef3f3774172b3 | refs/heads/master | 2023-06-19T22:28:58.956306 | 2021-07-19T00:20:56 | 2021-07-19T00:20:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 243 | py | class Solution:
def isOneBitCharacter(self, bits: List[int]) -> bool:
return False if not bits or bits == [[1, 0]] else True if bits == [0] else self.isOneBitCharacter(bits[1:]) if bits[0] == 0 else self.isOneBitCharacter(bits[2:]) | [
"[email protected]"
]
| |
deee26ca9e685631ff63c4376f9e435f66452620 | cadb6dceb7bb67ce47ef48b2c83f480a65d6b01a | /s3prl/problem/hear/gtzan_music_speech.py | 5cd6274c2963c8c9e15792e2f29f92bd1933caa8 | [
"Apache-2.0",
"CC-BY-NC-4.0"
]
| permissive | s3prl/s3prl | 52ec2ae4df5a61c786c122085603aa9c5e8c2681 | 76a9432b824f6ae3eae09a35a67782c4ed582832 | refs/heads/main | 2023-08-17T02:26:57.524087 | 2023-06-10T17:12:27 | 2023-06-10T17:12:27 | 196,905,457 | 1,549 | 398 | Apache-2.0 | 2023-09-14T13:07:05 | 2019-07-15T01:54:52 | Python | UTF-8 | Python | false | false | 2,662 | py | import logging
from s3prl.corpus.hear import hear_scene_kfolds
from s3prl.util.configuration import default_cfg, field
from .scene import HearScene
logger = logging.getLogger(__name__)
NUM_FOLDS = 10
class GtzanMusicSpeech(HearScene):
@default_cfg(
**HearScene.setup.default_except(
corpus=dict(
CLS=field(
hear_scene_kfolds,
"\nThe corpus class. You can add the **kwargs right below this CLS key",
str,
),
dataset_root=field(
"???",
"The root path of the corpus",
str,
),
test_fold="???",
num_folds=NUM_FOLDS,
),
train_sampler=dict(
batch_size=32,
),
task=dict(
prediction_type="multiclass",
scores=["top1_acc", "mAP", "d_prime", "aucroc"],
),
)
)
@classmethod
def setup(cls, **cfg):
super().setup(**cfg)
@default_cfg(
**HearScene.train.default_except(
trainer=dict(
valid_metric="top1_acc",
valid_higher_better=True,
)
)
)
@classmethod
def train(cls, **cfg):
super().train(**cfg)
@default_cfg(**HearScene.inference.default_cfg)
@classmethod
def inference(cls, **cfg):
super().inference(**cfg)
@default_cfg(
**HearScene.run.default_except(
stages=["setup", "train", "inference"],
start_stage="setup",
final_stage="inference",
setup=setup.default_cfg.deselect("workspace", "resume"),
train=train.default_cfg.deselect("workspace", "resume"),
inference=inference.default_cfg.deselect("workspace", "resume"),
)
)
@classmethod
def run(cls, **cfg):
super().run(**cfg)
@default_cfg(
num_fold=field(NUM_FOLDS, "The number of folds to run cross validation", int),
**run.default_except(
workspace=field(
"???",
"The root workspace for all folds.\n"
"Each fold will use a 'fold_{id}' sub-workspace under this root workspace",
),
setup=dict(
corpus=dict(
test_fold=field(
"TBD", "This will be auto-set by 'run_cross_validation'"
)
)
),
),
)
@classmethod
def cross_validation(cls, **cfg):
super().cross_validation(**cfg)
| [
"[email protected]"
]
| |
f79f3465381def312720a2205e28a051021ff1bd | 3c82ea78607e530811e0e837503ce26717e5fd04 | /TopQuarkAnalysis/Configuration/python/patRefSel_eventCleaning_cff.py | 5676a6c747cd5e1df39cdbd39d2ec009084dd6f1 | []
| no_license | fhoehle/OldCMSSWPackages | 7065c1cd2944c56fe2731c9be49dc2bd1d9781ce | cb655adfd0d59c9c8143b2e3db1ea950110df8f6 | refs/heads/master | 2016-09-06T18:05:43.458784 | 2014-08-21T10:54:47 | 2014-08-21T10:54:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 480 | py | import FWCore.ParameterSet.Config as cms
from CommonTools.RecoAlgos.HBHENoiseFilter_cfi import *
# s. https://hypernews.cern.ch/HyperNews/CMS/get/JetMET/1196.html
HBHENoiseFilter.minIsolatedNoiseSumE = 999999.
HBHENoiseFilter.minNumIsolatedNoiseChannels = 999999
HBHENoiseFilter.minIsolatedNoiseSumEt = 999999.
from TopQuarkAnalysis.Configuration.patRefSel_eventCleaning_cfi import scrapingFilter
eventCleaning = cms.Sequence(
HBHENoiseFilter
+ scrapingFilter
)
| [
"[email protected]"
]
| |
e3332261e40144fa97dfbd80d950582342ebc533 | f82757475ea13965581c2147ff57123b361c5d62 | /gi-stubs/repository/Gio/FileIOStream.py | cfe2c6065b47c09736727679d4b0284e2a15413a | []
| no_license | ttys3/pygobject-stubs | 9b15d1b473db06f47e5ffba5ad0a31d6d1becb57 | d0e6e93399212aada4386d2ce80344eb9a31db48 | refs/heads/master | 2022-09-23T12:58:44.526554 | 2020-06-06T04:15:00 | 2020-06-06T04:15:00 | 269,693,287 | 8 | 2 | null | 2020-06-05T15:57:54 | 2020-06-05T15:57:54 | null | UTF-8 | Python | false | false | 20,977 | py | # encoding: utf-8
# module gi.repository.Gio
# from /usr/lib64/girepository-1.0/Gio-2.0.typelib
# by generator 1.147
# no doc
# imports
import gi as __gi
import gi.overrides as __gi_overrides
import gi.overrides.Gio as __gi_overrides_Gio
import gi.overrides.GObject as __gi_overrides_GObject
import gi.repository.GObject as __gi_repository_GObject
import gobject as __gobject
from .IOStream import IOStream
from .Seekable import Seekable
class FileIOStream(IOStream, Seekable):
"""
:Constructors:
::
FileIOStream(**properties)
"""
def bind_property(self, *args, **kwargs): # real signature unknown
pass
def bind_property_full(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def can_seek(self): # real signature unknown; restored from __doc__
""" can_seek(self) -> bool """
return False
def can_truncate(self): # real signature unknown; restored from __doc__
""" can_truncate(self) -> bool """
return False
def chain(self, *args, **kwargs): # real signature unknown
pass
def clear_pending(self): # real signature unknown; restored from __doc__
""" clear_pending(self) """
pass
def close(self, cancellable=None): # real signature unknown; restored from __doc__
""" close(self, cancellable:Gio.Cancellable=None) -> bool """
return False
def close_async(self, io_priority, cancellable=None, callback=None, user_data=None): # real signature unknown; restored from __doc__
""" close_async(self, io_priority:int, cancellable:Gio.Cancellable=None, callback:Gio.AsyncReadyCallback=None, user_data=None) """
pass
def close_finish(self, result): # real signature unknown; restored from __doc__
""" close_finish(self, result:Gio.AsyncResult) -> bool """
return False
def compat_control(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def connect(self, *args, **kwargs): # real signature unknown
pass
def connect_after(self, *args, **kwargs): # real signature unknown
pass
def connect_data(self, detailed_signal, handler, *data, **kwargs): # reliably restored by inspect
"""
Connect a callback to the given signal with optional user data.
:param str detailed_signal:
A detailed signal to connect to.
:param callable handler:
Callback handler to connect to the signal.
:param *data:
Variable data which is passed through to the signal handler.
:param GObject.ConnectFlags connect_flags:
Flags used for connection options.
:returns:
A signal id which can be used with disconnect.
"""
pass
def connect_object(self, *args, **kwargs): # real signature unknown
pass
def connect_object_after(self, *args, **kwargs): # real signature unknown
pass
def disconnect(*args, **kwargs): # reliably restored by inspect
""" signal_handler_disconnect(instance:GObject.Object, handler_id:int) """
pass
def disconnect_by_func(self, *args, **kwargs): # real signature unknown
pass
def do_can_seek(self, *args, **kwargs): # real signature unknown
""" can_seek(self) -> bool """
pass
def do_can_truncate(self, *args, **kwargs): # real signature unknown
""" can_truncate(self) -> bool """
pass
def do_close_async(self, *args, **kwargs): # real signature unknown
""" close_async(self, io_priority:int, cancellable:Gio.Cancellable=None, callback:Gio.AsyncReadyCallback=None, user_data=None) """
pass
def do_close_finish(self, *args, **kwargs): # real signature unknown
""" close_finish(self, result:Gio.AsyncResult) -> bool """
pass
def do_close_fn(self, *args, **kwargs): # real signature unknown
""" close_fn(self, cancellable:Gio.Cancellable=None) -> bool """
pass
def do_get_etag(self, *args, **kwargs): # real signature unknown
""" get_etag(self) -> str """
pass
def do_get_input_stream(self, *args, **kwargs): # real signature unknown
""" get_input_stream(self) -> Gio.InputStream """
pass
def do_get_output_stream(self, *args, **kwargs): # real signature unknown
""" get_output_stream(self) -> Gio.OutputStream """
pass
def do_query_info(self, *args, **kwargs): # real signature unknown
""" query_info(self, attributes:str, cancellable:Gio.Cancellable=None) -> Gio.FileInfo """
pass
def do_query_info_async(self, *args, **kwargs): # real signature unknown
""" query_info_async(self, attributes:str, io_priority:int, cancellable:Gio.Cancellable=None, callback:Gio.AsyncReadyCallback=None, user_data=None) """
pass
def do_query_info_finish(self, *args, **kwargs): # real signature unknown
""" query_info_finish(self, result:Gio.AsyncResult) -> Gio.FileInfo """
pass
def do_seek(self, *args, **kwargs): # real signature unknown
""" seek(self, offset:int, type:GLib.SeekType, cancellable:Gio.Cancellable=None) -> bool """
pass
def do_tell(self, *args, **kwargs): # real signature unknown
""" tell(self) -> int """
pass
def do_truncate_fn(self, *args, **kwargs): # real signature unknown
""" truncate_fn(self, size:int, cancellable:Gio.Cancellable=None) -> bool """
pass
def emit(self, *args, **kwargs): # real signature unknown
pass
def emit_stop_by_name(self, detailed_signal): # reliably restored by inspect
""" Deprecated, please use stop_emission_by_name. """
pass
def find_property(self, property_name): # real signature unknown; restored from __doc__
""" find_property(self, property_name:str) -> GObject.ParamSpec """
pass
def force_floating(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def freeze_notify(self): # reliably restored by inspect
"""
Freezes the object's property-changed notification queue.
:returns:
A context manager which optionally can be used to
automatically thaw notifications.
This will freeze the object so that "notify" signals are blocked until
the thaw_notify() method is called.
.. code-block:: python
with obj.freeze_notify():
pass
"""
pass
def getv(self, names, values): # real signature unknown; restored from __doc__
""" getv(self, names:list, values:list) """
pass
def get_data(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def get_etag(self): # real signature unknown; restored from __doc__
""" get_etag(self) -> str """
return ""
def get_input_stream(self): # real signature unknown; restored from __doc__
""" get_input_stream(self) -> Gio.InputStream """
pass
def get_output_stream(self): # real signature unknown; restored from __doc__
""" get_output_stream(self) -> Gio.OutputStream """
pass
def get_properties(self, *args, **kwargs): # real signature unknown
pass
def get_property(self, *args, **kwargs): # real signature unknown
pass
def get_qdata(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def handler_block(obj, handler_id): # reliably restored by inspect
"""
Blocks the signal handler from being invoked until
handler_unblock() is called.
:param GObject.Object obj:
Object instance to block handlers for.
:param int handler_id:
Id of signal to block.
:returns:
A context manager which optionally can be used to
automatically unblock the handler:
.. code-block:: python
with GObject.signal_handler_block(obj, id):
pass
"""
pass
def handler_block_by_func(self, *args, **kwargs): # real signature unknown
pass
def handler_disconnect(*args, **kwargs): # reliably restored by inspect
""" signal_handler_disconnect(instance:GObject.Object, handler_id:int) """
pass
def handler_is_connected(*args, **kwargs): # reliably restored by inspect
""" signal_handler_is_connected(instance:GObject.Object, handler_id:int) -> bool """
pass
def handler_unblock(*args, **kwargs): # reliably restored by inspect
""" signal_handler_unblock(instance:GObject.Object, handler_id:int) """
pass
def handler_unblock_by_func(self, *args, **kwargs): # real signature unknown
pass
def has_pending(self): # real signature unknown; restored from __doc__
""" has_pending(self) -> bool """
return False
def install_properties(self, pspecs): # real signature unknown; restored from __doc__
""" install_properties(self, pspecs:list) """
pass
def install_property(self, property_id, pspec): # real signature unknown; restored from __doc__
""" install_property(self, property_id:int, pspec:GObject.ParamSpec) """
pass
def interface_find_property(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def interface_install_property(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def interface_list_properties(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def is_closed(self): # real signature unknown; restored from __doc__
""" is_closed(self) -> bool """
return False
def is_floating(self): # real signature unknown; restored from __doc__
""" is_floating(self) -> bool """
return False
def list_properties(self): # real signature unknown; restored from __doc__
""" list_properties(self) -> list, n_properties:int """
return []
def newv(self, object_type, parameters): # real signature unknown; restored from __doc__
""" newv(object_type:GType, parameters:list) -> GObject.Object """
pass
def notify(self, property_name): # real signature unknown; restored from __doc__
""" notify(self, property_name:str) """
pass
def notify_by_pspec(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def override_property(self, property_id, name): # real signature unknown; restored from __doc__
""" override_property(self, property_id:int, name:str) """
pass
def query_info(self, attributes, cancellable=None): # real signature unknown; restored from __doc__
""" query_info(self, attributes:str, cancellable:Gio.Cancellable=None) -> Gio.FileInfo """
pass
def query_info_async(self, attributes, io_priority, cancellable=None, callback=None, user_data=None): # real signature unknown; restored from __doc__
""" query_info_async(self, attributes:str, io_priority:int, cancellable:Gio.Cancellable=None, callback:Gio.AsyncReadyCallback=None, user_data=None) """
pass
def query_info_finish(self, result): # real signature unknown; restored from __doc__
""" query_info_finish(self, result:Gio.AsyncResult) -> Gio.FileInfo """
pass
def ref(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def ref_sink(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def replace_data(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def replace_qdata(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def run_dispose(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def seek(self, offset, type, cancellable=None): # real signature unknown; restored from __doc__
""" seek(self, offset:int, type:GLib.SeekType, cancellable:Gio.Cancellable=None) -> bool """
return False
def set_data(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def set_pending(self): # real signature unknown; restored from __doc__
""" set_pending(self) -> bool """
return False
def set_properties(self, *args, **kwargs): # real signature unknown
pass
def set_property(self, *args, **kwargs): # real signature unknown
pass
def splice_async(self, stream2, flags, io_priority, cancellable=None, callback=None, user_data=None): # real signature unknown; restored from __doc__
""" splice_async(self, stream2:Gio.IOStream, flags:Gio.IOStreamSpliceFlags, io_priority:int, cancellable:Gio.Cancellable=None, callback:Gio.AsyncReadyCallback=None, user_data=None) """
pass
def splice_finish(self, result): # real signature unknown; restored from __doc__
""" splice_finish(result:Gio.AsyncResult) -> bool """
return False
def steal_data(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def steal_qdata(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def stop_emission(self, detailed_signal): # reliably restored by inspect
""" Deprecated, please use stop_emission_by_name. """
pass
def stop_emission_by_name(*args, **kwargs): # reliably restored by inspect
""" signal_stop_emission_by_name(instance:GObject.Object, detailed_signal:str) """
pass
def tell(self): # real signature unknown; restored from __doc__
""" tell(self) -> int """
return 0
def thaw_notify(self): # real signature unknown; restored from __doc__
""" thaw_notify(self) """
pass
def truncate(self, offset, cancellable=None): # real signature unknown; restored from __doc__
""" truncate(self, offset:int, cancellable:Gio.Cancellable=None) -> bool """
return False
def unref(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def watch_closure(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def weak_ref(self, *args, **kwargs): # real signature unknown
pass
def _force_floating(self, *args, **kwargs): # real signature unknown
""" force_floating(self) """
pass
def _ref(self, *args, **kwargs): # real signature unknown
""" ref(self) -> GObject.Object """
pass
def _ref_sink(self, *args, **kwargs): # real signature unknown
""" ref_sink(self) -> GObject.Object """
pass
def _unref(self, *args, **kwargs): # real signature unknown
""" unref(self) """
pass
def _unsupported_data_method(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def _unsupported_method(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def __copy__(self, *args, **kwargs): # real signature unknown
pass
def __deepcopy__(self, *args, **kwargs): # real signature unknown
pass
def __delattr__(self, *args, **kwargs): # real signature unknown
""" Implement delattr(self, name). """
pass
def __dir__(self, *args, **kwargs): # real signature unknown
""" Default dir() implementation. """
pass
def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass
def __format__(self, *args, **kwargs): # real signature unknown
""" Default object formatter. """
pass
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass
def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass
def __hash__(self, *args, **kwargs): # real signature unknown
""" Return hash(self). """
pass
def __init_subclass__(self, *args, **kwargs): # real signature unknown
"""
This method is called when a class is subclassed.
The default implementation does nothing. It may be
overridden to extend subclasses.
"""
pass
def __init__(self, **properties): # real signature unknown; restored from __doc__
pass
def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass
def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass
def __reduce_ex__(self, *args, **kwargs): # real signature unknown
""" Helper for pickle. """
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
""" Helper for pickle. """
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
def __setattr__(self, *args, **kwargs): # real signature unknown
""" Implement setattr(self, name, value). """
pass
def __sizeof__(self, *args, **kwargs): # real signature unknown
""" Size of object in memory, in bytes. """
pass
def __str__(self, *args, **kwargs): # real signature unknown
""" Return str(self). """
pass
def __subclasshook__(self, *args, **kwargs): # real signature unknown
"""
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__().
It should return True, False or NotImplemented. If it returns
NotImplemented, the normal algorithm is used. Otherwise, it
overrides the normal algorithm (and the outcome is cached).
"""
pass
def __weakref__(self, *args, **kwargs): # real signature unknown
pass
g_type_instance = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
parent_instance = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
priv = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
qdata = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
ref_count = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
__gpointer__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
__grefcount__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
props = None # (!) real value is '<gi._gi.GProps object at 0x7f4b874621c0>'
__class__ = None # (!) real value is "<class 'gi.types.GObjectMeta'>"
__dict__ = None # (!) real value is "mappingproxy({'__info__': ObjectInfo(FileIOStream), '__module__': 'gi.repository.Gio', '__gtype__': <GType GFileIOStream (94269256882256)>, '__doc__': None, '__gsignals__': {}, 'get_etag': gi.FunctionInfo(get_etag), 'query_info': gi.FunctionInfo(query_info), 'query_info_async': gi.FunctionInfo(query_info_async), 'query_info_finish': gi.FunctionInfo(query_info_finish), 'do_can_seek': gi.VFuncInfo(can_seek), 'do_can_truncate': gi.VFuncInfo(can_truncate), 'do_get_etag': gi.VFuncInfo(get_etag), 'do_query_info': gi.VFuncInfo(query_info), 'do_query_info_async': gi.VFuncInfo(query_info_async), 'do_query_info_finish': gi.VFuncInfo(query_info_finish), 'do_seek': gi.VFuncInfo(seek), 'do_tell': gi.VFuncInfo(tell), 'do_truncate_fn': gi.VFuncInfo(truncate_fn), 'parent_instance': <property object at 0x7f4b8805bb30>, 'priv': <property object at 0x7f4b8805bd10>})"
__gdoc__ = 'Object GFileIOStream\n\nProperties from GIOStream:\n input-stream -> GInputStream: Input stream\n The GInputStream to read from\n output-stream -> GOutputStream: Output stream\n The GOutputStream to write to\n closed -> gboolean: Closed\n Is the stream closed\n\nSignals from GObject:\n notify (GParam)\n\n'
__gsignals__ = {}
__gtype__ = None # (!) real value is '<GType GFileIOStream (94269256882256)>'
__info__ = ObjectInfo(FileIOStream)
| [
"[email protected]"
]
| |
b1b040d767296d8c2901283ddd4759ac1033adbc | 25ebc03b92df764ff0a6c70c14c2848a49fe1b0b | /daily/20200112/example_python/00varargs.py | ad017fc8a47ce3cd6acaaafb2268930d71dc5a06 | []
| no_license | podhmo/individual-sandbox | 18db414fafd061568d0d5e993b8f8069867dfcfb | cafee43b4cf51a321f4e2c3f9949ac53eece4b15 | refs/heads/master | 2023-07-23T07:06:57.944539 | 2023-07-09T11:45:53 | 2023-07-09T11:45:53 | 61,940,197 | 6 | 0 | null | 2022-10-19T05:01:17 | 2016-06-25T11:27:04 | Python | UTF-8 | Python | false | false | 141 | py | def f(name: str, *args: str) -> None:
print(name, args)
# TypeError: f() got multiple values for argument 'name'
f(1, 2, 3, name="foo")
| [
"[email protected]"
]
| |
ee0922e23396ac2c3237791b760d5864c43c937b | 9b6f65a28af4c6befdd015d1416d6257138c0219 | /alpha/event/migrations/0019_auto__add_field_event_audited.py | d84f098e7baab33d92cf6539647b8c48da0925a4 | []
| no_license | dany431/cityfusion | 5beec53131898e539a892249fa711fb3086fb53c | 4e67464db69cfa21c965e4eb8796a5c727d5a443 | refs/heads/master | 2016-08-11T13:20:17.966539 | 2016-01-13T11:17:12 | 2016-01-13T11:17:12 | 49,567,611 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 13,323 | py | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Event.audited'
db.add_column(u'event_event', 'audited',
self.gf('django.db.models.fields.BooleanField')(default=False),
keep_default=False)
def backwards(self, orm):
# Deleting field 'Event.audited'
db.delete_column(u'event_event', 'audited')
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'cities.city': {
'Meta': {'object_name': 'City'},
'country': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cities.Country']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'location': ('django.contrib.gis.db.models.fields.PointField', [], {}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'db_index': 'True'}),
'name_std': ('django.db.models.fields.CharField', [], {'max_length': '200', 'db_index': 'True'}),
'population': ('django.db.models.fields.IntegerField', [], {}),
'region': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cities.Region']", 'null': 'True', 'blank': 'True'}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'subregion': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cities.Subregion']", 'null': 'True', 'blank': 'True'})
},
u'cities.country': {
'Meta': {'ordering': "['name']", 'object_name': 'Country'},
'code': ('django.db.models.fields.CharField', [], {'max_length': '2', 'db_index': 'True'}),
'continent': ('django.db.models.fields.CharField', [], {'max_length': '2'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'db_index': 'True'}),
'population': ('django.db.models.fields.IntegerField', [], {}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'tld': ('django.db.models.fields.CharField', [], {'max_length': '5'})
},
u'cities.region': {
'Meta': {'object_name': 'Region'},
'code': ('django.db.models.fields.CharField', [], {'max_length': '200', 'db_index': 'True'}),
'country': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cities.Country']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'db_index': 'True'}),
'name_std': ('django.db.models.fields.CharField', [], {'max_length': '200', 'db_index': 'True'}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '200'})
},
u'cities.subregion': {
'Meta': {'object_name': 'Subregion'},
'code': ('django.db.models.fields.CharField', [], {'max_length': '200', 'db_index': 'True'}),
'country': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cities.Country']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'db_index': 'True'}),
'name_std': ('django.db.models.fields.CharField', [], {'max_length': '200', 'db_index': 'True'}),
'region': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cities.Region']"}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '200'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'event.auditevent': {
'Meta': {'object_name': 'AuditEvent', '_ormbases': [u'event.Event']},
u'event_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['event.Event']", 'unique': 'True', 'primary_key': 'True'}),
'phrases': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['event.AuditPhrase']", 'symmetrical': 'False'})
},
u'event.auditphrase': {
'Meta': {'object_name': 'AuditPhrase'},
'active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'phrase': ('django.db.models.fields.CharField', [], {'max_length': '200'})
},
u'event.auditsingleevent': {
'Meta': {'object_name': 'AuditSingleEvent'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'phrases': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['event.AuditPhrase']", 'symmetrical': 'False'})
},
u'event.canadianvenue': {
'Meta': {'object_name': 'CanadianVenue', '_ormbases': [u'event.Venue']},
'postal_code': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'province': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
u'venue_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['event.Venue']", 'unique': 'True', 'primary_key': 'True'})
},
u'event.event': {
'Meta': {'object_name': 'Event'},
'audited': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'authentication_key': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 1, 26, 0, 0)', 'auto_now_add': 'True', 'blank': 'True'}),
'cropping': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'email': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'location': ('django.contrib.gis.db.models.fields.PointField', [], {}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 1, 26, 0, 0)', 'auto_now': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '250'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']", 'null': 'True', 'blank': 'True'}),
'picture': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'price': ('django.db.models.fields.CharField', [], {'default': "'Free'", 'max_length': '40', 'blank': 'True'}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '255'}),
'venue': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['event.Venue']", 'null': 'True', 'blank': 'True'}),
'website': ('django.db.models.fields.URLField', [], {'default': "''", 'max_length': '200', 'null': 'True', 'blank': 'True'})
},
u'event.fakeauditevent': {
'Meta': {'object_name': 'FakeAuditEvent', 'db_table': "u'event_auditevent'", 'managed': 'False'},
'event_ptr_id': ('django.db.models.fields.PositiveIntegerField', [], {'primary_key': 'True', 'db_column': "'event_ptr_id'"})
},
u'event.reminder': {
'Meta': {'object_name': 'Reminder'},
'date': ('django.db.models.fields.DateTimeField', [], {}),
'email': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'event': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
u'event.singleevent': {
'Meta': {'object_name': 'SingleEvent'},
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'end_time': ('django.db.models.fields.DateTimeField', [], {}),
'event': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['event.Event']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'start_time': ('django.db.models.fields.DateTimeField', [], {})
},
u'event.venue': {
'Meta': {'object_name': 'Venue'},
'city': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cities.City']"}),
'country': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cities.Country']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'location': ('django.contrib.gis.db.models.fields.PointField', [], {}),
'name': ('django.db.models.fields.CharField', [], {'default': "'Default Venue'", 'max_length': '250'}),
'street': ('django.db.models.fields.CharField', [], {'max_length': '250', 'blank': 'True'})
},
u'taggit.tag': {
'Meta': {'object_name': 'Tag'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100'})
},
u'taggit.taggeditem': {
'Meta': {'object_name': 'TaggedItem'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'taggit_taggeditem_tagged_items'", 'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'object_id': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),
'tag': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'taggit_taggeditem_items'", 'to': u"orm['taggit.Tag']"})
}
}
complete_apps = ['event'] | [
"[email protected]"
]
| |
338224b306fe6bd7bfb403460e852eaca4b28dee | da64994d73d250d19a30381de7462c5729372f81 | /apps/student/migrations/0023_auto_20191125_2256.py | e8d84833aad8f99e902435dfa2d29e34a791bfa8 | []
| no_license | Mid0Riii/psybackend | 2f872c1dd21e97ba0a46efa10f2b3246ac8bb2b5 | 2cd477f01111a816b17725a00ffa77a156dec7b0 | refs/heads/master | 2023-03-26T07:55:17.580161 | 2021-03-14T01:45:19 | 2021-03-14T01:45:19 | 305,083,821 | 0 | 1 | null | 2021-03-14T01:45:20 | 2020-10-18T11:15:48 | Python | UTF-8 | Python | false | false | 578 | py | # Generated by Django 2.2.5 on 2019-11-25 14:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('student', '0022_auto_20191123_1526'),
]
operations = [
migrations.AlterField(
model_name='studentbasic',
name='stu_level',
field=models.CharField(blank=True, choices=[('二级', '二级'), ('三级', '三级'), ('中科院', '中科院'), ('心理辅导师', '心理辅导师')], default='空', max_length=16, null=True, verbose_name='级别'),
),
]
| [
"[email protected]"
]
| |
ef4d6dfcc404eef043eb20246f5b4cda418d1972 | eaa43160aeeaa3cb4c7c9f52d8ed01f9abdf85e5 | /tests/db/sql/clauses/test_array_agg.py | b827c5049998aee470f52ac1b088f9ea6f219154 | [
"MIT"
]
| permissive | furious-luke/polecat | 4fd2a2f859b9a77d9d004b32bc1bf8f907fea2ba | 7be5110f76dc42b15c922c1bb7d49220e916246d | refs/heads/master | 2022-07-31T16:38:45.791129 | 2021-05-06T01:05:03 | 2021-05-06T01:05:03 | 179,440,367 | 4 | 0 | MIT | 2022-07-05T21:28:34 | 2019-04-04T07:00:55 | Python | UTF-8 | Python | false | false | 457 | py | from unittest.mock import MagicMock
import pytest
from polecat.db.sql.expression.array_agg import ArrayAgg
from polecat.db.sql.sql import Sql
from .conftest import SqlTermTester
def test_to_sql():
term = ArrayAgg('test')
sql = Sql(term.to_sql())
assert str(sql) == 'array_agg("test")'
@pytest.mark.parametrize('test_func', SqlTermTester.ALL_TESTS)
def test_sql_term_methods(test_func):
term = ArrayAgg(MagicMock())
test_func(term)
| [
"[email protected]"
]
| |
1958ba72f578a180ae656aab8c407494a1874f58 | cbc5e26bb47ae69e80a3649c90275becf25ce404 | /xlsxwriter/test/comparison/test_chart_up_down_bars01.py | 393b2df0723766bdd319a942f072296d1d44a69f | [
"BSD-2-Clause-Views",
"BSD-3-Clause",
"MIT"
]
| permissive | mst-solar-car/kicad-bom-generator | c3549409c3139f787ad28391372b5cb03791694a | 2aae905056d06f3d25343a8d784049c141d05640 | refs/heads/master | 2021-09-07T14:00:40.759486 | 2018-02-23T23:21:13 | 2018-02-23T23:21:13 | 107,868,801 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,690 | py | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2017, John McNamara, [email protected]
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'chart_up_down_bars01.xlsx'
test_dir = 'xlsxwriter/test/comparison/'
self.got_filename = test_dir + '_test_' + filename
self.exp_filename = test_dir + 'xlsx_files/' + filename
self.ignore_files = []
self.ignore_elements = {}
def test_create_file(self):
"""Test the creation of an XlsxWriter file with up-down bars."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({'type': 'line'})
chart.axis_ids = [46808448, 49289856]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column('A1', data[0])
worksheet.write_column('B1', data[1])
worksheet.write_column('C1', data[2])
chart.set_up_down_bars()
chart.add_series({
'categories': '=Sheet1!$A$1:$A$5',
'values': '=Sheet1!$B$1:$B$5',
})
chart.add_series({
'categories': '=Sheet1!$A$1:$A$5',
'values': '=Sheet1!$C$1:$C$5',
})
worksheet.insert_chart('E9', chart)
workbook.close()
self.assertExcelEqual()
| [
"[email protected]"
]
| |
07401c1e6a187b32c1074eb2c08dd8cb41916ac7 | b095173b2dbc77c8ad61c42403258c76169b7a63 | /src/sagemaker/cli/compatibility/v2/modifiers/deprecated_params.py | 1cc2f6dca060824a2f9117889c88e84f5fe907bd | [
"Apache-2.0"
]
| permissive | aws/sagemaker-python-sdk | 666665e717cfb76698ba3ea7563b45344634264d | 8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85 | refs/heads/master | 2023-09-04T01:00:20.663626 | 2023-08-31T15:29:19 | 2023-08-31T15:29:19 | 110,621,895 | 2,050 | 1,255 | Apache-2.0 | 2023-09-14T17:37:15 | 2017-11-14T01:03:33 | Python | UTF-8 | Python | false | false | 2,482 | py | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
"""Classes to remove deprecated parameters."""
from __future__ import absolute_import
from sagemaker.cli.compatibility.v2.modifiers import matching
from sagemaker.cli.compatibility.v2.modifiers.modifier import Modifier
TF_NAMESPACES = ("sagemaker.tensorflow", "sagemaker.tensorflow.estimator")
class TensorFlowScriptModeParameterRemover(Modifier):
"""A class to remove ``script_mode`` from TensorFlow estimators (because it's the only mode)."""
def node_should_be_modified(self, node):
"""Checks if the ``ast.Call`` node instantiates a TensorFlow estimator.
TensorFlow estimator would use``script_mode`` set. This looks for the following formats:
- ``TensorFlow``
- ``sagemaker.tensorflow.TensorFlow``
Args:
node (ast.Call): a node that represents a function call. For more,
see https://docs.python.org/3/library/ast.html#abstract-grammar.
Returns:
bool: If the ``ast.Call`` is instantiating a TensorFlow estimator with ``script_mode``.
"""
is_tf_constructor = matching.matches_name_or_namespaces(node, "TensorFlow", TF_NAMESPACES)
return is_tf_constructor and self._has_script_mode_param(node)
def _has_script_mode_param(self, node):
"""Checks if the ``ast.Call`` node's keywords include ``script_mode``."""
for kw in node.keywords:
if kw.arg == "script_mode":
return True
return False
def modify_node(self, node):
"""Modifies the ``ast.Call`` node's keywords to remove ``script_mode``.
Args:
node (ast.Call): a node that represents a TensorFlow constructor.
Returns:
ast.AST: the original node, which has been potentially modified.
"""
for kw in node.keywords:
if kw.arg == "script_mode":
node.keywords.remove(kw)
return node
| [
"[email protected]"
]
| |
c97534d7ad5b129aa5e2e092a9d772af4853ed9a | ffadf9541d01cf9af20c419759d48b1eb01bfd35 | /pachong/PCdemo1/day16/刘士豪20200414/梨视频爬取.py | c6ded9d8a6124d9c59c2e87f6c0e2f3f0748bb42 | []
| no_license | 1987617587/lsh_py | b1bb1016eaafcba03bbc4a5310c1db04ae227af4 | 80eb5175cd0e5b3c6c5e2ebb906bb78d9a8f9e0d | refs/heads/master | 2021-01-02T05:14:31.330287 | 2020-06-20T05:18:23 | 2020-06-20T05:18:23 | 239,498,994 | 2 | 1 | null | 2020-06-07T23:09:56 | 2020-02-10T11:46:47 | Python | UTF-8 | Python | false | false | 6,029 | py | # author:lsh
# datetime:2020/4/14 17:32
'''
.::::. _oo0oo_
.::::::::. o8888888o
::::::::::: 88" . "88
..:::::::::::' (| -_- |)
'::::::::::::' 0\ = /0
.:::::::::: ___/`---'\___
'::::::::::::::.. .' \\| |# '.
..::::::::::::. / \\||| : |||# \
``:::::::::::::::: / _||||| -:- |||||- \
::::``:::::::::' .:::. | | \\\ - #/ | |
::::' ':::::' .::::::::. | \_| ''\---/'' |_/ |
.::::' :::: .:::::::'::::. \ .-\__ '-' ___/-. /
.:::' ::::: .:::::::::' ':::::. ___'. .' /--.--\ `. .'___
.::' :::::.:::::::::' ':::::. ."" '< `.___\_<|>_/___.' >' "".
.::' ::::::::::::::' ``::::. | | : `- \`.;`\ _ /`;.`/ - ` : | |
...::: ::::::::::::' ``::. \ \ `_. \_ __\ /__ _/ .-` / /
```` ':. ':::::::::' ::::.. `-.____`.___ \_____/___.-`___.-'
'.:::::' ':'````.. `=---='
女神保佑 永无BUG 佛祖保佑 永无BUG
'''
import os
import re
import requests
import time
import random
import json
import xlwt # excel文档的写操作
def down_video(url,path):
with requests.get(url,stream=True) as response: # 使用字节流的方式下载
print('开始下载视频……')
# 数据块的大小
chunk_size = 10240
# 获取视频的大小
content_size = int(response.headers['content-length'])
print(f'content_size:{content_size}')
with open(path,'wb')as file:
n = 1
for chunk in response.iter_content(chunk_size=chunk_size):
loaded = n*chunk_size / content_size
print(f'已下载:{loaded:%}')
n += 1
file.write(chunk)
print("下载成功")
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36',
'Referer': 'https://www.pearvideo.com/category_8',
'Cookie':'__secdyid=84f00d239b16acbdcfb9cde101a17af47b0d99ea9a3a759a021586856771; JSESSIONID=9BC77A296B4EA4B8841EC7857515E446; PEAR_UUID=63dcb5e7-c77d-4312-b9ee-b74afd0cb7cd; PV_WWW=srv-pv-prod-portal4; _uab_collina=158685677096523995133632; UM_distinctid=1717808bfe41ee-08084333e12f5a-b791b36-1fa400-1717808bfe642d; CNZZDATA1260553744=996779612-1586856014-https%253A%252F%252Fwww.baidu.com%252F%7C1586856014; Hm_lvt_9707bc8d5f6bba210e7218b8496f076a=1586856772; __ads_session=zQ/j+u9ZdQk+8LohtQA=; Hm_lpvt_9707bc8d5f6bba210e7218b8496f076a=1586856796'
}
headers2 = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36',
'Referer': 'https://www.pearvideo.com/',
'Cookie':'__secdyid=84f00d239b16acbdcfb9cde101a17af47b0d99ea9a3a759a021586856771; JSESSIONID=9BC77A296B4EA4B8841EC7857515E446; PEAR_UUID=63dcb5e7-c77d-4312-b9ee-b74afd0cb7cd; PV_WWW=srv-pv-prod-portal4; _uab_collina=158685677096523995133632; UM_distinctid=1717808bfe41ee-08084333e12f5a-b791b36-1fa400-1717808bfe642d; CNZZDATA1260553744=996779612-1586856014-https%253A%252F%252Fwww.baidu.com%252F%7C1586856014; Hm_lvt_9707bc8d5f6bba210e7218b8496f076a=1586856772; __ads_session=zQ/j+u9ZdQk+8LohtQA=; Hm_lpvt_9707bc8d5f6bba210e7218b8496f076a=1586856796'
}
# url = 'https://www.pearvideo.com/category_loading.jsp?reqType=5&categoryId=8&start=12&mrd=0.5616803019773882&filterIds=1668776,1668820,1667839,1667761,1668006,1667974,1667846,1667598,1667770,1667134,1667302,1667266'
# 把上面路由优化,修改参数,进行多页爬取
pageCount = 1
# url = 'https://www.pearvideo.com/category_8'
url = 'https://www.pearvideo.com/category_loading.jsp'
# for page in range(5):
page = 0
while page<= pageCount:
print(f'page:{page}')
params = {
'reqType': '5',
'categoryId': '8',
'start': page*12,
}
page+=1
response = requests.get(url, params=params, headers=headers)
html = response.text
# print(html)
pat = re.compile(r'<a.*?href="(.*?)" class="vervideo-lilink actplay">')
ls = pat.findall(html)
# ['video_1668820', 'video_1668776', 'living_1667761', 'video_1667839', 'video_1668006', 'video_1667974', 'video_1667846', 'video_1667598', 'video_1667770', 'video_1667134', 'video_1667302', 'video_1667266']
print(ls)
for detail_url in ls:
video_detail_url = 'https://www.pearvideo.com/'+detail_url
print(f'video_detail_url:{video_detail_url}')
headers2['Referer'] = 'https://www.pearvideo.com/'+detail_url
print(headers2)
response = requests.get(video_detail_url,headers=headers2)
print(response.text)
detail_html = response.text
pat = re.compile(r'.*?srcUrl="(.*?)"')
mp4_url = pat.findall(detail_html)[0]
print(f'mp4_url:{mp4_url}')
# 开始下载视频
down_video(mp4_url,'videos/'+os.path.basename(mp4_url))
time.sleep(random.random())
| [
"[email protected]"
]
| |
a8bf7488a6744e53a99e1ccd19d70c3f88be861b | 9a832a66a8a4b17021b2e0f7e3b40362879a7012 | /arabel/asgi.py | dbdc7b43f4e9f73ea21c38c7c9520aa6d284df7f | [
"MIT"
]
| permissive | niconoe/arabel | dcdd29cb14bafef8cf19853ad87b28fc30bc709d | ef0ffb1ef3e104799ac95dea55e48aae93b399d5 | refs/heads/master | 2023-05-04T22:07:53.244933 | 2021-05-26T14:58:08 | 2021-05-26T14:58:08 | 334,908,666 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 389 | py | """
ASGI config for arabel project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'arabel.settings')
application = get_asgi_application()
| [
"[email protected]"
]
| |
e56c0a6f34577794fddf1e0e344ffa44cd7c5504 | 7807d8d9d109a3e272fffed91bf841201da39256 | /trans_ALDS1_1_B/oreo0320_ALDS1_1_B_kotonoha.py | fb7da8b5cfb0a8448ae7e1cfdeee8e2de5cd6b7f | []
| no_license | y-akinobu/AOJ_to_Kotonoha | 0e8df43393964fcdd5df06c75545091bd6c0c2e2 | 5a694a55a3d85e3fbc4a07b57edc4374556db9a1 | refs/heads/main | 2023-02-05T15:33:16.581177 | 2020-12-30T16:14:44 | 2020-12-30T16:14:44 | 325,524,216 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 226 | py | # mathモジュールを用いる
import math
# map(整数,入力された文字列を空白で分割した列)を展開し順にaとbとする
a,b = map(int,input().split())
# math.gcd(a,b)を出力する
print(math.gcd(a,b)) | [
"[email protected]"
]
| |
5ebae5874d208063c395bbf6d6118ed2aca27b8c | aa6e1dd07a71a73bc08574b76f9e57a3ce8c8286 | /077.Test_BeeWare/helloworld/macOS/Hello World/Hello World.app/Contents/Resources/app_packages/rubicon/objc/__init__.py | 15b6e36cede428eead64cb153f86979a662adfe7 | [
"MIT",
"BSD-3-Clause"
]
| permissive | IvanaXu/PyTools | 0aff5982f50bb300bfa950405192c78473b69537 | 358ae06eef418fde35f424909d4f13049ca9ec7b | refs/heads/master | 2023-06-07T21:45:44.242363 | 2023-06-06T16:00:25 | 2023-06-06T16:00:25 | 163,940,845 | 60 | 8 | MIT | 2022-12-23T02:49:05 | 2019-01-03T07:54:16 | Python | UTF-8 | Python | false | false | 2,188 | py | # Examples of valid version strings
# __version__ = '1.2.3.dev1' # Development release 1
# __version__ = '1.2.3a1' # Alpha Release 1
# __version__ = '1.2.3b1' # Beta Release 1
# __version__ = '1.2.3rc1' # RC Release 1
# __version__ = '1.2.3' # Final Release
# __version__ = '1.2.3.post1' # Post Release 1
__version__ = '0.4.0'
# Import commonly used submodules right away.
# The first few imports are only included for clarity. They are not strictly necessary, because the from-imports below
# also import the types and runtime modules and implicitly add them to the rubicon.objc namespace.
from . import types # noqa: F401
from . import runtime # noqa: F401
from . import api # noqa: F401
# The import of collections is important, however. The classes from collections are not meant to be used directly,
# instead they are registered with the runtime module (using the for_objcclass decorator) so they are used in place of
# ObjCInstance when representing Foundation collections in Python. If this module is not imported, the registration
# will not take place, and Foundation collections will not support the expected methods/operators in Python!
from . import collections # noqa: F401
# Note to developers: when modifying any of the import lists below, please:
# * Keep each list in alphabetical order
# * Update the corresponding list in the documentation at docs/reference/rubicon-objc.rst
# Thank you!
from .types import ( # noqa: F401
CFIndex, CFRange, CGFloat, CGGlyph, CGPoint, CGPointMake, CGRect, CGRectMake, CGSize, CGSizeMake, NSEdgeInsets,
NSEdgeInsetsMake, NSInteger, NSMakePoint, NSMakeRect, NSMakeSize, NSPoint, NSRange, NSRect, NSSize, NSTimeInterval,
NSUInteger, NSZeroPoint, UIEdgeInsets, UIEdgeInsetsMake, UIEdgeInsetsZero, UniChar, unichar,
)
from .runtime import SEL, send_message, send_super # noqa: F401
from .api import ( # noqa: F401
Block, NSArray, NSDictionary, NSMutableArray, NSMutableDictionary, NSObject, NSObjectProtocol, ObjCBlock,
ObjCClass, ObjCInstance, ObjCMetaClass, ObjCProtocol, at, ns_from_py, objc_classmethod, objc_const, objc_ivar,
objc_method, objc_property, objc_rawmethod, py_from_ns,
)
| [
"[email protected]"
]
| |
f92f5f95e7c1c9b68e7a522938c2afe1c00e0d01 | b38e64f47f84e3aa984f813d1fbeef2717e2bc3d | /characters/migrations/0003_class_race.py | fbdf75700c0bc20661afb443e1d24f7dabb0b948 | [
"MIT"
]
| permissive | luiz158/django-tutorial-v2 | 2abf28939060750e031fca95429c1d6cbb738f46 | 3d128301357e687542c6627f9d8eca026e04faaa | refs/heads/master | 2021-12-04T04:18:59.535664 | 2015-01-06T21:54:45 | 2015-01-06T21:54:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,052 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('characters', '0002_alignment'),
]
operations = [
migrations.CreateModel(
name='Class',
fields=[
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),
('name', models.CharField(max_length=200)),
('description', models.TextField()),
],
options={
},
bases=(models.Model,),
),
migrations.CreateModel(
name='Race',
fields=[
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),
('name', models.CharField(max_length=200)),
('description', models.TextField()),
],
options={
},
bases=(models.Model,),
),
]
| [
"[email protected]"
]
| |
df6b7919f0f4d731c68b54914240fed2aaa8fe5b | 91d1a6968b90d9d461e9a2ece12b465486e3ccc2 | /rds_write_3/db-parameter-group_copy.py | ee699d9102789428290b58d77fa4169647f2cf6c | []
| no_license | lxtxl/aws_cli | c31fc994c9a4296d6bac851e680d5adbf7e93481 | aaf35df1b7509abf5601d3f09ff1fece482facda | refs/heads/master | 2023-02-06T09:00:33.088379 | 2020-12-27T13:38:45 | 2020-12-27T13:38:45 | 318,686,394 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,218 | py | #!/usr/bin/python
# -*- codding: utf-8 -*-
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from common.execute_command import write_three_parameter
# url : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/copy-db-parameter-group.html
if __name__ == '__main__':
"""
create-db-parameter-group : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/create-db-parameter-group.html
delete-db-parameter-group : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/delete-db-parameter-group.html
describe-db-parameter-groups : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-db-parameter-groups.html
modify-db-parameter-group : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/modify-db-parameter-group.html
reset-db-parameter-group : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/reset-db-parameter-group.html
"""
parameter_display_string = """
# source-db-parameter-group-identifier : The identifier or ARN for the source DB parameter group. For information about creating an ARN, see Constructing an ARN for Amazon RDS in the Amazon RDS User Guide .
Constraints:
Must specify a valid DB parameter group.
Must specify a valid DB parameter group identifier, for example my-db-param-group , or a valid ARN.
# target-db-parameter-group-identifier : The identifier for the copied DB parameter group.
Constraints:
Canât be null, empty, or blank
Must contain from 1 to 255 letters, numbers, or hyphens
First character must be a letter
Canât end with a hyphen or contain two consecutive hyphens
Example: my-db-parameter-group
# target-db-parameter-group-description : A description for the copied DB parameter group.
"""
add_option_dict = {}
add_option_dict["parameter_display_string"] = parameter_display_string
# ex: add_option_dict["no_value_parameter_list"] = "--single-parameter"
write_three_parameter("rds", "copy-db-parameter-group", "source-db-parameter-group-identifier", "target-db-parameter-group-identifier", "target-db-parameter-group-description", add_option_dict)
| [
"[email protected]"
]
| |
92710436566b708b08bd48d719f1d036e734bd41 | 1aeb828e57be9b046ee25433fff05956f01db53b | /python_bms/연습/파이썬/2309일곱난쟁이.py | e3763f5945dec78a7f01414e9b1daa99104cf9ab | []
| no_license | LynnYeonjuLee/TIL_BMS2 | 11f2753e2e82c4898a782d6907a21e973c34cf69 | f363723391598caf5ec6b33925fcb8a13a252d9f | refs/heads/master | 2023-01-22T00:45:25.091512 | 2020-12-04T00:22:44 | 2020-12-04T00:22:44 | 290,238,836 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 64 | py | for tc in range(9):
heights = int(input())
h_list = [0]* | [
"[email protected]"
]
| |
b73428382fda2e1ca751a76df524f3bcf515ef26 | 7967a3ee1c0ba80d2c4be404f5b779882cd24439 | /playground/config/apps.py | 8a5b10b147866b35f9dd3f69a721de35112665cc | [
"MIT"
]
| permissive | LeeHanYeong/django-quill-editor | bf0e7150afedc890652b20b288b27c635c777a5f | f49eabd65503462f0a9081626dfc66d2d7ddce36 | refs/heads/master | 2023-06-24T07:26:55.664214 | 2023-02-07T08:14:56 | 2023-02-07T08:30:14 | 245,107,729 | 184 | 44 | MIT | 2023-06-09T09:35:05 | 2020-03-05T08:27:55 | Python | UTF-8 | Python | false | false | 185 | py | from django.contrib.admin.apps import AdminConfig as DefaultAdminConfig
__all__ = ("AdminConfig",)
class AdminConfig(DefaultAdminConfig):
default_site = "config.admin.AdminSite"
| [
"[email protected]"
]
| |
10219f3aa82ee083283d3ab5e26f3e0d93b5266b | cf70b91df736d472d31a54c79bbdf124b7713adc | /docs/conf.py | 00d03b6ce5f611f322a30ce6a1b3ec1349168f29 | [
"MIT"
]
| permissive | andycasey/mcfa | 1e8a46d7c313988c4c0c57f214bd5268f8e35ae7 | 8c4135e665e47006e9ca725e8bfc67315508366e | refs/heads/master | 2021-06-16T02:27:01.686167 | 2019-09-30T02:18:17 | 2019-09-30T02:18:17 | 142,864,003 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,654 | py | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath("../"))
# -- Project information -----------------------------------------------------
project = 'mcfa'
copyright = '2018, Andrew R. Casey et al.'
author = 'Andrew R. Casey et al.'
# The short X.Y version
version = ''
# The full version, including alpha/beta/rc tags
release = ''
# -- General configuration ---------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.coverage',
'sphinx.ext.mathjax',
'sphinx.ext.viewcode',
'sphinx.ext.githubpages',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = None
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# The default sidebars (for documents that don't match any pattern) are
# defined by theme itself. Builtin themes are using these templates by
# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
# 'searchbox.html']``.
#
# html_sidebars = {}
# -- Options for HTMLHelp output ---------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'mcfadoc'
# -- Options for LaTeX output ------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'mcfa.tex', 'mcfa Documentation',
'Andrew R. Casey', 'manual'),
]
# -- Options for manual page output ------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'mcfa', 'mcfa Documentation',
[author], 1)
]
# -- Options for Texinfo output ----------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'mcfa', 'mcfa Documentation',
author, 'mcfa', 'One line description of project.',
'Miscellaneous'),
]
# -- Options for Epub output -------------------------------------------------
# Bibliographic Dublin Core info.
epub_title = project
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#
# epub_identifier = ''
# A unique identification for the text.
#
# epub_uid = ''
# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
# -- Extension configuration -------------------------------------------------
# -- Options for intersphinx extension ---------------------------------------
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'https://docs.python.org/': None}
autodoc_mock_imports = ['numpy', 'scipy', 'sklearn', 'tqdm']
| [
"[email protected]"
]
| |
3dffc5c20f744079690693c532bc36ee2d591421 | ef3a7391b0a5c5d8e276355e97cbe4de621d500c | /venv/Lib/site-packages/caffe2/quantization/server/group_norm_dnnlowp_op_test.py | 973576bc6ed334f54d6524e629e153233989b982 | [
"Apache-2.0"
]
| permissive | countBMB/BenjiRepo | 143f6da5d198ea6f06404b4559e1f4528b71b3eb | 79d882263baaf2a11654ca67d2e5593074d36dfa | refs/heads/master | 2022-12-11T07:37:04.807143 | 2019-12-25T11:26:29 | 2019-12-25T11:26:29 | 230,090,428 | 1 | 1 | Apache-2.0 | 2022-12-08T03:21:09 | 2019-12-25T11:05:59 | Python | UTF-8 | Python | false | false | 4,621 | py | from __future__ import absolute_import, division, print_function, unicode_literals
import collections
import caffe2.python.hypothesis_test_util as hu
import hypothesis.strategies as st
import numpy as np
from caffe2.python import core, dyndep, utils, workspace
from caffe2.quantization.server import utils as dnnlowp_utils
from dnnlowp_test_utils import check_quantized_results_close
from hypothesis import given
dyndep.InitOpsLibrary("//caffe2/caffe2/quantization/server:dnnlowp_ops")
workspace.GlobalInit(["caffe2", "--caffe2_omp_num_threads=11"])
class DNNLowPOpGroupNormTest(hu.HypothesisTestCase):
@given(
N=st.integers(0, 4),
G=st.integers(2, 4),
K=st.integers(2, 12),
H=st.integers(4, 16),
W=st.integers(4, 16),
order=st.sampled_from(["NCHW", "NHWC"]),
in_quantized=st.booleans(),
out_quantized=st.booleans(),
weight_quantized=st.booleans(),
**hu.gcs_cpu_only
)
def test_dnnlowp_group_norm(
self,
N,
G,
K,
H,
W,
order,
in_quantized,
out_quantized,
weight_quantized,
gc,
dc,
):
C = G * K
X = np.random.rand(N, C, H, W).astype(np.float32) * 5.0 - 1.0
if order == "NHWC":
X = utils.NCHW2NHWC(X)
gamma = np.random.rand(C).astype(np.float32) * 2.0 - 1.0
beta = np.random.randn(C).astype(np.float32) - 0.5
Output = collections.namedtuple("Output", ["Y", "op_type", "engine"])
outputs = []
op_engine_list = [
("GroupNorm", ""),
("GroupNorm", "DNNLOWP"),
("Int8GroupNorm", "DNNLOWP"),
]
for op_type, engine in op_engine_list:
net = core.Net("test_net")
do_quantize = "DNNLOWP" in engine and in_quantized
do_dequantize = "DNNLOWP" in engine and out_quantized
do_quantize_weight = (
engine == "DNNLOWP" and weight_quantized and len(outputs) > 0
)
if do_quantize:
quantize = core.CreateOperator(
"Quantize", ["X"], ["X_q"], engine=engine, device_option=gc
)
net.Proto().op.extend([quantize])
if do_quantize_weight:
int8_given_tensor_fill, gamma_q_param = dnnlowp_utils.create_int8_given_tensor_fill(
gamma, "gamma_q"
)
net.Proto().op.extend([int8_given_tensor_fill])
X_min = 0 if X.size == 0 else X.min()
X_max = 0 if X.size == 0 else X.max()
X_q_param = dnnlowp_utils.choose_quantization_params(X_min, X_max)
int8_bias_tensor_fill = dnnlowp_utils.create_int8_bias_tensor_fill(
beta, "beta_q", X_q_param, gamma_q_param
)
net.Proto().op.extend([int8_bias_tensor_fill])
group_norm = core.CreateOperator(
op_type,
[
"X_q" if do_quantize else "X",
"gamma_q" if do_quantize_weight else "gamma",
"beta_q" if do_quantize_weight else "beta",
],
["Y_q" if do_dequantize else "Y"],
dequantize_output=0 if do_dequantize else 1,
group=G,
order=order,
is_test=True,
engine=engine,
device_option=gc,
)
if do_quantize_weight:
# When quantized weight is provided, we can't rescale the
# output dynamically by looking at the range of output of each
# batch, so here we provide the range of output observed from
# fp32 reference implementation
dnnlowp_utils.add_quantization_param_args(group_norm, outputs[0][0])
net.Proto().op.extend([group_norm])
if do_dequantize:
dequantize = core.CreateOperator(
"Dequantize", ["Y_q"], ["Y"], engine=engine, device_option=gc
)
net.Proto().op.extend([dequantize])
self.ws.create_blob("X").feed(X, device_option=gc)
self.ws.create_blob("gamma").feed(gamma, device_option=gc)
self.ws.create_blob("beta").feed(beta, device_option=gc)
self.ws.run(net)
outputs.append(
Output(Y=self.ws.blobs["Y"].fetch(), op_type=op_type, engine=engine)
)
check_quantized_results_close(outputs, atol_scale=2.0)
| [
"[email protected]"
]
| |
b546b3ddc0e7dfe417126377133ce316d35c7020 | e13c98f36c362717fdf22468b300321802346ef5 | /documents/migrations/0001_initial.py | 6c30b613f871a3e0cbc4328170b19e5c35b4b42e | []
| no_license | alexmon1989/libraries_portal | 2415cc49de33459266a9f18ed8bb34ac99d3eb7c | 277081e09f6347c175775337bffba074a35f3b92 | refs/heads/master | 2021-01-23T07:25:53.884795 | 2018-12-25T14:29:29 | 2018-12-25T14:29:29 | 80,501,603 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,144 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-12-06 13:45
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('home', '0008_profile_address'),
]
operations = [
migrations.CreateModel(
name='AnotherPerson',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=255, verbose_name='Имя')),
],
options={
'verbose_name_plural': 'Другие пресоны',
'verbose_name': 'Другая пресона',
},
),
migrations.CreateModel(
name='Document',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=255, verbose_name='Название')),
('author', models.CharField(max_length=255, verbose_name='Автор')),
('notes', models.TextField(verbose_name='Примечания')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('another_persons', models.ManyToManyField(blank=True, to='documents.AnotherPerson', verbose_name='Другие персоны')),
],
),
migrations.CreateModel(
name='DocumentType',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=255, verbose_name='Название')),
],
),
migrations.CreateModel(
name='Rubric',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=255, verbose_name='Название')),
],
options={
'verbose_name_plural': 'Рубрики',
'verbose_name': 'Рубрика',
},
),
migrations.AddField(
model_name='document',
name='document_type',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='documents.DocumentType', verbose_name='Тип документа'),
),
migrations.AddField(
model_name='document',
name='library',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='home.Library', verbose_name='Библиотека'),
),
migrations.AddField(
model_name='document',
name='rubrics',
field=models.ManyToManyField(blank=True, to='documents.Rubric', verbose_name='Рубрики'),
),
]
| [
"[email protected]"
]
| |
2351ca814b5fc811cbe99d550c0e9c2c1ce73a95 | 3247e7151711e257e2eeebf9b57487bfe3e4b239 | /backend/manage.py | 58715ed4c97a92e328f590a9375167cfbbd0eb43 | []
| no_license | crowdbotics-apps/wam-18762 | 6703f5e275b3afecd814ec4d6f8cef96b55d105c | 069669b42d42be0c310433e020c82cad83c186a9 | refs/heads/master | 2022-11-19T03:30:28.338372 | 2020-07-10T16:50:17 | 2020-07-10T16:50:17 | 278,461,990 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 629 | py | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "wam_18762.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == "__main__":
main()
| [
"[email protected]"
]
| |
838878a7c21c4d3041bdd02699936657ce06ad10 | e3365bc8fa7da2753c248c2b8a5c5e16aef84d9f | /indices/locket.py | 64afc11dcc2dc630d17738ff6e338fc2675aad89 | []
| no_license | psdh/WhatsintheVector | e8aabacc054a88b4cb25303548980af9a10c12a8 | a24168d068d9c69dc7a0fd13f606c080ae82e2a6 | refs/heads/master | 2021-01-25T10:34:22.651619 | 2015-09-23T11:54:06 | 2015-09-23T11:54:06 | 42,749,205 | 2 | 3 | null | 2015-09-23T11:54:07 | 2015-09-18T22:06:38 | Python | UTF-8 | Python | false | false | 122 | py | ii = [('BailJD2.py', 1), ('GilmCRS.py', 6), ('EdgeMHT.py', 19), ('RoscTTI.py', 1), ('JacoWHI2.py', 1), ('HogaGMM2.py', 2)] | [
"[email protected]"
]
| |
25d7024a3f721b5139b7b411e7d035a562642b33 | a17b30a9ed9e18e89433aadbb54ac94e7ea12045 | /tests/test_feature.py | 79ae55a811979865532f3a906c12e46cbdee7443 | [
"BSD-3-Clause"
]
| permissive | HuttleyLab/mutationorigin | b327fcbc9d9403006f2e9f8166b73185698d7dca | 614aa0bc25531a1a0bc24f94ad0ca0fc101aa88a | refs/heads/develop | 2021-06-30T01:37:05.359810 | 2020-02-10T02:26:55 | 2020-02-10T02:26:55 | 210,751,092 | 1 | 3 | BSD-3-Clause | 2021-01-14T03:22:40 | 2019-09-25T03:53:11 | Python | UTF-8 | Python | false | false | 3,705 | py | from unittest import TestCase, main
from mutation_origin.feature import (isproximal, get_feature_indices,
feature_indices_upto, seq_2_features,
seq_feature_labels_upto)
__author__ = "Gavin Huttley"
__copyright__ = "Copyright 2014, Gavin Huttley"
__credits__ = ["Yicheng Zhu", "Cheng Soon Ong", "Gavin Huttley"]
__license__ = "BSD"
__version__ = "0.3"
__maintainer__ = "Gavin Huttley"
__email__ = "[email protected]"
__status__ = "Development"
class TestEncoder(TestCase):
def test_isproximal(self):
"""given a dimension value, return columns in a feature matrix with
defined dimensional neighborhood"""
self.assertTrue(isproximal([1]))
self.assertTrue(isproximal([0, 1]))
self.assertTrue(isproximal([1, 0]))
self.assertTrue(isproximal([0, 1, 2]))
self.assertTrue(isproximal([2, 3, 4]))
self.assertFalse(isproximal([0, 2]))
self.assertFalse(isproximal([0, 3, 4]))
self.assertFalse(isproximal([0, 1, 3]))
self.assertFalse(isproximal([1, 2, 4]))
def test_get_feature_indices(self):
"""selecting feature indices"""
# case of single positions
got = get_feature_indices(2, 1)
self.assertEqual(got, [(0,), (1,), (2,), (3,)])
got = get_feature_indices(2, 2)
self.assertEqual(got, [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)])
got = get_feature_indices(2, 2, proximal=True)
self.assertEqual(got, [(0, 1), (1, 2), (2, 3)])
def test_feature_indices_upto(self):
"""correctly produces all feature indices"""
got = feature_indices_upto(4, 1, proximal=False)
self.assertEqual(got, [(0,), (1,), (2,), (3,), (4,), (5,), (6,), (7,)])
got = feature_indices_upto(2, 2, proximal=False)
self.assertEqual(got, [(0,), (1,), (2,), (3,),
(0, 1), (0, 2), (0, 3),
(1, 2), (1, 3),
(2, 3)])
got = feature_indices_upto(2, 2, proximal=True)
self.assertEqual(got, [(0,), (1,), (2,), (3,),
(0, 1), (1, 2), (2, 3)])
got = feature_indices_upto(2, 3, proximal=False)
self.assertEqual(got, [(0,), (1,), (2,), (3,),
(0, 1), (0, 2), (0, 3),
(1, 2), (1, 3),
(2, 3),
(0, 1, 2), (0, 1, 3),
(0, 2, 3), (1, 2, 3)])
def test_seq_2_features(self):
"""convert a sequence to string features"""
seq = "CAGA"
indices = feature_indices_upto(2, 1, proximal=False)
got = seq_2_features(seq, indices)
self.assertEqual(got, ['C', 'A', 'G', 'A'])
indices = feature_indices_upto(2, 2, proximal=False)
got = seq_2_features(seq, indices)
self.assertEqual(got, ['C', 'A', 'G', 'A',
'CA', 'CG', 'CA',
'AG', 'AA', 'GA'])
indices = feature_indices_upto(2, 2, proximal=True)
got = seq_2_features(seq, indices)
self.assertEqual(got, ['C', 'A', 'G', 'A',
'CA', 'AG', 'GA'])
def test_seq_feature_labels_upto(self):
"""construction of sequence feature labels"""
# the possible labels for a given dimension
# is just the k-mers for that dimension
for dim in range(1, 5):
got = seq_feature_labels_upto(dim)
for i in range(1, dim + 1):
self.assertEqual(4**i, len(got[i].classes_))
if __name__ == '__main__':
main()
| [
"[email protected]"
]
| |
2cf68c4c488cae807414c8d867e8fab21bbd5f08 | 935e6fc5f32dfd6dcd7db4c2ef2b6083e9dcd867 | /examples/whbm/lstm_task.py | 4637ae76103386793980ff053a3f90f6a6978202 | []
| no_license | zkmartin/tsframe | 0e805d76c89f647aa102e0acd5d75831f5dd808f | b522180f8179b52c4b1e510882813da912243e33 | refs/heads/master | 2020-03-21T13:14:08.559186 | 2018-06-12T14:03:00 | 2018-06-12T14:03:00 | 138,594,568 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 793 | py | import tensorflow as tf
import core
from tframe import console
import model_lib as models
def main(_):
console.start('WHBM task (LSTM model)')
# Configurations
th = core.th
th.model = models.lstm
th.num_blocks = 1
th.memory_depth = 2
th.hidden_dim = 100
th.epoch = 50000
th.learning_rate = 1e-4
th.batch_size = 8
th.num_steps = 100
th.val_preheat = 500
th.validation_per_round = 2
th.print_cycle = 2
# th.train = False
th.smart_train = True
th.max_bad_apples = 4
th.lr_decay = 0.5
th.save_model = True
th.overwrite = True
th.export_note = True
th.summary = True
th.monitor = False
description = ''
th.mark = '{}x{}{}'.format(th.num_blocks, th.memory_depth, description)
core.activate()
if __name__ == '__main__':
tf.app.run()
| [
"[email protected]"
]
| |
ccc08696bb1af782a16f12ab9b1ff3d1aa5fa18e | 8eebf844c95adcc6d969e19a6d5335b25f7024e7 | /tenancy/models.py | b261d02af299d8ba7c77ac3d4d51bd97e098a55b | []
| no_license | ape-goku/django-tenancy | a6508926f7f974a459057b3c80d3a3c546cc7870 | d52383c7f3a220b8c463dec82ac8502b3c8095c6 | refs/heads/master | 2021-01-15T16:28:34.681513 | 2014-12-04T22:14:32 | 2014-12-04T22:14:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 25,770 | py | from __future__ import unicode_literals
from abc import ABCMeta
# TODO: Remove when support for Python 2.6 is dropped
try:
from collections import OrderedDict
except ImportError:
from django.utils.datastructures import SortedDict as OrderedDict
import copy
from contextlib import contextmanager
import logging
from django.core.exceptions import ImproperlyConfigured
from django.db import connections, DEFAULT_DB_ALIAS, models
from django.db.models.base import ModelBase, subclass_exception
from django.db.models.deletion import DO_NOTHING
from django.db.models.fields import Field
from django.db.models.fields.related import add_lazy_relation
from django.dispatch.dispatcher import receiver
from django.utils.six import itervalues, string_types, with_metaclass
from django.utils.six.moves import copyreg
from . import get_tenant_model
from .management import create_tenant_schema, drop_tenant_schema
from .managers import (
AbstractTenantManager, TenantManager, TenantModelManagerDescriptor
)
from .signals import lazy_class_prepared
from .utils import (
clear_opts_related_cache, disconnect_signals, get_model,
receivers_for_model, remove_from_app_cache
)
class TenantModels(object):
__slots__ = ['references']
def __init__(self, tenant):
self.references = OrderedDict((
(reference, reference.for_tenant(tenant))
for reference in TenantModelBase.references
))
def __getitem__(self, key):
return self.references[key]
def __iter__(self, **kwargs):
return itervalues(self.references, **kwargs)
class TenantModelsDescriptor(object):
def contribute_to_class(self, cls, name):
self.name = name
setattr(cls, name, self)
def _get_instance(self, instance):
return instance._default_manager.get_by_natural_key(
*instance.natural_key()
)
def __get__(self, instance, owner):
if instance is None:
return self
instance = self._get_instance(instance)
try:
models = instance.__dict__[self.name]
except KeyError:
models = TenantModels(instance)
self.__set__(instance, models)
return models
def __set__(self, instance, value):
instance = self._get_instance(instance)
instance.__dict__[self.name] = value
def __delete__(self, instance):
for model in self.__get__(instance, owner=None):
model.destroy()
class AbstractTenant(models.Model):
ATTR_NAME = 'tenant'
objects = AbstractTenantManager()
class Meta:
abstract = True
def __init__(self, *args, **kwargs):
super(AbstractTenant, self).__init__(*args, **kwargs)
if self.pk:
self._default_manager._add_to_cache(self)
def save(self, *args, **kwargs):
created = not self.pk
save = super(AbstractTenant, self).save(*args, **kwargs)
if created:
create_tenant_schema(self)
return save
def delete(self, *args, **kwargs):
delete = super(AbstractTenant, self).delete(*args, **kwargs)
drop_tenant_schema(self)
return delete
def natural_key(self):
raise NotImplementedError
models = TenantModelsDescriptor()
@contextmanager
def as_global(self):
"""
Expose this tenant as thread local object. This is required by parts
of django relying on global states such as authentification backends.
"""
connection = connections[DEFAULT_DB_ALIAS]
try:
setattr(connection, self.ATTR_NAME, self)
yield
finally:
delattr(connection, self.ATTR_NAME)
@property
def model_name_prefix(self):
return "Tenant_%s" % '_'.join(self.natural_key())
@property
def db_schema(self):
return "tenant_%s" % '_'.join(self.natural_key())
class Tenant(AbstractTenant):
name = models.CharField(unique=True, max_length=20)
objects = TenantManager()
class Meta:
swappable = 'TENANCY_TENANT_MODEL'
def natural_key(self):
return (self.name,)
def meta(Meta=None, **opts):
"""
Create a class with specified opts as attributes to be used as model
definition options.
"""
if Meta:
opts = dict(Meta.__dict__, **opts)
return type(str('Meta'), (), opts)
def db_schema_table(tenant, db_table):
connection = connections[tenant._state.db or DEFAULT_DB_ALIAS]
if connection.vendor == 'postgresql':
# See https://code.djangoproject.com/ticket/6148#comment:47
return '%s\".\"%s' % (tenant.db_schema, db_table)
else:
return "%s_%s" % (tenant.db_schema, db_table)
class Reference(object):
__slots__ = ['model', 'bases', 'Meta', 'related_names']
def __init__(self, model, Meta, related_names=None):
self.model = model
self.Meta = Meta
self.related_names = related_names
def object_name_for_tenant(self, tenant):
return "%s_%s" % (
tenant.model_name_prefix,
self.model._meta.object_name
)
def for_tenant(self, tenant):
app_label = self.model._meta.app_label
object_name = self.object_name_for_tenant(tenant)
return "%s.%s" % (app_label, object_name)
class TenantSpecificModel(with_metaclass(ABCMeta)):
@classmethod
def __subclasshook__(cls, subclass):
if isinstance(subclass, TenantModelBase):
try:
tenant_model = get_tenant_model(False)
except ImproperlyConfigured:
# If the tenant model is not configured yet we can assume
# no specific models have been defined so far.
return False
tenant = getattr(subclass, tenant_model.ATTR_NAME, None)
return isinstance(tenant, tenant_model)
return NotImplemented
class TenantDescriptor(object):
__slots__ = ['natural_key']
def __init__(self, tenant):
self.natural_key = tenant.natural_key()
def __get__(self, model, owner):
tenant_model = get_tenant_model()
return tenant_model._default_manager.get_by_natural_key(*self.natural_key)
class TenantModelBase(ModelBase):
reference = Reference
references = OrderedDict()
tenant_model_class = None
exceptions = ('DoesNotExist', 'MultipleObjectsReturned')
def __new__(cls, name, bases, attrs):
super_new = super(TenantModelBase, cls).__new__
# attrs will never be empty for classes declared in the standard way
# (ie. with the `class` keyword). This is quite robust.
if name == 'NewBase' and attrs == {}:
return super_new(cls, name, bases, attrs)
Meta = attrs.setdefault('Meta', meta())
if (getattr(Meta, 'abstract', False) or
any(issubclass(base, TenantSpecificModel) for base in bases)):
# Abstract model definition and ones subclassing tenant specific
# ones shouldn't get any special treatment.
model = super_new(cls, name, bases, attrs)
if not cls.tenant_model_class:
cls.tenant_model_class = model
else:
# Store managers to replace them with a descriptor specifying they
# can't be accessed this way.
managers = set(
name for name, attr in attrs.items()
if isinstance(attr, models.Manager)
)
# There's always a default manager named `objects`.
managers.add('objects')
if getattr(Meta, 'proxy', False):
model = super_new(
cls, name, bases,
dict(attrs, meta=meta(Meta, managed=False))
)
cls.references[model] = cls.reference(model, Meta)
else:
# Extract field related names prior to adding them to the model
# in order to validate them later on.
related_names = dict(
(attr.name or name, attr.rel.related_name)
for name, attr in attrs.items()
if isinstance(attr, Field) and attr.rel
)
for base in bases:
if isinstance(base, ModelBase) and base._meta.abstract:
for field in base._meta.local_fields:
if field.rel:
related_names[field.name] = field.rel.related_name
for m2m in base._meta.local_many_to_many:
related_names[m2m.name] = m2m.rel.related_name
model = super_new(
cls, name, bases,
dict(attrs, Meta=meta(Meta, managed=False))
)
cls.references[model] = cls.reference(model, Meta, related_names)
opts = model._meta
# Validate related name of related fields.
for field in (opts.local_fields + opts.virtual_fields):
rel = getattr(field, 'rel', None)
if rel:
cls.validate_related_name(field, field.rel.to, model)
# Replace and store the current `on_delete` value to
# make sure non-tenant models are not collected on
# deletion.
on_delete = rel.on_delete
if on_delete is not DO_NOTHING:
rel._on_delete = on_delete
rel.on_delete = DO_NOTHING
for m2m in opts.local_many_to_many:
rel = m2m.rel
to = rel.to
cls.validate_related_name(m2m, to, model)
through = rel.through
if (not isinstance(through, string_types) and
through._meta.auto_created):
# Replace the automatically created intermediary model
# by a TenantModelBase instance.
remove_from_app_cache(through)
# Make sure to clear the referenced model cache if
# we have contributed to it already.
if not isinstance(to, string_types):
clear_opts_related_cache(rel.to)
rel.through = cls.intermediary_model_factory(m2m, model)
else:
cls.validate_through(m2m, m2m.rel.to, model)
# Replace `ManagerDescriptor`s with `TenantModelManagerDescriptor`
# instances.
for manager in managers:
setattr(model, manager, TenantModelManagerDescriptor(model))
# Extract the specified related name if it exists.
try:
related_name = attrs.pop('TenantMeta').related_name
except (KeyError, AttributeError):
pass
else:
# Attach a descriptor to the tenant model to access the
# underlying model based on the tenant instance.
def attach_descriptor(tenant_model):
descriptor = TenantModelDescriptor(model)
setattr(tenant_model, related_name, descriptor)
# Avoid circular imports on Django < 1.7
from .settings import TENANT_MODEL
app_label, model_name = TENANT_MODEL.split('.')
lazy_class_prepared(app_label, model_name, attach_descriptor)
model._for_tenant_model = model
return model
@classmethod
def validate_related_name(cls, field, rel_to, model):
"""
Make sure that related fields pointing to non-tenant models specify
a related name containing a %(class)s format placeholder.
"""
if isinstance(rel_to, string_types):
add_lazy_relation(model, field, rel_to, cls.validate_related_name)
elif not isinstance(rel_to, TenantModelBase):
related_name = cls.references[model].related_names[field.name]
if (related_name is not None and
not (field.rel.is_hidden() or '%(class)s' in related_name)):
del cls.references[model]
remove_from_app_cache(model, quiet=True)
raise ImproperlyConfigured(
"Since `%s.%s` is originating from an instance "
"of `TenantModelBase` and not pointing to one "
"its `related_name` option must ends with a "
"'+' or contain the '%%(class)s' format "
"placeholder." % (model.__name__, field.name)
)
@classmethod
def validate_through(cls, field, rel_to, model):
"""
Make sure the related fields with a specified through points to an
instance of `TenantModelBase`.
"""
through = field.rel.through
if isinstance(through, string_types):
add_lazy_relation(model, field, through, cls.validate_through)
elif not isinstance(through, cls):
del cls.references[model]
remove_from_app_cache(model, quiet=True)
raise ImproperlyConfigured(
"Since `%s.%s` is originating from an instance of "
"`TenantModelBase` its `through` option must also be pointing "
"to one." % (model.__name__, field.name)
)
@classmethod
def intermediary_model_factory(cls, field, from_model):
to_model = field.rel.to
opts = from_model._meta
from_model_name = opts.model_name
if to_model == from_model:
from_ = "from_%s" % from_model_name
to = "to_%s" % from_model_name
to_model = from_model
else:
from_ = from_model_name
if isinstance(to_model, string_types):
to = to_model.split('.')[-1].lower()
else:
to = to_model._meta.model_name
Meta = meta(
db_table=field._get_m2m_db_table(opts),
auto_created=from_model,
app_label=opts.app_label,
db_tablespace=opts.db_tablespace,
unique_together=(from_, to),
verbose_name="%(from)s-%(to)s relationship" % {'from': from_, 'to': to},
verbose_name_plural="%(from)s-%(to)s relationships" % {'from': from_, 'to': to}
)
name = str("%s_%s" % (opts.object_name, field.name))
field_opts = {'db_tablespace': field.db_tablespace}
# Django 1.6 introduced `db_contraint`.
if hasattr(field, 'db_constraint'):
field_opts['db_constraint'] = field.db_constraint
return type(name, (cls.tenant_model_class,), {
'Meta': Meta,
'__module__': from_model.__module__,
from_: models.ForeignKey(
from_model, related_name="%s+" % name, **field_opts
),
to: models.ForeignKey(
to_model, related_name="%s+" % name, **field_opts
),
})
@classmethod
def tenant_model_bases(cls, tenant, bases):
return tuple(
base.for_tenant(tenant) for base in bases
if isinstance(base, cls) and not base._meta.abstract
)
def abstract_tenant_model_factory(self, tenant):
if issubclass(self, TenantSpecificModel):
raise ValueError('Can only be called on non-tenant specific model.')
reference = self.references[self]
model = super(TenantModelBase, self).__new__(
self.__class__,
str("Abstract%s" % reference.object_name_for_tenant(tenant)),
(self,) + self.tenant_model_bases(tenant, self.__bases__), {
'__module__': self.__module__,
'Meta': meta(
reference.Meta,
abstract=True
),
tenant.ATTR_NAME: TenantDescriptor(tenant),
'_for_tenant_model': self
}
)
opts = model._meta
# Remove ourself from the parents chain and our descriptor
ptr = opts.parents.pop(self)
opts.local_fields.remove(ptr)
delattr(model, ptr.name)
# Rename parent ptr fields
for parent, ptr in opts.parents.items():
local_ptr = self._meta.parents[parent._for_tenant_model]
ptr.name = None
ptr.set_attributes_from_name(local_ptr.name)
# Add copy of the fields to cloak the inherited ones.
fields = (
copy.deepcopy(field) for field in (
self._meta.local_fields +
self._meta.local_many_to_many +
self._meta.virtual_fields
)
)
for field in fields:
rel = getattr(field, 'rel', None)
if rel:
# Make sure related fields pointing to tenant models are
# pointing to their tenant specific counterpart.
to = rel.to
if isinstance(to, TenantModelBase):
if getattr(rel, 'parent_link', False):
continue
rel.to = self.references[to].for_tenant(tenant)
# If no `related_name` was specified we make sure to
# define one based on the non-tenant specific model name.
if not rel.related_name:
rel.related_name = "%s_set" % self._meta.model_name
else:
clear_opts_related_cache(to)
related_name = reference.related_names[field.name]
# The `related_name` was validated earlier to either end
# with a '+' sign or to contain %(class)s.
if related_name:
rel.related_name = related_name
else:
related_name = 'unspecified_for_tenant_model+'
if isinstance(field, models.ManyToManyField):
through = field.rel.through
rel.through = self.references[through].for_tenant(tenant)
# Re-assign the correct `on_delete` that was swapped for
# `DO_NOTHING` to prevent non-tenant model collection.
on_delete = getattr(rel, '_on_delete', None)
if on_delete:
rel.on_delete = on_delete
field.contribute_to_class(model, field.name)
# Some virtual fields such as GenericRelation are not correctly
# cloaked by `contribute_to_class`. Make sure to remove non-tenant
# virtual instances from tenant specific model options.
for virtual_field in self._meta.virtual_fields:
if virtual_field in opts.virtual_fields:
opts.virtual_fields.remove(virtual_field)
return model
def _prepare(self):
super(TenantModelBase, self)._prepare()
if issubclass(self, TenantSpecificModel):
for_tenant_model = self._for_tenant_model
# Attach the tenant model concrete managers since they should
# override the ones from abstract bases.
managers = for_tenant_model._meta.concrete_managers
for _, mgr_name, manager in managers:
new_manager = manager._copy_to_model(self)
new_manager.creation_counter = manager.creation_counter
self.add_to_class(mgr_name, new_manager)
# Since our declaration class is not one of our parents we must
# make sure our exceptions extend his.
for exception in self.exceptions:
subclass = subclass_exception(
str(exception),
(getattr(self, exception), getattr(for_tenant_model, exception)),
self.__module__,
self,
)
self.add_to_class(exception, subclass)
def for_tenant(self, tenant):
"""
Returns the model for the specific tenant.
"""
if issubclass(self, TenantSpecificModel):
raise ValueError('Can only be called on non-tenant specific model.')
reference = self.references[self]
opts = self._meta
name = reference.object_name_for_tenant(tenant)
# Return the already cached model instead of creating a new one.
model = get_model(
opts.app_label, name.lower(),
only_installed=False
)
if model:
return model
attrs = {
'__module__': self.__module__,
'Meta': meta(
reference.Meta,
# TODO: Use `db_schema` once django #6148 is fixed.
db_table=db_schema_table(tenant, self._meta.db_table),
)
}
if opts.proxy:
attrs['_for_tenant_model'] = self
# In order to make sure the non-tenant model is part of the
# __mro__ we create an abstract model with stripped fields and
# inject it as the first base.
base = type(
str("Abstract%s" % reference.object_name_for_tenant(tenant)),
(self,), {
'__module__': self.__module__,
'Meta': meta(abstract=True),
}
)
# Remove ourself from the parents chain and our descriptor
base_opts = base._meta
ptr = base_opts.parents.pop(opts.concrete_model)
base_opts.local_fields.remove(ptr)
delattr(base, ptr.name)
bases = (base,) + self.tenant_model_bases(tenant, self.__bases__)
else:
bases = (self.abstract_tenant_model_factory(tenant),)
model = super(TenantModelBase, self).__new__(
TenantModelBase, str(name), bases, attrs
)
return model
def destroy(self):
"""
Remove all reference to this tenant model.
"""
if not issubclass(self, TenantSpecificModel):
raise ValueError('Can only be called on tenant specific model.')
remove_from_app_cache(self, quiet=True)
if not self._meta.proxy:
# Some fields (GenericForeignKey, ImageField) attach (pre|post)_init
# signals to their associated model even if they are abstract.
# Since this instance was created from an abstract base generated
# by `abstract_tenant_model_factory` we must make sure to disconnect
# all signal receivers attached to it in order to be gc'ed.
disconnect_signals(self.__bases__[0])
def __unpickle_tenant_model_base(model, natural_key, abstract):
try:
manager = get_tenant_model()._default_manager
tenant = manager.get_by_natural_key(*natural_key)
tenant_model = model.for_tenant(tenant)
if abstract:
tenant_model = tenant_model.__bases__[0]
return tenant_model
except Exception:
logger = logging.getLogger('tenancy.pickling')
logger.exception('Failed to unpickle tenant model')
def __pickle_tenant_model_base(model):
if issubclass(model, TenantSpecificModel):
tenant = getattr(model, get_tenant_model().ATTR_NAME)
return (
__unpickle_tenant_model_base,
(model._for_tenant_model, tenant.natural_key(), model._meta.abstract)
)
return model.__name__
copyreg.pickle(TenantModelBase, __pickle_tenant_model_base)
class TenantModelDescriptor(object):
__slots__ = ['model']
def __init__(self, model):
self.model = model
def __get__(self, tenant, owner):
if not tenant:
return self
return tenant.models[self.model]._default_manager
class TenantModel(with_metaclass(TenantModelBase, models.Model)):
class Meta:
abstract = True
@receiver(models.signals.class_prepared)
def attach_signals(signal, sender, **kwargs):
"""
Re-attach signals to tenant models
"""
if issubclass(sender, TenantSpecificModel):
for signal, receiver_ in receivers_for_model(sender._for_tenant_model):
signal.connect(receiver_, sender=sender)
def validate_not_to_tenant_model(field, to, model):
"""
Make sure the `to` relationship is not pointing to an instance of
`TenantModelBase`.
"""
if isinstance(to, string_types):
add_lazy_relation(model, field, to, validate_not_to_tenant_model)
elif isinstance(to, TenantModelBase):
remove_from_app_cache(model, quiet=True)
raise ImproperlyConfigured(
"`%s.%s`'s `to` option` can't point to an instance of "
"`TenantModelBase` since it's not one itself." % (
model.__name__, field.name
)
)
@receiver(models.signals.class_prepared)
def validate_relationships(signal, sender, **kwargs):
"""
Non-tenant models can't have relationships pointing to tenant models.
"""
if not isinstance(sender, TenantModelBase):
opts = sender._meta
# Don't validate auto-intermediary models since they are created
# before their origin model (from) and cloak the actual, user-defined
# improper configuration.
if not opts.auto_created:
for field in opts.local_fields:
if field.rel:
validate_not_to_tenant_model(field, field.rel.to, sender)
for m2m in opts.local_many_to_many:
validate_not_to_tenant_model(m2m, m2m.rel.to, sender)
| [
"[email protected]"
]
| |
8df4ca9b5e0fe7752819761c02071cc06fc4b1a2 | 68e76ef27df38b0fe2c1c993a9c15896563f950d | /2 Практика Робот/robot-tasks-master/task_27.py | adb36b2f4c4d8b0d56eece184d7dc0228bed4853 | []
| no_license | Jumas-Cola/mipt_cs_on_python3_answers | 72e9341656daa4afa35f8d39de917eb5471ee132 | a2d128c4ce391bdeea6d20eb955855ad5bc5a0b4 | refs/heads/master | 2020-03-27T23:44:09.088994 | 2019-07-29T13:55:35 | 2019-07-29T13:55:35 | 147,341,552 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 242 | py | #!/usr/bin/python3
from pyrob.api import *
@task
def task_7_5():
n = 0
i = 0
move_right()
while not wall_is_on_the_right():
if i==n:
fill_cell()
n+=1
i=0
move_right()
i+=1
if __name__ == '__main__':
run_tasks()
| [
"[email protected]"
]
| |
8f90c43fdb9608255f7aee58ef6c166d69b5e865 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p00001/s858862768.py | ef31f0508caf06e2a57f4dcb7d9882d5a5cb5fd8 | []
| no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 137 | py | #coding: utf-8
temp = []
for i in range(10):
N = input()
temp.append(N)
temp.sort()
print temp[-1]
print temp[-2]
print temp[-3] | [
"[email protected]"
]
| |
1aece47b2e3ac6f10e5639dc6cb4c83423d6d772 | d01a8a10cb6b5bdde50e5f522cb8bd5012910393 | /footfolder_25603/wsgi.py | 615846566d9480ca8e337c50ac41ebfff8a07680 | []
| no_license | crowdbotics-apps/footfolder-25603 | 7231ab4c4db7f082ff1488bc69e00f637950b3a6 | 82be1f77f7f2658ab6244a1913b0a8b8109452b4 | refs/heads/master | 2023-04-02T20:48:15.819920 | 2021-04-09T21:13:24 | 2021-04-09T21:13:24 | 356,399,532 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 409 | py | """
WSGI config for footfolder_25603 project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'footfolder_25603.settings')
application = get_wsgi_application()
| [
"[email protected]"
]
| |
90f51bda9748dbaf04ac10395e80bfc9dc869487 | 9fb7df549d33b3b3d854d60873b8047c885eedf4 | /lib/pycbio/stats/__init__.py | 87dcb27c11a9defeb6845711a66e8fe5f831dc67 | []
| no_license | strbean/pubMunch-BRCA | 3a24199440b71469d3fb0135e1d3a9d3823d39b5 | b7eb1270a2f69a262747d1366e0cd16e5b222b5d | refs/heads/master | 2020-03-22T22:57:41.558632 | 2018-09-25T04:59:47 | 2018-09-25T04:59:47 | 140,781,441 | 0 | 0 | null | 2018-07-13T01:29:13 | 2018-07-13T01:29:12 | null | UTF-8 | Python | false | false | 112 | py | # Copyright 2006-2012 Mark Diekhans
from pycbio.stats.Venn import Venn
from pycbio.stats.Subsets import Subsets
| [
"[email protected]"
]
| |
d9442ec4991157e8ecacec81963170be831c63f4 | 3a28b1a12d0710c06f6360381ad8be6cf3707907 | /modular_model/triHPC/triHPCThermo/HPCFeed2SelfCstmLiqEtlp_pP.py | 50a3ca49480d7c661fda3be8fe4136376d2ddf41 | []
| no_license | WheatZhang/DynamicModelling | 6ce1d71d3b55176fd4d77a6aedbaf87e25ce4d02 | ea099245135fe73e8c9590502b9c8b87768cb165 | refs/heads/master | 2020-06-15T14:12:50.373047 | 2019-07-05T01:37:06 | 2019-07-05T01:37:06 | 195,319,788 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 247 | py | def LiqEtlp_pP(P,T,x_N2):
x = (P-5.40396585e+02)/1.23902400e-01
y = (T--1.78102248e+02)/2.35833333e-03
z = (x_N2-9.97848887e-01)/4.61257558e-04
output = \
1*-7.45932272e-01
liq_etlp = output*1.00000000e+00+0.00000000e+00
return liq_etlp | [
"[email protected]"
]
| |
03e81ca2b65853869b3c82f32c0a5025d22b0183 | b99d44bc1eea1681185429dab0c238e9fa45dc2e | /datatypes/Data/Functor/pure.src.py | 11f50c806d872d8946d83dd63337787f3565129f | []
| no_license | Testing-PureScript-Python/datatypes | 0933218ed21329be440a0218ee996b206b9ecf50 | 838cbca1a87cb4eea8a22c796799fb7fad69191d | refs/heads/master | 2021-01-05T21:33:40.556174 | 2020-02-24T05:02:32 | 2020-02-24T05:02:32 | 241,143,733 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,528 | py | from py_sexpr.terms import *
from py_sexpr.stack_vm.emit import module_code
res = block( "No document"
, assign_star( "$foreign"
, call( var('import_module')
, "datatypes.ffi.Data.Functor" ) )
, assign_star( "ps_Control_Semigroupoid"
, call( var('import_module')
, "datatypes.Control.Semigroupoid.pure" ) )
, assign_star( "ps_Data_Function"
, call( var('import_module')
, "datatypes.Data.Function.pure" ) )
, assign_star( "ps_Data_Unit"
, call( var('import_module')
, "datatypes.Data.Unit.pure" ) )
, assign_star( "ps_Functor"
, define( None
, ["ps_map", ".this"]
, block( set_item( var(".this")
, "map"
, var("ps_map") )
, var(".this") ) ) )
, assign_star( "ps_map"
, define( None
, ["ps_dict"]
, block( ret( get_item( var("ps_dict")
, "map" ) ) ) ) )
, assign_star( "ps_mapFlipped"
, define( None
, ["ps_dictFunctor"]
, block( ret( define( None
, ["ps_fa"]
, block( ret( define( None
, [ "ps_f" ]
, block( ret( call( call( call( var( "ps_map" )
, var( "ps_dictFunctor" ) )
, var( "ps_f" ) )
, var( "ps_fa" ) ) ) ) ) ) ) ) ) ) ) )
, assign_star( "ps_void"
, define( None
, ["ps_dictFunctor"]
, block( ret( call( call( var("ps_map")
, var( "ps_dictFunctor" ) )
, call( get_item( var( "ps_Data_Function" )
, "const" )
, get_item( var( "ps_Data_Unit" )
, "unit" ) ) ) ) ) ) )
, assign_star( "ps_voidLeft"
, define( None
, ["ps_dictFunctor"]
, block( ret( define( None
, ["ps_f"]
, block( ret( define( None
, [ "ps_x" ]
, block( ret( call( call( call( var( "ps_map" )
, var( "ps_dictFunctor" ) )
, call( get_item( var( "ps_Data_Function" )
, "const" )
, var( "ps_x" ) ) )
, var( "ps_f" ) ) ) ) ) ) ) ) ) ) ) )
, assign_star( "ps_voidRight"
, define( None
, ["ps_dictFunctor"]
, block( ret( define( None
, ["ps_x"]
, block( ret( call( call( var( "ps_map" )
, var( "ps_dictFunctor" ) )
, call( get_item( var( "ps_Data_Function" )
, "const" )
, var( "ps_x" ) ) ) ) ) ) ) ) ) )
, assign_star( "ps_functorFn"
, new( var("ps_Functor")
, call( get_item( var("ps_Control_Semigroupoid")
, "compose" )
, get_item( var("ps_Control_Semigroupoid")
, "semigroupoidFn" ) ) ) )
, assign_star( "ps_functorArray"
, new( var("ps_Functor")
, get_item(var("$foreign"), "arrayMap") ) )
, assign_star( "ps_flap"
, define( None
, ["ps_dictFunctor"]
, block( ret( define( None
, ["ps_ff"]
, block( ret( define( None
, [ "ps_x" ]
, block( ret( call( call( call( var( "ps_map" )
, var( "ps_dictFunctor" ) )
, define( None
, [ "ps_f" ]
, block( ret( call( var( "ps_f" )
, var( "ps_x" ) ) ) ) ) )
, var( "ps_ff" ) ) ) ) ) ) ) ) ) ) ) )
, assign( "exports"
, record( ("Functor", var("ps_Functor"))
, ("map", var("ps_map"))
, ("mapFlipped", var("ps_mapFlipped"))
, ("void", var("ps_void"))
, ("voidRight", var("ps_voidRight"))
, ("voidLeft", var("ps_voidLeft"))
, ("flap", var("ps_flap"))
, ("functorFn", var("ps_functorFn"))
, ("functorArray", var("ps_functorArray")) ) ) )
res = module_code(res, filename="C:\\Users\\twshe\\Desktop\\mydb\\com-haskell\\testing\\datatypes\\.spago\\prelude\\v4.1.1\\src\\Data\\Functor.purs", name="datatypes.Data.Functor.pure")
| [
"[email protected]"
]
| |
5c21a1f652a75a295576e53ff349f00acfdecbdf | 9af29df29012ff521074aa1f3a6eacfe7f3eb6a9 | /449/main.py | 16040660dbe2ad5bb44c5084a592f09b3f83d7fe | []
| no_license | rh01/spring-go-code | e3a0cd1246683aa1bed8b29baa1c8b5ea87253c6 | 706ad785cbc4abb3566710c6e2904fe743c1cc6f | refs/heads/master | 2021-04-13T02:36:54.892843 | 2020-03-22T06:52:08 | 2020-03-22T06:52:08 | 249,129,346 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,301 | py | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
res = []
def encode(node):
if root is None:
res.append("#")
return
else:
res.append(str(node.val))
res.append()
encode(node.left)
encode(node.right)
encode(root)
return "_".join(res)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
ds = data.split("_")
l = len(ds)
def decode(level):
if level >= l:
return
if ds[level] == "#":
return None
node = TreeNode(ds[level])
node.left(level+1)
node.right(level+1)
return node
return decode(0)
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root)) | [
"[email protected]"
]
| |
1d6041b82892195a800cd204f526e36d4a3cbb2b | 23f8076467b0cc276a91a3ee0a6fbd6e30d3905d | /resource/trac-plugins/workfloweditorplugin/workfloweditor/workfloweditor_admin.py | 2a3d481fc0c5eefd49d67bd1a17ef4200bf1bb60 | []
| no_license | okamototk/kanonconductor | b6f7d04b2e5c5acd6fd4ee6f6d2f05a4b02bce45 | e6335c264e7a9a2e961e9a72db3660c2da1c24e3 | refs/heads/master | 2021-01-13T02:11:45.895523 | 2012-11-22T14:03:02 | 2012-11-22T14:03:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,149 | py | # -*- coding: utf-8 -*-
from trac.core import *
from trac.web.chrome import ITemplateProvider, add_stylesheet, add_script
from trac.admin import IAdminPanelProvider
from trac.web.api import ITemplateStreamFilter, IRequestHandler
from trac.web.chrome import Chrome
from api import LocaleUtil
class WorkflowEditorAdmin(Component):
implements(ITemplateProvider, ITemplateStreamFilter, IAdminPanelProvider)
# ITemplateProvider method
def get_htdocs_dirs(self):
from pkg_resources import resource_filename
return [('workfloweditor', resource_filename(__name__, 'htdocs'))]
# ITemplateProvider method
def get_templates_dirs(self):
from pkg_resources import resource_filename
return [resource_filename(__name__, 'templates')]
# ITemplateStreamFilter method
def filter_stream(self, req, method, filename, stream, data):
return stream
# IAdminPanelProvider method
def get_admin_panels(self, req):
if req.perm.has_permission('TRAC_ADMIN'):
# localization
locale = LocaleUtil().get_locale(req)
if (locale == 'ja'):
yield ('ticket', u'チケットシステム', 'workfloweditor', u'ワークフロー')
else:
yield ('ticket', 'Ticket System', 'workfloweditor', 'Workflow')
# IAdminPanelProvider method
def render_admin_panel(self, req, cat, page, path_info):
req.perm.assert_permission('TRAC_ADMIN')
add_script(req, 'workfloweditor/js/jquery.jqGrid.js')
add_script(req, 'workfloweditor/js/grid/jqModal.js')
add_script(req, 'workfloweditor/js/grid/jqDnR.js')
add_script(req, 'workfloweditor/js/grid/jquery.tablednd.js')
add_script(req, 'workfloweditor/js/ui/ui.core.js')
add_script(req, 'workfloweditor/js/ui/ui.tabs.pack.js')
add_script(req, 'workfloweditor/js/workfloweditor.js')
add_stylesheet(req, 'workfloweditor/css/grid.css')
add_stylesheet(req, 'workfloweditor/css/jqModal.css')
add_stylesheet(req, 'workfloweditor/css/ui.tabs.css')
add_stylesheet(req, 'workfloweditor/css/workfloweditor.css')
if req.method == 'POST':
self._update_config(req)
page_param = {}
self._create_page_param(req, page_param)
# localization
locale = LocaleUtil().get_locale(req)
if (locale == 'ja'):
add_script(req, 'workfloweditor/js/workfloweditor-locale-ja.js')
page_template = 'workfloweditor_admin_ja.html'
else:
page_template = 'workfloweditor_admin.html'
return page_template, {'template': page_param}
def _update_config(self, req):
# get ticket-workflow section
section = self.config._sections['ticket-workflow']
# delete old data
for (name, value) in section.options():
self.config.remove('ticket-workflow', name)
# parse input data
input_string = req.args['workflow_config']
config_list = input_string.split('\n')
for config_string in config_list:
if config_string.find('=') == -1:
continue
(name, value) = config_string.split('=', 1)
# set to memory
section.set(name.strip(), value.strip())
# save to file
self.config.save()
def _create_page_param(self, req, page_param):
# page_param['workflow_config']
# sort config for display
section = self.config._sections['ticket-workflow']
name_list = []
for (name, value) in section.options():
name_list.append(name)
name_list.sort()
# create config data for display
ret_val = ''
for name in name_list:
ret_val += name + '=' + section.get(name) + '\n'
page_param['workflow_config'] = ret_val
# page_param['workflow_default_config']
# localization
locale = LocaleUtil().get_locale(req)
if (locale == 'ja'):
init_file = 'trac_jp.ini'
else:
init_file = 'trac.ini'
# read defalut config
template = Chrome(self.env).load_template(init_file, 'text')
stream = template.generate()
default_config = stream.render('text')
page_param['workflow_default_config'] = default_config.decode('utf-8')
class WorkflowChangeHandler(Component):
implements(IRequestHandler)
# IRequestHandler method
def match_request(self, req):
match = False
if req.path_info == '/admin/ticket/workfloweditor/edit':
match = True
return match
# IRequestHandler method
def process_request(self, req):
req.send_response(200)
req.send_header('Content-Type', 'content=text/html; charset=UTF-8')
req.end_headers()
req.write("OK")
| [
"devnull@localhost"
]
| devnull@localhost |
5d1de83c438d5ee3ae02af5116e3e20221357b03 | e3365bc8fa7da2753c248c2b8a5c5e16aef84d9f | /indices/nnwatch.py | 2cbb90397d8c7b7424e2d50e7be5ae470684f730 | []
| no_license | psdh/WhatsintheVector | e8aabacc054a88b4cb25303548980af9a10c12a8 | a24168d068d9c69dc7a0fd13f606c080ae82e2a6 | refs/heads/master | 2021-01-25T10:34:22.651619 | 2015-09-23T11:54:06 | 2015-09-23T11:54:06 | 42,749,205 | 2 | 3 | null | 2015-09-23T11:54:07 | 2015-09-18T22:06:38 | Python | UTF-8 | Python | false | false | 2,913 | py | ii = [('BentJDO2.py', 8), ('EmerRN.py', 2), ('CookGHP3.py', 10), ('LyelCPG2.py', 3), ('MarrFDI.py', 19), ('RogePAV2.py', 11), ('CoolWHM2.py', 10), ('KembFFF.py', 4), ('GodwWSL2.py', 33), ('ChanWS.py', 5), ('RogePAV.py', 9), ('SadlMLP.py', 1), ('FerrSDO3.py', 16), ('WilbRLW.py', 36), ('WilbRLW4.py', 28), ('RennJIT.py', 18), ('AubePRP2.py', 15), ('CookGHP.py', 4), ('MartHSI2.py', 26), ('LeakWTI2.py', 3), ('UnitAI.py', 1), ('KembFJ1.py', 11), ('WilkJMC3.py', 7), ('WilbRLW5.py', 32), ('LeakWTI3.py', 3), ('PettTHE.py', 4), ('MarrFDI3.py', 1), ('TennAP.py', 12), ('PeckJNG.py', 2), ('KnowJMM.py', 1), ('BailJD2.py', 16), ('AubePRP.py', 17), ('ChalTPW2.py', 4), ('GellWPT.py', 1), ('AdamWEP.py', 8), ('FitzRNS3.py', 25), ('WilbRLW2.py', 39), ('ClarGE2.py', 39), ('GellWPT2.py', 1), ('WilkJMC2.py', 3), ('CarlTFR.py', 60), ('SeniNSP.py', 5), ('LyttELD.py', 12), ('CoopJBT2.py', 26), ('TalfTAC.py', 9), ('GrimSLE.py', 1), ('RoscTTI3.py', 13), ('AinsWRR3.py', 19), ('CookGHP2.py', 7), ('KiddJAE.py', 4), ('BailJD1.py', 32), ('RoscTTI2.py', 8), ('CoolWHM.py', 2), ('MarrFDI2.py', 3), ('CrokTPS.py', 12), ('ClarGE.py', 22), ('LandWPA.py', 3), ('BuckWGM.py', 4), ('IrviWVD.py', 20), ('LyelCPG.py', 1), ('GilmCRS.py', 39), ('DaltJMA.py', 2), ('WestJIT2.py', 6), ('DibdTRL2.py', 6), ('AinsWRR.py', 12), ('CrocDNL.py', 13), ('MedwTAI.py', 14), ('LandWPA2.py', 4), ('WadeJEB.py', 12), ('FerrSDO2.py', 7), ('TalfTIT.py', 8), ('NewmJLP.py', 2), ('GodwWLN.py', 19), ('CoopJBT.py', 11), ('KirbWPW2.py', 18), ('SoutRD2.py', 6), ('BackGNE.py', 28), ('LeakWTI4.py', 4), ('LeakWTI.py', 12), ('MedwTAI2.py', 14), ('BachARE.py', 10), ('SoutRD.py', 3), ('DickCSG.py', 4), ('BuckWGM2.py', 2), ('WheeJPT.py', 2), ('MereHHB3.py', 30), ('HowiWRL2.py', 30), ('BailJD3.py', 15), ('MereHHB.py', 23), ('WilkJMC.py', 4), ('HogaGMM.py', 4), ('MartHRW.py', 54), ('MackCNH.py', 3), ('WestJIT.py', 4), ('BabbCEM.py', 27), ('FitzRNS4.py', 60), ('CoolWHM3.py', 1), ('DequTKM.py', 25), ('FitzRNS.py', 36), ('BentJRP.py', 5), ('EdgeMHT.py', 16), ('BowrJMM.py', 10), ('LyttELD3.py', 5), ('HallFAC.py', 2), ('FerrSDO.py', 6), ('RoscTTI.py', 8), ('ThomGLG.py', 2), ('StorJCC.py', 10), ('KembFJ2.py', 11), ('LewiMJW.py', 17), ('BabbCRD.py', 2), ('MackCNH2.py', 2), ('BellCHM.py', 11), ('JacoWHI2.py', 56), ('SomeMMH.py', 1), ('HaliTBC.py', 3), ('WilbRLW3.py', 43), ('AinsWRR2.py', 17), ('MereHHB2.py', 26), ('BrewDTO.py', 4), ('JacoWHI.py', 9), ('ClarGE3.py', 23), ('RogeSIP.py', 15), ('MartHRW2.py', 40), ('DibdTRL.py', 9), ('FitzRNS2.py', 66), ('HogaGMM2.py', 1), ('MartHSI.py', 46), ('EvarJSP.py', 5), ('DwigTHH.py', 3), ('NortSTC.py', 20), ('SadlMLP2.py', 1), ('BowrJMM2.py', 16), ('LyelCPG3.py', 1), ('BowrJMM3.py', 6), ('BeckWRE.py', 1), ('TaylIF.py', 12), ('WordWYR.py', 12), ('DibdTBR.py', 2), ('ChalTPW.py', 4), ('ThomWEC.py', 5), ('KeigTSS.py', 12), ('KirbWPW.py', 9), ('WaylFEP.py', 6), ('BentJDO.py', 4), ('ClarGE4.py', 25), ('HowiWRL.py', 15)] | [
"[email protected]"
]
| |
e83b9ea8504433bfed386da9ae633fcd91098dd9 | 73c01a3f052f8ef63890ec3c2e28403ad41e9a71 | /td/migrations/0004_auto_20170207_1445.py | 47bae81cbf8dd662e87669a0574724e21c14fb19 | []
| no_license | Jokey90/aho | 4c007c65c819efb726a732a8f36067c5a0226100 | 8bcd41e9ef7d40f07499429f385d4fec590636f6 | refs/heads/master | 2020-03-21T22:28:36.395996 | 2018-06-29T09:25:05 | 2018-06-29T09:25:05 | 139,128,834 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,958 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2017-02-07 14:45
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('main', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('td', '0003_proxytracking'),
]
operations = [
migrations.CreateModel(
name='Item',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('type', models.CharField(choices=[('pts', 'ПТС'), ('sts', 'СТС'), ('diag_card', 'Диагностическая карта'), ('fuel_card', 'Топливная карта'), ('corp_card', 'Корпоративная карта'), ('osago', 'Полис ОСАГО'), ('kasko', 'Полис КАСКО'), ('key-car', 'Ключ от автомобиля'), ('key-alarm', 'Ключ от сигнализации'), ('key-card', 'Ключ-карта'), ('key-parking', 'Пропуск на парковку')], max_length=50, verbose_name='Тип ключа')),
('number', models.CharField(blank=True, default='', max_length=50, null=True, verbose_name='Номер')),
('pin', models.CharField(blank=True, default='', max_length=50, null=True, verbose_name='Пин код')),
('start_date', models.DateField(blank=True, null=True, verbose_name='Дата начала')),
('end_date', models.DateField(blank=True, null=True, verbose_name='Дата окончания')),
('company', models.CharField(blank=True, default='', max_length=50, null=True, verbose_name='Компания')),
('comment', models.CharField(blank=True, default='', max_length=255, null=True, verbose_name='Комментарий')),
('active', models.BooleanField(default=True, verbose_name='Активен')),
('scan', models.FileField(blank=True, null=True, upload_to='scans/documents/', verbose_name='Скан')),
],
options={
'verbose_name': 'Атрибут',
'verbose_name_plural': 'Атрибуты',
},
),
migrations.CreateModel(
name='ItemTracking',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date', models.DateField(verbose_name='Дата передачи')),
('add_date', models.DateTimeField(auto_now_add=True)),
('added_by', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
('item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='td.Proxy', verbose_name='Доверенность')),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='main.Employee', verbose_name='Кому выдана')),
],
options={
'verbose_name': 'Выдача документов/ключей',
'verbose_name_plural': 'Выдачи документов/ключей',
},
),
migrations.RemoveField(
model_name='key',
name='car',
),
migrations.RemoveField(
model_name='key',
name='owner',
),
migrations.RemoveField(
model_name='car',
name='corp_card_number',
),
migrations.RemoveField(
model_name='car',
name='corp_card_pin',
),
migrations.RemoveField(
model_name='car',
name='corp_card_place',
),
migrations.RemoveField(
model_name='car',
name='corp_card_scan',
),
migrations.RemoveField(
model_name='car',
name='diag_card_date',
),
migrations.RemoveField(
model_name='car',
name='diag_card_number',
),
migrations.RemoveField(
model_name='car',
name='diag_card_place',
),
migrations.RemoveField(
model_name='car',
name='diag_card_scan',
),
migrations.RemoveField(
model_name='car',
name='fuel_card_date',
),
migrations.RemoveField(
model_name='car',
name='fuel_card_number',
),
migrations.RemoveField(
model_name='car',
name='fuel_card_pin',
),
migrations.RemoveField(
model_name='car',
name='fuel_card_place',
),
migrations.RemoveField(
model_name='car',
name='fuel_card_scan',
),
migrations.RemoveField(
model_name='car',
name='kasko_company',
),
migrations.RemoveField(
model_name='car',
name='kasko_date',
),
migrations.RemoveField(
model_name='car',
name='kasko_number',
),
migrations.RemoveField(
model_name='car',
name='kasko_place',
),
migrations.RemoveField(
model_name='car',
name='kasko_scan',
),
migrations.RemoveField(
model_name='car',
name='osago_company',
),
migrations.RemoveField(
model_name='car',
name='osago_date',
),
migrations.RemoveField(
model_name='car',
name='osago_number',
),
migrations.RemoveField(
model_name='car',
name='osago_place',
),
migrations.RemoveField(
model_name='car',
name='osago_scan',
),
migrations.RemoveField(
model_name='car',
name='pts_number',
),
migrations.RemoveField(
model_name='car',
name='pts_place',
),
migrations.RemoveField(
model_name='car',
name='pts_scan',
),
migrations.RemoveField(
model_name='car',
name='sts_number',
),
migrations.RemoveField(
model_name='car',
name='sts_place',
),
migrations.RemoveField(
model_name='car',
name='sts_scan',
),
migrations.DeleteModel(
name='Key',
),
migrations.AddField(
model_name='item',
name='car',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='td.Car', verbose_name='Автомобиль'),
),
]
| [
"[email protected]"
]
| |
efc9bfc1f5bb128ff465c9c98e06e75c9ccd4d0f | 7c3116ca951c1c989fcc6cd673993ce6b1d4be5a | /modules/iconcache_connector.py | 626ff1385dbd7b7fefbfaf8cae8c755cde714200 | [
"Apache-2.0"
]
| permissive | Kimwonkyung/carpe | c8c619c29350d6edc464dbd9ba85aa3b7f847b8a | 58a8bf7a7fc86a07867890c2ce15c7271bbe8e78 | refs/heads/master | 2022-12-15T13:51:47.678875 | 2020-09-11T05:25:43 | 2020-09-11T05:25:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,068 | py | # -*- coding: utf-8 -*-
import os
from modules import manager
from modules import interface
from modules import logger
from modules.windows_iconcache import IconCacheParser as ic
from dfvfs.lib import definitions as dfvfs_definitions
class IconCacheConnector(interface.ModuleConnector):
NAME = 'iconcache_connector'
DESCRIPTION = 'Module for iconcache_connector'
_plugin_classes = {}
def __init__(self):
super(IconCacheConnector, self).__init__()
def Connect(self, configuration, source_path_spec, knowledge_base):
print('[MODULE]: IconCacheConnector Connect')
this_file_path = os.path.dirname(os.path.abspath(__file__)) + os.sep + 'schema' + os.sep
# 모든 yaml 파일 리스트
yaml_list = [this_file_path + 'lv1_os_win_icon_cache.yaml']
# 모든 테이블 리스트
table_list = ['lv1_os_win_icon_cache']
# 모든 테이블 생성
if not self.check_table_from_yaml(configuration, yaml_list, table_list):
return False
try:
if source_path_spec.parent.type_indicator != dfvfs_definitions.TYPE_INDICATOR_TSK_PARTITION:
par_id = configuration.partition_list['p1']
else:
par_id = configuration.partition_list[getattr(source_path_spec.parent, 'location', None)[1:]]
if par_id == None:
return False
owner = ''
query = f"SELECT name, parent_path, extension FROM file_info WHERE par_id='{par_id}' " \
f"and extension = 'db' and size > 24 and name regexp 'iconcache_[0-9]' and ("
for user_accounts in knowledge_base._user_accounts.values():
for hostname in user_accounts.values():
if hostname.identifier.find('S-1-5-21') == -1:
continue
query += f"parent_path like '%{hostname.username}%' or "
query = query[:-4] + ");"
#print(query)
iconcache_files = configuration.cursor.execute_query_mul(query)
#print(f'iconcache_files: {len(iconcache_files)}')
if len(iconcache_files) == 0:
return False
insert_iconcache_info = []
for iconcache in iconcache_files:
iconcache_path = iconcache[1][iconcache[1].find('/'):] + '/' + iconcache[0] # document full path
fileExt = iconcache[2]
fileName = iconcache[0]
owner = iconcache[1][iconcache[1].find('/'):].split('/')[2]
# Windows.old 폴더 체크
if 'Windows.old' in iconcache_path:
fileExt = iconcache[2]
fileName = iconcache[0]
owner = iconcache[1][iconcache[1].find('/'):].split('/')[3] + "(Windows.old)"
output_path = configuration.root_tmp_path + os.sep + configuration.case_id + os.sep + configuration.evidence_id + os.sep + par_id
img_output_path = output_path + os.sep + "iconcache_img" + os.sep + owner + os.sep + fileName[:-3]
self.ExtractTargetFileToPath(
source_path_spec=source_path_spec,
configuration=configuration,
file_path=iconcache_path,
output_path=output_path)
fn = output_path + os.path.sep + fileName
app_path = os.path.abspath(os.path.dirname(__file__)) + os.path.sep + "windows_iconcache"
results = ic.main(fn, app_path, img_output_path)
if not results:
os.remove(output_path + os.sep + fileName)
continue
for i in range(len(results["ThumbsData"])):
if i == 0:
continue
result = results["ThumbsData"][i]
filename = result[0]
filesize = result[1]
imagetype = result[2]
data = result[3]
sha1 = result[4]
tmp = []
tmp.append(par_id)
tmp.append(configuration.case_id)
tmp.append(configuration.evidence_id)
tmp.append(owner)
tmp.append(filename)
tmp.append(filesize)
tmp.append(imagetype)
tmp.append(data)
tmp.append(sha1)
insert_iconcache_info.append(tuple(tmp))
os.remove(output_path + os.sep + fileName)
# IconCache
print('[MODULE]: IconCache')
query = "Insert into lv1_os_win_icon_cache values (%s, %s, %s, %s, %s, %s, %s, %s, %s);"
configuration.cursor.bulk_execute(query, insert_iconcache_info)
print('[MODULE]: IconCache Complete')
except Exception as e:
print("IconCache Connector Error", e)
manager.ModulesManager.RegisterModule(IconCacheConnector)
| [
"[email protected]"
]
| |
9bc346a7ae74d0660986cc88c38cd2578d71e903 | 741333ced9ea1b326997dc031e5de27529bad04a | /glue_vispy_viewers/extern/vispy/testing/__init__.py | d8a7266c45d1e6c776b6e2397a6158aff13fb7d4 | [
"BSD-3-Clause",
"BSD-2-Clause"
]
| permissive | jzuhone/glue-vispy-viewers | f1b7f506d3263c4b0c2f4032d4940b931b2c1ada | d940705f4ba95f8d7a9a74d37fb68c71080b490a | refs/heads/master | 2020-06-20T19:10:02.866527 | 2019-06-24T11:40:39 | 2019-06-24T11:40:39 | 197,217,964 | 0 | 0 | BSD-2-Clause | 2019-07-16T15:14:53 | 2019-07-16T15:14:52 | null | UTF-8 | Python | false | false | 2,415 | py | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
Testing
=======
This module provides functions useful for running tests in vispy.
Tests can be run in a few ways:
* From Python, you can import ``vispy`` and do ``vispy.test()``.
* From the source root, you can do ``make test`` which wraps to
a call to ``python make test``.
There are various diffrent testing "modes", including:
* "full": run all tests.
* any backend name (e.g., "glfw"): run application/GL tests using a
specific backend.
* "nobackend": run tests that do not require a backend.
* "examples": run repo examples to check for errors and warnings.
* "flake": check style errors.
Examples get automatically tested unless they have a special comment toward
the top ``# vispy: testskip``. Examples that should be tested should be
formatted so that 1) a ``Canvas`` class is defined, or a ``canvas`` class
is instantiated; and 2) the ``app.run()`` call is protected by a check
if ``__name__ == "__main__"``. This makes it so that the event loop is not
started when running examples in the test suite -- the test suite instead
manually updates the canvas (using ``app.process_events()``) for under one
second to ensure that things like timer events are processed.
For examples on how to test various bits of functionality (e.g., application
functionality, or drawing things with OpenGL), it's best to look at existing
examples in the test suite.
The code base gets automatically tested by Travis-CI (Linux) and AppVeyor
(Windows) on Python 2.6, 2.7, 3.4. There are multiple testing modes that
use e.g. full dependencies, minimal dependencies, etc. See ``.travis.yml``
to determine what automatic tests are run.
"""
from ._testing import (SkipTest, requires_application, requires_ipython, # noqa
requires_img_lib, # noqa
has_backend, requires_pyopengl, # noqa
requires_scipy, has_matplotlib, # noqa
save_testing_image, TestingCanvas, has_pyopengl, # noqa
run_tests_if_main,
assert_is, assert_in, assert_not_in, assert_equal,
assert_not_equal, assert_raises, assert_true, # noqa
raises) # noqa
from ._runners import test # noqa
| [
"[email protected]"
]
| |
84d070f945255f5301c9b2a7602b9f80389ce53e | 45f93a9d47204d76b8bf25a71dfb79403e75c33c | /next-greater-element-i.py | 36f563052966cec348db92db4c5eb4254417f009 | []
| no_license | tahmid-tanzim/problem-solving | 0173bce1973ac3e95441a76c10324c0e1b0a57c3 | 6ddb51de6772130f209474e76f39ca2938f444f0 | refs/heads/master | 2023-06-25T02:18:03.690263 | 2023-06-20T06:58:46 | 2023-06-20T06:58:46 | 137,173,850 | 4 | 1 | null | 2022-03-30T08:28:41 | 2018-06-13T06:44:25 | Python | UTF-8 | Python | false | false | 1,340 | py | #!/usr/bin/python3
# https://leetcode.com/problems/next-greater-element-i/
from typing import List
# Time O(n)
# Space O(1)
def nextGreaterElement(nums1: List[int], nums2: List[int]) -> List[int]:
nums1Index = {}
for i, n1 in enumerate(nums1):
nums1Index[n1] = i
nums1[i] = -1
n = len(nums2)
stack = []
for i in range(n):
while len(stack) > 0 and nums2[i] > stack[-1]:
value = stack.pop()
index = nums1Index[value]
nums1[index] = nums2[i]
if nums2[i] in nums1Index:
stack.append(nums2[i])
return nums1
if __name__ == '__main__':
inputs = (
{
"nums1": [4, 1, 2],
"nums2": [1, 3, 4, 2],
"expected": [-1, 3, -1]
},
{
"nums1": [2, 4],
"nums2": [1, 2, 3, 4],
"expected": [3, -1]
},
)
test_passed = 0
for idx, val in enumerate(inputs):
output = nextGreaterElement(val["nums1"], val["nums2"])
if output == val['expected']:
print(f"{idx}. CORRECT Answer\nOutput: {output}\nExpected: {val['expected']}\n")
test_passed += 1
else:
print(f"{idx}. WRONG Answer\nOutput:{output}\nExpected:{val['expected']}\n")
print(f"Passed: {test_passed:3}/{idx + 1}\n")
| [
"[email protected]"
]
| |
c1e42865ba3ad91fb08d55eeef704a910a0e7138 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02771/s406306655.py | 4ada1942e5bf7fc9e5cd7254eff15a8aba906b50 | []
| no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 170 | py |
A, B, C = map(int,input().split())
if A == B and B != C:
print('Yes')
elif C == B and C != A:
print('Yes')
elif A == C and C != B:
print('Yes')
else:
print('No') | [
"[email protected]"
]
| |
6f101ccbdad195f757a4123805328db4ef6ba9c5 | ef5f98cdaca58bc9c1ba1a94a1ccf7bebc3f1260 | /ir_actions_act_url.py | d2968068725bcdde7011beb4ddd33709c85f326e | [
"MIT"
]
| permissive | tonygalmiche/is_plastigray | 512ad911b3118c6aa2aab49f64ad7871fb80f195 | 774feea510fc0854776016dbbbc7472ebd1248c5 | refs/heads/master | 2023-07-25T21:49:56.284434 | 2023-07-18T13:15:28 | 2023-07-18T13:15:28 | 24,811,999 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,794 | py | # -*- coding: utf-8 -*-
from openerp import models, fields, api, _
from openerp.http import request
class ir_actions_act_url(models.Model):
_inherit = 'ir.actions.act_url'
# def get_soc(self, cr, uid):
# user = self.pool['res.users'].browse(cr, uid, [uid])[0]
# soc = user.company_id.partner_id.is_code
# return soc
def get_company(self, cr, uid):
user = self.pool['res.users'].browse(cr, uid, [uid])[0]
company = user.company_id
return company
def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'):
if not context: context = {}
results = super(ir_actions_act_url, self).read(cr, uid, ids, fields=fields, context=context, load=load)
if load=='_classic_read' and len(ids) == 1:
if results[0]['name']==u'is_url_parc_presses_action':
user = self.pool['res.users'].browse(cr, uid, [uid], context=context)[0]
soc = user.company_id.is_code_societe
ip = request.httprequest.environ['REMOTE_ADDR']
url='http://raspberry-theia/atelier.php?atelier=inj&soc='+str(soc)+'&uid='+str(uid)
results[0].update({'url': url})
if results[0]['name']==u'is_url_parc_presses_new_action':
user = self.pool['res.users'].browse(cr, uid, [uid], context=context)[0]
soc = user.company_id.is_code_societe
ip = request.httprequest.environ['REMOTE_ADDR']
url='http://raspberry-theia4/atelier.php?atelier=inj&soc='+str(soc)+'&uid='+str(uid)
results[0].update({'url': url})
if results[0]['name']==u'is_url_parc_assemblage_action':
user = self.pool['res.users'].browse(cr, uid, [uid], context=context)[0]
soc = user.company_id.is_code_societe
ip = request.httprequest.environ['REMOTE_ADDR']
url='http://raspberry-theia4/atelier.php?atelier=ass&soc='+str(soc)+'&uid='+str(uid)
results[0].update({'url': url})
if results[0]['name']==u'is_url_indicateur_rebuts_action':
user = self.pool['res.users'].browse(cr, uid, [uid], context=context)[0]
soc = user.company_id.is_code_societe
ip = request.httprequest.environ['REMOTE_ADDR']
url='http://odoo/odoo-theia/rebuts.php?soc='+str(soc)+'&uid='+str(uid)
results[0].update({'url': url})
if results[0]['name']==u'is_url_indicateur_trs_action':
user = self.pool['res.users'].browse(cr, uid, [uid], context=context)[0]
soc = user.company_id.is_code_societe
ip = request.httprequest.environ['REMOTE_ADDR']
url='http://odoo/odoo-theia/trs.php?soc='+str(soc)+'&uid='+str(uid)
results[0].update({'url': url})
#if results[0]['name']==u'is_url_indicateur_trs_new_action':
# user = self.pool['res.users'].browse(cr, uid, [uid], context=context)[0]
# soc = user.company_id.is_code_societe
# ip = request.httprequest.environ['REMOTE_ADDR']
# url='http://odoo/odoo-theia/trs-new.php?soc='+str(soc)+'&uid='+str(uid)
# results[0].update({'url': url})
if results[0]['name']==u'is_url_planning_action':
ip = request.httprequest.environ['REMOTE_ADDR']
company=self.get_company(cr,uid)
soc=company.partner_id.is_code
url=company.is_url_intranet_odoo or ''
url=url+'/odoo-erp/planning/?soc='+str(soc)+'&uid='+str(uid)
results[0].update({'url': url})
if results[0]['name']==u'is_url_analyse_cbn_action':
ip = request.httprequest.environ['REMOTE_ADDR']
company=self.get_company(cr,uid)
soc=company.partner_id.is_code
url=company.is_url_intranet_odoo or ''
url=url+'/odoo-erp/cbn/Sugestion_CBN.php?Soc='+str(soc)+'&product_id=&uid='+str(uid)
results[0].update({'url': url})
if results[0]['name']==u'is_url_pic_3_ans_action':
ip = request.httprequest.environ['REMOTE_ADDR']
company=self.get_company(cr,uid)
soc=company.partner_id.is_code
url=company.is_url_intranet_odoo or ''
url=url+'/odoo-erp/analyses/pic-3-ans.php?Soc='+str(soc)+'&uid='+str(uid)
results[0].update({'url': url})
if results[0]['name']==u'is_url_pic_3_mois':
ip = request.httprequest.environ['REMOTE_ADDR']
company=self.get_company(cr,uid)
soc=company.partner_id.is_code
url=company.is_url_intranet_odoo or ''
url=url+'/odoo-erp/analyses/pic-3-mois.php?Soc='+str(soc)+'&uid='+str(uid)
results[0].update({'url': url})
if results[0]['name']==u'is_url_theia':
company=self.get_company(cr,uid)
soc=company.partner_id.is_code
url=company.is_url_odoo_theia or ''
#url='http://odoo-cpi1'
#if soc=='3':
# url='http://odoo-theia3'
#if soc=='4':
# url='http://odoo-theia4'
results[0].update({'url': url})
if results[0]['name']==u'is_url_theia_suivi_prod':
company=self.get_company(cr,uid)
soc=company.partner_id.is_code
url=company.is_url_intranet_theia or ''
url=url+'/atelier.php?soc='+soc
results[0].update({'url': url})
#if results[0]['name']==u'is_url_theia_rebuts':
# company=self.get_company(cr,uid)
# soc=company.partner_id.is_code
# url=company.is_url_intranet_odoo or ''
# url=url+'/odoo-cpi/rebuts.php?soc='+soc
# results[0].update({'url': url})
#if results[0]['name']==u'is_url_theia_trs':
# company=self.get_company(cr,uid)
# soc=company.partner_id.is_code
# url=company.is_url_intranet_odoo or ''
# url=url+'/odoo-cpi/trs.php?soc='+soc
# results[0].update({'url': url})
return results
| [
"[email protected]"
]
| |
c6431345804aab5097e1f006eec9f898f72ba44b | bc8509d57a162fb685da06a98c67dc8130d96316 | /src/slim/nets/cyclegan_test.py | 593af0862b804778ed17a102fa23ecd5566d776a | [
"Apache-2.0"
]
| permissive | Ptolemy-DL/Ptolemy | 2065e2d157d641010567062410bee4608691d059 | f72a531286d17c69e0e2e84d0ad8a5b0587e2e08 | refs/heads/master | 2023-05-29T08:58:18.328258 | 2021-06-15T09:28:16 | 2021-06-15T09:28:16 | 284,590,756 | 115 | 5 | NOASSERTION | 2020-10-24T04:18:51 | 2020-08-03T03:06:35 | Python | UTF-8 | Python | false | false | 4,398 | py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for tensorflow.contrib.slim.nets.cyclegan."""
from __future__ import absolute_import, division, print_function
import tensorflow as tf
from nets import cyclegan
# TODO(joelshor): Add a test to check generator endpoints.
class CycleganTest(tf.test.TestCase):
def test_generator_inference(self):
"""Check one inference step."""
img_batch = tf.zeros([2, 32, 32, 3])
model_output, _ = cyclegan.cyclegan_generator_resnet(img_batch)
with self.test_session() as sess:
sess.run(tf.global_variables_initializer())
sess.run(model_output)
def _test_generator_graph_helper(self, shape):
"""Check that generator can take small and non-square inputs."""
output_imgs, _ = cyclegan.cyclegan_generator_resnet(tf.ones(shape))
self.assertAllEqual(shape, output_imgs.shape.as_list())
def test_generator_graph_small(self):
self._test_generator_graph_helper([4, 32, 32, 3])
def test_generator_graph_medium(self):
self._test_generator_graph_helper([3, 128, 128, 3])
def test_generator_graph_nonsquare(self):
self._test_generator_graph_helper([2, 80, 400, 3])
def test_generator_unknown_batch_dim(self):
"""Check that generator can take unknown batch dimension inputs."""
img = tf.placeholder(tf.float32, shape=[None, 32, None, 3])
output_imgs, _ = cyclegan.cyclegan_generator_resnet(img)
self.assertAllEqual([None, 32, None, 3], output_imgs.shape.as_list())
def _input_and_output_same_shape_helper(self, kernel_size):
img_batch = tf.placeholder(tf.float32, shape=[None, 32, 32, 3])
output_img_batch, _ = cyclegan.cyclegan_generator_resnet(
img_batch, kernel_size=kernel_size)
self.assertAllEqual(img_batch.shape.as_list(),
output_img_batch.shape.as_list())
def input_and_output_same_shape_kernel3(self):
self._input_and_output_same_shape_helper(3)
def input_and_output_same_shape_kernel4(self):
self._input_and_output_same_shape_helper(4)
def input_and_output_same_shape_kernel5(self):
self._input_and_output_same_shape_helper(5)
def input_and_output_same_shape_kernel6(self):
self._input_and_output_same_shape_helper(6)
def _error_if_height_not_multiple_of_four_helper(self, height):
self.assertRaisesRegexp(
ValueError,
'The input height must be a multiple of 4.',
cyclegan.cyclegan_generator_resnet,
tf.placeholder(tf.float32, shape=[None, height, 32, 3]))
def test_error_if_height_not_multiple_of_four_height29(self):
self._error_if_height_not_multiple_of_four_helper(29)
def test_error_if_height_not_multiple_of_four_height30(self):
self._error_if_height_not_multiple_of_four_helper(30)
def test_error_if_height_not_multiple_of_four_height31(self):
self._error_if_height_not_multiple_of_four_helper(31)
def _error_if_width_not_multiple_of_four_helper(self, width):
self.assertRaisesRegexp(
ValueError,
'The input width must be a multiple of 4.',
cyclegan.cyclegan_generator_resnet,
tf.placeholder(tf.float32, shape=[None, 32, width, 3]))
def test_error_if_width_not_multiple_of_four_width29(self):
self._error_if_width_not_multiple_of_four_helper(29)
def test_error_if_width_not_multiple_of_four_width30(self):
self._error_if_width_not_multiple_of_four_helper(30)
def test_error_if_width_not_multiple_of_four_width31(self):
self._error_if_width_not_multiple_of_four_helper(31)
if __name__ == '__main__':
tf.test.main()
| [
"[email protected]"
]
| |
7f02a5306eb52284c806b3ab7df0859ec1c2c51c | 8e69eee9b474587925e22413717eb82e4b024360 | /v2.5.7/toontown/speedchat/TTSCSellbotInvasionMenu.py | 8118a9bd04309cc70834ec5261fd1357faa3fcfd | [
"MIT"
]
| permissive | TTOFFLINE-LEAK/ttoffline | afaef613c36dc3b70514ccee7030ba73c3b5045b | bb0e91704a755d34983e94288d50288e46b68380 | refs/heads/master | 2020-06-12T15:41:59.411795 | 2020-04-17T08:22:55 | 2020-04-17T08:22:55 | 194,348,185 | 5 | 4 | null | null | null | null | UTF-8 | Python | false | false | 1,641 | py | from otp.otpbase import PythonUtil
from otp.speedchat.SCMenu import SCMenu
from otp.speedchat.SCMenuHolder import SCMenuHolder
from otp.speedchat.SCStaticTextTerminal import SCStaticTextTerminal
from toontown.speedchat.TTSCIndexedTerminal import TTSCIndexedTerminal
from otp.otpbase import OTPLocalizer
SellbotInvasionMenu = [
(
OTPLocalizer.SellbotInvasionMenuSections[0], range(30400, 30404))]
class TTSCSellbotInvasionMenu(SCMenu):
def __init__(self):
SCMenu.__init__(self)
self.__messagesChanged()
def destroy(self):
SCMenu.destroy(self)
def clearMenu(self):
SCMenu.clearMenu(self)
def __messagesChanged(self):
self.clearMenu()
try:
lt = base.localAvatar
except:
return
for section in SellbotInvasionMenu:
if section[0] == -1:
for phrase in section[1]:
if phrase not in OTPLocalizer.SpeedChatStaticText:
print 'warning: tried to link Winter phrase %s which does not seem to exist' % phrase
break
self.append(SCStaticTextTerminal(phrase))
else:
menu = SCMenu()
for phrase in section[1]:
if phrase not in OTPLocalizer.SpeedChatStaticText:
print 'warning: tried to link Halloween phrase %s which does not seem to exist' % phrase
break
menu.append(SCStaticTextTerminal(phrase))
menuName = str(section[0])
self.append(SCMenuHolder(menuName, menu)) | [
"[email protected]"
]
| |
1d602b92c8fee5c4b37ab8b37affd34b151a01b7 | 9a343c495459e79dc408a102730bcaeac7fa8886 | /CMDB_SYSTEM/autoclient/src/plugins/board.py | 3da6198756f35073241b05ffde6ee417b3325017 | [
"MIT"
]
| permissive | MMingLeung/Python_Study | 62d3ae92bf6760de0804aa5792f53fb3799486a2 | 4ff1d02d2b6dd54e96f7179fa000548936b691e7 | refs/heads/master | 2022-12-27T12:53:05.186800 | 2018-03-07T04:34:36 | 2018-03-07T04:34:36 | 92,124,981 | 3 | 1 | MIT | 2021-06-10T18:35:33 | 2017-05-23T03:28:52 | JavaScript | UTF-8 | Python | false | false | 1,639 | py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
from lib.conf.config import settings
class Board(object):
def __init__(self):
pass
@classmethod
def initial(cls):
return cls()
def process(self, command_func, debug):
if debug:
output = open(os.path.join(settings.BASE_DIR, 'debug_files/board.out'), 'r', encoding='utf-8').read()
else:
output = command_func("sudo dmidecode -t1")
return self.parse(output)
'''
SMBIOS 2.7 present.
Handle 0x0001, DMI type 1, 27 bytes
System Information
Manufacturer: Parallels Software International Inc.
Product Name: Parallels Virtual Platform
Version: None
Serial Number: Parallels-1A 1B CB 3B 64 66 4B 13 86 B0 86 FF 7E 2B 20 30
UUID: 3BCB1B1A-6664-134B-86B0-86FF7E2B2030
Wake-up Type: Power Switch
SKU Number: Undefined
Family: Parallels VM
'''
def parse(self, content):
result = {}
key_map = {
'Manufacturer': 'manufacturer',
'Product Name': 'model',
'Serial Number': 'sn',
}
#循环遍历切分的信息
for item in content.split('\n'):
#根据":"切分
row_data = item.strip().split(':')
#如果列表长度是2
if len(row_data) == 2:
#所需信息的key与遍历的数据匹配
if row_data[0] in key_map:
#赋值
result[key_map[row_data[0]]] = row_data[1].strip() if row_data[1] else row_data[1]
return result
| [
"[email protected]"
]
| |
d54177f734b5221d7c6a4fe45641dab66c10a92b | 7bd5ca970fbbe4a3ed0c7dadcf43ba8681a737f3 | /codeforces/cf251-275/cf255/b2.py | ce0f660a579831dc53f02607d6e65c334c0b0e0d | []
| no_license | roiti46/Contest | c0c35478cd80f675965d10b1a371e44084f9b6ee | c4b850d76796c5388d2e0d2234f90dc8acfaadfa | refs/heads/master | 2021-01-17T13:23:30.551754 | 2017-12-10T13:06:42 | 2017-12-10T13:06:42 | 27,001,893 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 317 | py | # -*- coding: utf-8 -*-
import sys,copy,math,heapq,itertools as it,fractions,re,bisect,collections as coll
s = raw_input()
k = int(raw_input())
w = map(int, raw_input().split())
c = chr(w.index(max(w)) + ord("a"))
s += c * k
ans = 0
for i, si in enumerate(s):
ans += w[ord(s[i]) - ord("a")] * (i + 1)
print ans
| [
"[email protected]"
]
| |
7e8ffd682bae9bbaff7485ca16af4ec980de96df | 89a90707983bdd1ae253f7c59cd4b7543c9eda7e | /programming_python/Gui/Tools/queuetest-gui.py | af7ab12cc6f3f174c8f6247680d767335d9e5fb5 | []
| no_license | timothyshull/python_reference_code | 692a7c29608cadfd46a6cc409a000023e95b9458 | f3e2205dd070fd3210316f5f470d371950945028 | refs/heads/master | 2021-01-22T20:44:07.018811 | 2017-03-17T19:17:22 | 2017-03-17T19:17:22 | 85,346,735 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,094 | py | # GUI that displays data produced and queued by worker threads
import _thread
import queue
import time
dataQueue = queue.Queue() # infinite size
def producer(id):
for i in range(5):
time.sleep(0.1)
print('put')
dataQueue.put('[producer id=%d, count=%d]' % (id, i))
def consumer(root):
try:
print('get')
data = dataQueue.get(block=False)
except queue.Empty:
pass
else:
root.insert('end', 'consumer got => %s\n' % str(data))
root.see('end')
root.after(250, lambda: consumer(root)) # 4 times per sec
def makethreads():
for i in range(4):
_thread.start_new_thread(producer, (i,))
if __name__ == '__main__':
# main GUI thread: spawn batch of worker threads on each mouse click
from tkinter.scrolledtext import ScrolledText
root = ScrolledText()
root.pack()
root.bind('<Button-1>', lambda event: makethreads())
consumer(root) # start queue check loop in main thread
root.mainloop() # pop-up window, enter tk event loop
| [
"[email protected]"
]
| |
459925a74c6e9585cf8d4b23622b67d49986ab33 | 51aa2894c317f60726fe9a778999eb7851b6be3e | /140_gui/pyqt_pyside/examples/Advanced_Python_Scripting/008_Class_widget/006_Tree_widget_QTreeWidget.py | 7c346ad7464b09da172de7525381e20a3b937bde | []
| no_license | pranaymate/Python_Topics | dd7b288ab0f5bbee71d57080179d6481aae17304 | 33d29e0a5bf4cde104f9c7f0693cf9897f3f2101 | refs/heads/master | 2022-04-25T19:04:31.337737 | 2020-04-26T00:36:03 | 2020-04-26T00:36:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,436 | py | from PySide.QtGui import *
from PySide.QtCore import *
import os
path = os.path.dirname(os.path.dirname(__file__))
class simpleWindow(QWidget):
def __init__(self):
super(simpleWindow, self).__init__()
ly = QHBoxLayout()
self.setLayout(ly)
self.tree = QTreeWidget()
ly.addWidget(self.tree)
self.tree.header().hide()
# connect
self.tree.itemChanged.connect(self.action) # signal itemChanged vozvrachaet item i kolonky v kotoroj proizoshlo izmenenie
# start
self.resize(500,400)
self.updateTree()
def updateTree(self):
self.tree.blockSignals(True) # eto komanda blokiryet vse signalu, signalu ne bydyt emititsja shto bu ne slychilos'
self.fillTree()
self.tree.blockSignals(False) # eto komanda rablokiryet blokirovky signalov
def fillTree(self, parent=None, root=None):
if not parent:
parent = self.tree.invisibleRootItem()
if not root:
root = path
for f in os.listdir(root):
if f[0] in ['.', '_']: continue # iskluchaet papki s tochkoj i podchorkivaniem v peredi v nazvanii
item = QTreeWidgetItem()
item.setText(0, f) # TreeWidget podderzivaet kolonki, i mu dolznu ykazat' v kakyjy kolonky mu kladjom etot tekst.
parent.addChild(item)
fullpath = os.path.join(root, f)
if os.path.isdir(fullpath):
self.fillTree(item, fullpath)
item.setExpanded(1)
else:
item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable)
item.setData(0, Qt.UserRole, {'path': os.path.normpath(fullpath)}) # pozvoljaet polozit v jachejky lybue dannue.
# Kontejner kyda mu mozem vremmeno polozit te dannue, kotorue nam nyzno
# takze sychestvyet klass QVariant, kotoruj pozvoljaet soderzat' lyboj tip dannuh
#
def action(self, item):
print item
print item.text(0)
s = item.data(0, Qt.UserRole)
# print s
if __name__ == '__main__':
app = QApplication([])
w = simpleWindow()
w.show()
app.exec_() | [
"[email protected]"
]
| |
99843c7e7a1a0218b814ee58d5be89d0b2b70fee | b456cbde5527e5ef1617c4670f79052d9d9b1e0c | /fundemo/filter_demo.py | 69e7002d9dbac921461db5d82938cf9a06002ac5 | []
| no_license | srikanthpragada/PYTHON_07_JAN_2019_DEMO | 071269dd59b954ecb69d33b63b0bece1f29d8563 | f8e211da5460072b34526b50eebfe4df242c11a4 | refs/heads/master | 2020-04-16T03:31:44.032616 | 2019-02-16T12:27:31 | 2019-02-16T12:27:31 | 165,234,686 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 171 | py | def positive(n):
return n >= 0
nums = [10, -10, 20, 5, -7, 15]
for n in filter(positive, nums):
print(n)
for n in filter(lambda v: v >= 0, nums):
print(n)
| [
"[email protected]"
]
| |
994a21e1b5351bb8803115122538763a18ca4061 | 8ce656578e04369cea75c81b529b977fb1d58d94 | /cabinet/management/commands/install_agent_document_categories.py | f7066c4849307c4450974b965c055fa0181053d4 | []
| no_license | JJvzd/django_exp | f9a08c40a6a7535777a8b5005daafe581d8fe1dc | b1df4681e67aad49a1ce6426682df66b81465cb6 | refs/heads/master | 2023-05-31T13:21:24.178394 | 2021-06-22T10:19:43 | 2021-06-22T10:19:43 | 379,227,324 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,460 | py | from django.core.management import BaseCommand
from clients.models import AgentDocumentCategory
class Command(BaseCommand):
help = 'Ининцализация документов агента'
def handle(self, *args, **options):
data = [
{
'name': 'Согласие на обработку персональных данных.',
'for_physical_person': True,
'for_individual_entrepreneur': True,
'for_organization': True,
'type': 'doc_ConfirmPersonalData',
},
{
'name': 'Устав',
'for_organization': True,
'type': 'doc_Charter',
},
{
'name': 'Копия паспорта',
'for_individual_entrepreneur': True,
'for_physical_person': True,
'type': 'doc_Passport',
},
{
'name': 'Скан свидетельства ИНН',
'for_individual_entrepreneur': True,
'for_organization': True,
'for_physical_person': True,
'type': 'doc_ScanINN',
},
{
'name': 'Скан свидетельства ОГРН.',
'for_individual_entrepreneur': True,
'for_organization': True,
'type': 'doc_ScanOGRN',
},
{
'name': 'Решение о назначение или приказ о заключение крупных сделок',
'for_organization': True,
'type': 'doc_BigDeal',
},
{
'name': 'Документ, подтверждающий применение режима налогообложения',
'for_individual_entrepreneur': True,
'for_organization': True,
'type': 'doc_ConfirmTax',
},
{
'name': 'Документ, подтверждающий применение режима налогообложения',
'for_individual_entrepreneur': True,
'for_organization': True,
'type': 'doc_ConfirmTax',
},
{
'name': 'Карточка компании.',
'for_individual_entrepreneur': True,
'for_organization': True,
'for_physical_person': True,
'type': 'doc_CompanyInfo',
},
{
'name': 'Договор ТХ для ознакомления.',
'for_individual_entrepreneur': True,
'for_organization': True,
'for_physical_person': True,
'auto_generate': True,
'type': 'doc_ContractExample',
},
{
'name': 'Договор ТХ',
'for_individual_entrepreneur': True,
'for_organization': True,
'for_physical_person': True,
'auto_generate': True,
'type': 'doc_Contract',
},
]
for (order, params) in enumerate(data):
AgentDocumentCategory.objects.update_or_create(
type=params.pop('type'),
defaults=dict(order=order, **params),
)
| [
"[email protected]"
]
| |
d1f9a4f51096ddd9ae18d5367d377658e2bb5622 | 11fe265badfae33041cf5fcdde1aa08aa1ab6839 | /LeetCode/290.WordPattern/Solution.py | 304580b9b2cf4a2bf6f2f11f799295df3b755fb2 | []
| no_license | CharlotteKuang/algorithm | 04344a0f3d2675625843d47fbf7ea8ef5621ccc8 | e5750c2eee33fcc94d5be1643576ace541036bf5 | refs/heads/master | 2021-01-19T09:12:48.102258 | 2016-03-21T05:46:11 | 2016-03-21T05:46:11 | 33,219,348 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 742 | py | class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
strArr = str.split(' ')
if len(strArr) != len(pattern): return False
count = 0
strDict = {}
for p in pattern:
if not p in strDict:
strDict[p] = strArr[count]
else:
if strDict[p] != strArr[count]:
return False
count += 1
count = 0
pDict = {}
for s in strArr:
if not s in pDict:
pDict[s] = pattern[count]
else:
if pDict[s] != pattern[count]:
return False
count += 1
return True
if __name__ == '__main__':
sol = Solution()
#pattern, string = "abba","dog dog dog dog"
pattern = "abba"
string = "dog cat cat dog"
print sol.wordPattern(pattern, string)
| [
"[email protected]"
]
| |
d60e472f2c0a6abc4f19eb90c7e3b6c0f3fdef2b | 8dfe4b53fae92795405d789d52148d1291836afa | /python/python学习/day1/习题二-找出tmp目录下所有相同大小的文件.py | 732d9fc54c4c063aaf8d66a4aec841a91b161712 | []
| no_license | ymyjohnny/python | e07c54a88954e090cf3d30a4c6f6ac46353063fb | b483fd55e577d4dcceb5762bddf833df23874f3a | refs/heads/master | 2021-01-10T01:10:19.038424 | 2019-07-02T02:40:23 | 2019-07-02T02:40:23 | 45,223,843 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 713 | py | import os
from os import path
from os.path import join, getsize
d_size ={}
for root, dirs, files in os.walk('/tmp'):
for file in files:
# if '-' not in file:
# continue
# filenameall = os.path.join(dirs, file)
filenameall = path.join(root,file)
#print filenameall
try:
sizef = os.stat(filenameall)
except:
continue
if sizef.st_size == 0:
continue
#print sizef.st_size
d_size.setdefault(sizef.st_size, []).append(filenameall)
#print d_size
for k,v in d_size.items():
if len(v) <= 1:
continue
print v
#print d_size
| [
"[email protected]"
]
| |
b18236cb57a00898c5431242292ced8deffcd973 | 7bb747cb9a36b83fa1ba7e907f6198065f9bcab5 | /models/GAN3D.py | 785d3f7dd0b21e453601356a27467c3d221b18a4 | [
"MIT"
]
| permissive | stjordanis/3D-GAN-pytorch | 87531716b1574798558f741fa84a80aeaacc7479 | e3f640dbb8335cde239334b3b1ad143acd784c56 | refs/heads/master | 2022-04-17T12:52:03.358450 | 2020-04-15T16:48:25 | 2020-04-15T16:48:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,379 | py | import torch
import torch.nn as nn
from torchsummary import summary
"""
Implementation based on original paper NeurIPS 2016
https://papers.nips.cc/paper/6096-learning-a-probabilistic-latent-space-of-object-shapes-via-3d-generative-adversarial-modeling.pdf
"""
class Discriminator(torch.nn.Module):
def __init__(self, in_channels=3, dim=64, out_conv_channels=512):
super(Discriminator, self).__init__()
conv1_channels = int(out_conv_channels / 8)
conv2_channels = int(out_conv_channels / 4)
conv3_channels = int(out_conv_channels / 2)
self.out_conv_channels = out_conv_channels
self.out_dim = int(dim / 16)
self.conv1 = nn.Sequential(
nn.Conv3d(
in_channels=in_channels, out_channels=conv1_channels, kernel_size=4,
stride=2, padding=1, bias=False
),
nn.BatchNorm3d(conv1_channels),
nn.LeakyReLU(0.2, inplace=True)
)
self.conv2 = nn.Sequential(
nn.Conv3d(
in_channels=conv1_channels, out_channels=conv2_channels, kernel_size=4,
stride=2, padding=1, bias=False
),
nn.BatchNorm3d(conv2_channels),
nn.LeakyReLU(0.2, inplace=True)
)
self.conv3 = nn.Sequential(
nn.Conv3d(
in_channels=conv2_channels, out_channels=conv3_channels, kernel_size=4,
stride=2, padding=1, bias=False
),
nn.BatchNorm3d(conv3_channels),
nn.LeakyReLU(0.2, inplace=True)
)
self.conv4 = nn.Sequential(
nn.Conv3d(
in_channels=conv3_channels, out_channels=out_conv_channels, kernel_size=4,
stride=2, padding=1, bias=False
),
nn.BatchNorm3d(out_conv_channels),
nn.LeakyReLU(0.2, inplace=True)
)
self.out = nn.Sequential(
nn.Linear(out_conv_channels * self.out_dim * self.out_dim * self.out_dim, 1),
nn.Sigmoid(),
)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
x = self.conv4(x)
# Flatten and apply linear + sigmoid
x = x.view(-1, self.out_conv_channels * self.out_dim * self.out_dim * self.out_dim)
x = self.out(x)
return x
class Generator(torch.nn.Module):
def __init__(self, in_channels=512, out_dim=64, out_channels=1, noise_dim=200, activation="sigmoid"):
super(Generator, self).__init__()
self.in_channels = in_channels
self.out_dim = out_dim
self.in_dim = int(out_dim / 16)
conv1_out_channels = int(self.in_channels / 2.0)
conv2_out_channels = int(conv1_out_channels / 2)
conv3_out_channels = int(conv2_out_channels / 2)
self.linear = torch.nn.Linear(noise_dim, in_channels * self.in_dim * self.in_dim * self.in_dim)
self.conv1 = nn.Sequential(
nn.ConvTranspose3d(
in_channels=in_channels, out_channels=conv1_out_channels, kernel_size=(4, 4, 4),
stride=2, padding=1, bias=False
),
nn.BatchNorm3d(conv1_out_channels),
nn.ReLU(inplace=True)
)
self.conv2 = nn.Sequential(
nn.ConvTranspose3d(
in_channels=conv1_out_channels, out_channels=conv2_out_channels, kernel_size=(4, 4, 4),
stride=2, padding=1, bias=False
),
nn.BatchNorm3d(conv2_out_channels),
nn.ReLU(inplace=True)
)
self.conv3 = nn.Sequential(
nn.ConvTranspose3d(
in_channels=conv2_out_channels, out_channels=conv3_out_channels, kernel_size=(4, 4, 4),
stride=2, padding=1, bias=False
),
nn.BatchNorm3d(conv3_out_channels),
nn.ReLU(inplace=True)
)
self.conv4 = nn.Sequential(
nn.ConvTranspose3d(
in_channels=conv3_out_channels, out_channels=out_channels, kernel_size=(4, 4, 4),
stride=2, padding=1, bias=False
)
)
if activation == "sigmoid":
self.out = torch.nn.Sigmoid()
else:
self.out = torch.nn.Tanh()
def project(self, x):
"""
projects and reshapes latent vector to starting volume
:param x: latent vector
:return: starting volume
"""
return x.view(-1, self.in_channels, self.in_dim, self.in_dim, self.in_dim)
def forward(self, x):
x = self.linear(x)
x = self.project(x)
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
x = self.conv4(x)
return self.out(x)
def test_gan3d():
noise_dim = 200
in_channels = 512
dim = 64 # cube volume
model_generator = Generator(in_channels=512, out_dim=dim, out_channels=1, noise_dim=noise_dim)
noise = torch.rand(1, noise_dim)
generated_volume = model_generator(noise)
print("Generator output shape", generated_volume.shape)
model_discriminator = Discriminator(in_channels=1, dim=dim, out_conv_channels=in_channels)
out = model_discriminator(generated_volume)
print("Discriminator output", out)
summary(model_generator, (1, noise_dim))
summary(model_discriminator, (1, 64, 64, 64))
test_gan3d()
| [
"[email protected]"
]
| |
3203f96749773440ba87ed366bd845ea5a43a2c9 | f6080f777407734e4b42a0100df57f40f17f3ad2 | /DSA 450 GFG/reverse_linked_list_iterative.py | 791cbfa29840d79af71d950be8fd0124e0a84ec3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | MannyP31/CompetitiveProgrammingQuestionBank | abf136410a9a76b186995b0e851cb3869938b5f5 | 23fd547b06a65ae0f5246d2500c4c81fab1a92e0 | refs/heads/master | 2023-08-24T23:06:13.740397 | 2021-09-30T06:38:34 | 2021-09-30T06:38:34 | 358,646,838 | 2 | 0 | MIT | 2021-09-30T06:38:35 | 2021-04-16T15:43:10 | C++ | UTF-8 | Python | false | false | 960 | py | #https://leetcode.com/problems/reverse-linked-list/
# Iterative method
#Approach :
# Store the head in a temp variable called current .
# curr = head , prev = null
# Now for a normal linked list , the current will point to the next node and so on till null
# For reverse linked list, the current node should point to the previous node and the first node here will point to null
# Keep iterating the linkedlist until the last node and keep changing the next of the current node to prev node and also
# update the prev node to current node and current node to next node
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head):
curr = head
prev = None
while(curr != None):
next = curr.next
curr.next = prev
prev = curr
curr = next
return prev
| [
"[email protected]"
]
| |
117e4a84741a16aa97c2439a4cb411ffa6ea84f1 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p00007/s249774203.py | 45118b4f2e83abf18eb480f4129f1763910d08c9 | []
| no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 106 | py | i = int(input())
x = 100000
for _ in range(i):
x *= 1.05
x = int((x+999) / 1000) * 1000
print(x) | [
"[email protected]"
]
| |
010fa572fce96bbea946684f5f4c6dd203f393d4 | 66a530b297725b1a2d1c95f95883145c04614ae1 | /0x06-python-classes/4-square.py | b06dd0ffb43c9324bf62690a848170202420b3da | []
| no_license | Yagomfh/holbertonschool-higher_level_programming | 4e6f28186eae18eaba60017fe49ac446a02cbdc5 | 1d15597a6040a8ee15b08447c478d0a2e79b5854 | refs/heads/main | 2023-04-23T18:23:28.096644 | 2021-05-18T08:12:27 | 2021-05-18T08:12:27 | 319,253,389 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,031 | py | #!/usr/bin/python3
"""Define a class Square."""
class Square:
"""A class Square."""
def __init__(self, size=0):
"""Initialize a new Square.
Args:
size (int): The size of the new square.
Raises:
TypeError: if size is not an int
ValueError: if size is < 0
"""
if type(size) != int:
raise TypeError('size must be an integer')
if size < 0:
raise ValueError('size must be >= 0')
self.__size = size
def area(self):
"""Calculates the area of a square.
Returns: the size raise to the power of two
"""
return self.__size ** 2
@property
def size(self):
"""Get/set the current size of the square."""
return self.__size
@size.setter
def size(self, value):
if type(value) != int:
raise TypeError('size must be an integer')
if value < 0:
raise ValueError('size must be >= 0')
self.__size = value
| [
"[email protected]"
]
| |
125b0fb3e4af48e20e3f8383e2f0dfe78cb291fe | d57b51ec207002e333b8655a8f5832ed143aa28c | /.history/gos_20200614063006.py | 3b1d50fca3f5888ff5d4a21fa47bff0e281d9930 | []
| no_license | yevheniir/python_course_2020 | b42766c4278a08b8b79fec77e036a1b987accf51 | a152d400ab4f45d9d98d8ad8b2560d6f0b408c0b | refs/heads/master | 2022-11-15T07:13:24.193173 | 2020-07-11T15:43:26 | 2020-07-11T15:43:26 | 278,890,802 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 8,556 | py | # # Імпорт фажливих бібліотек
# from BeautifulSoup import BeautifulSoup
# import urllib2
# import re
# # Створення функції пошуку силок
# def getLinks(url):
# # отримання та присвоєння контенту сторінки в змінну
# html_page = urllib2.urlopen(url)
# # Перетворення контенту в обєкт бібліотеки BeautifulSoup
# soup = BeautifulSoup(html_page)
# # створення пустого масиву для лінків
# links = []
# # ЗА ДОПОМОГОЮ ЧИКЛУ ПРОХЛДИМСЯ ПО ВСІХ ЕЛЕМЕНТАХ ДЕ Є СИЛКА
# for link in soup.findAll('a', attrs={'href': re.compile("^http://")}):
# # Додаємо всі силки в список
# links.append(link.get('href'))
# # повертаємо список
# return links
# -----------------------------------------------------------------------------------------------------------
# # # Імпорт фажливих бібліотек
# import subprocess
# # Створення циклу та використання функції range для генерації послідовних чисел
# for ping in range(1,10):
# # генерування IP адреси базуючись на номері ітерації
# address = "127.0.0." + str(ping)
# # виклик функції call яка робить запит на IP адрес та запис відповіді в змінну
# res = subprocess.call(['ping', '-c', '3', address])
# # За допомогою умовних операторів перевіряємо відповідь та виводимо результат
# if res == 0:
# print "ping to", address, "OK"
# elif res == 2:
# print "no response from", address
# else:
# print "ping to", address, "failed!"
# -----------------------------------------------------------------------------------------------------------
# # Імпорт фажливих бібліотек
# import requests
# # Ітеруємося по масиву з адресами зображень
# for i, pic_url in enumerate(["http://x.com/nanachi.jpg", "http://x.com/nezuko.jpg"]):
# # Відкриваємо файл базуючись на номері ітерації
# with open('pic{0}.jpg'.format(i), 'wb') as handle:
# # Отримуємо картинку
# response = requests.get(pic_url, stream=True)
# # Використовуючи умовний оператор перевіряємо чи успішно виконався запит
# if not response.ok:
# print(response)
# # Ітеруємося по байтах картинки та записуємо батчаси в 1024 до файлу
# for block in response.iter_content(1024):
# # Якщо байти закінчилися, завершуємо алгоритм
# if not block:
# break
# # Записуємо байти в файл
# handle.write(block)
# -----------------------------------------------------------------------------------------------------------
# # Створюємо клас для рахунку
# class Bank_Account:
# # В конструкторі ініціалізуємо рахунок як 0
# def __init__(self):
# self.balance=0
# print("Hello!!! Welcome to the Deposit & Withdrawal Machine")
# # В методі депозит, використовуючи функцію input() просимо ввести суму поповенння та додаємо цю суму до рахунку
# def deposit(self):
# amount=float(input("Enter amount to be Deposited: "))
# self.balance += amount
# print("\n Amount Deposited:",amount)
# # В методі депозит, використовуючи функцію input() просимо ввести суму отримання та віднімаємо цю суму від рахунку
# def withdraw(self):
# amount = float(input("Enter amount to be Withdrawn: "))
# # За допомогою умовного оператора перевіряємо чи достатнього грошей на рахунку
# if self.balance>=amount:
# self.balance-=amount
# print("\n You Withdrew:", amount)
# else:
# print("\n Insufficient balance ")
# # Виводимо бааланс на екран
# def display(self):
# print("\n Net Available Balance=",self.balance)
# # Створюємо рахунок
# s = Bank_Account()
# # Проводимо операції з рахунком
# s.deposit()
# s.withdraw()
# s.display()
# -----------------------------------------------------------------------------------------------------------
# # Створюємо рекурсивну функцію яка приймає десяткове число
# def decimalToBinary(n):
# # перевіряємо чи число юільше 1
# if(n > 1):
# # Якщо так, ділемо на 2 юез остачі та рекурсивно викликаємо функцію
# decimalToBinary(n//2)
# # Якщо ні, виводимо на остачу ділення числа на 2
# print(n%2, end=' ')
# # Створюємо функцію яка приймає бінарне число
# def binaryToDecimal(binary):
# # Створюємо додаткову змінну
# binary1 = binary
# # Ініціалізуємо ще 3 змінню даючи їм значення 0
# decimal, i, n = 0, 0, 0
# # Ітеруємося до тих пір поки передане нами число не буде 0
# while(binary != 0):
# # Отримуємо остачу від ділення нашого чила на 10 на записуємо в змінну
# dec = binary % 10
# # Додаємо до результату суму попереднього результату та добуток від dec та піднесення 2 до степеня номеру ітерації
# decimal = decimal + dec * pow(2, i)
# # Змінюємо binary
# binary = binary//10
# # Додаємо 1 до кількості ітерацій
# i += 1
# # Виводимо результат
# print(decimal)
# -----------------------------------------------------------------------------------------------------------
# # Імпорт фажливих бібліотек
# import re
# # В умовному операторі перевіряємо чи підходить введена пошта під знайдений з інтернету regex
# if re.match(r"[^@]+@[^@]+\.[^@]+", "[email protected]"):
# # Якщо так, виводиму valid
# print("valid")
# -----------------------------------------------------------------------------------------------------------
# # Створення функції яка приймає текст для шифрування та здвиг
# def encrypt(text,s):
# # Створення змінної для результату
# result = ""
# # Ітеруємося по тексту використовуючи range та довжину тексту
# for i in range(len(text)):
# # Беремо літеру базуючись на номері ітерації
# char = text[i]
# # Перевіряємо чи ця літера велика
# if (char.isupper()):
# # Кодуємо літеру базуючись на її номері
# result += chr((ord(char) + s-65) % 26 + 65)
# else:
# # Кодуємо літеру базуючись на її номері
# result += chr((ord(char) + s - 97) % 26 + 97)
# # Повертаємо результат
# return result
# -----------------------------------------------------------------------------------------------------------
numbers = ["0502342349", "0500897897", "0992342349"]
result = {}
for num in numbers:
result[num[:3]] = []
for num in numbers:
result[num[:3]].append()
print(result) | [
"[email protected]"
]
| |
b31c92f6f572429aeea4c020e3003a173304d42f | cf3645e1bbfde328aec2175b3fa5d6eda6b5e2b1 | /crawling_back/spiders/__init__.py | 8c5f24e6fe7b0bc4dccd48b1c108c5ef422fcca0 | []
| no_license | ShichaoMa/old-spider | f74f00d6a6c114aa6878662907c70ebe42f9ea09 | cf030b655434a3adb6094302b1d2650f6521d1d3 | refs/heads/master | 2020-03-06T15:53:49.709223 | 2018-03-27T09:36:58 | 2018-03-27T09:36:58 | 126,963,707 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,975 | py | # -*- coding:utf-8 -*-
# This package will contain the spiders of your Scrapy project
#
# Please refer to the documentation for information on how to create and manage
# your spiders.
import time
from hashlib import sha1
from urllib.parse import urlparse
from scrapy.spiders import Spider
from scrapy import signals, Request
from scrapy.exceptions import DontCloseSpider, IgnoreRequest
from scrapy.utils.response import response_status_message
from .fingerprint import FINGERPRINT
from .exception_process import parse_method_wrapper
from .utils import post_es, LoggerDescriptor, url_arg_increment, url_item_arg_increment, \
url_path_arg_increment, enrich_wrapper, ItemCollector, ItemCollectorPath, is_debug
class JaySpider(Spider):
name = "jay"
need_duplicate = False
item_xpath = tuple()
page_xpath = tuple()
proxy = None
change_proxy = None
log = LoggerDescriptor()
debug = is_debug()
def __init__(self, *args, **kwargs):
Spider.__init__(self, *args, **kwargs)
self.redis_conn = None
@property
def logger(self):
return self.log
def _set_crawler(self, crawler):
super(JaySpider, self)._set_crawler(crawler)
self.crawler.signals.connect(self.spider_idle,
signal=signals.spider_idle)
def set_redis(self, redis_conn):
self.redis_conn = redis_conn
def spider_idle(self):
if self.settings.getbool("IDLE", True):
print('Don\'t close spider......')
raise DontCloseSpider
def duplicate_filter(self, response, url, func):
crawlid = response.meta["crawlid"]
common_part = func(url)
if self.redis_conn.sismember("crawlid:%s:model" % crawlid, common_part):
return True
else:
self.redis_conn.sadd("crawlid:%s:model" % crawlid, common_part)
self.redis_conn.expire("crawlid:%s:model" % crawlid,
self.crawler.settings.get("DUPLICATE_TIMEOUT", 60 * 60))
return False
@staticmethod
def get_base_loader(response):
pass
def extract_item_urls(self, response):
return [response.urljoin(x) for x in set(response.xpath("|".join(self.item_xpath)).extract())]
@staticmethod
def adjust(response):
if "if_next_page" in response.meta:
del response.meta["if_next_page"]
else:
response.meta["seed"] = response.url
# 防止代理继承 add at 16.10.26
response.meta.pop("proxy", None)
response.meta["callback"] = "parse_item"
response.meta["priority"] -= 20
def extract_page_urls(self, response, effective_urls, item_urls):
xpath = "|".join(self.page_xpath)
if xpath.count("?") == 1:
next_page_urls = [url_arg_increment(xpath, response.url)] if len(effective_urls) else []
elif xpath.count("~="):
next_page_urls = [url_path_arg_increment(xpath, response.url)] if len(effective_urls) else []
elif xpath.count("/") > 1:
next_page_urls = [response.urljoin(x) for x in set(response.xpath(xpath).extract())] if len(effective_urls) else []
else:
next_page_urls = [url_item_arg_increment(xpath, response.url, len(item_urls))] if len(effective_urls) else []
response.meta["if_next_page"] = True
response.meta["callback"] = "parse"
response.meta["priority"] += 20
return next_page_urls
@parse_method_wrapper
def parse(self, response):
self.logger.debug("Start response in parse. ")
item_urls = self.extract_item_urls(response)
if not response.meta.get("full", True):
self.logger.debug("Filtering exists items. ")
new_urls = [i for i in item_urls if not post_es(
self.crawler.settings.get("ES_HOST", "192.168.200.153"), self.crawler.settings.getint("ES_PORT", 9200),
sha1(FINGERPRINT.get(self.name, lambda x: x)(i).encode("utf-8")).hexdigest())]
self.logger.debug("%s items have been skipped. " % (len(item_urls) - len(new_urls)))
item_urls = new_urls
self.adjust(response)
# 增加这个字段的目的是为了记住去重后的url有多少个,如果为空,对于按参数翻页的网站,有可能已经翻到了最后一页。
effective_urls = []
for item_url in item_urls:
if self.need_duplicate:
if self.duplicate_filter(response, item_url, self.need_duplicate):
continue
response.meta["url"] = item_url
self.crawler.stats.inc_total_pages(response.meta['crawlid'])
effective_urls.append(item_url)
yield Request(url=item_url,
callback=self.parse_item,
meta=response.meta,
errback=self.errback)
next_page_urls = self.extract_page_urls(response, effective_urls, item_urls) or []
for next_page_url in next_page_urls:
response.meta["url"] = next_page_url
yield Request(url=next_page_url,
callback=self.parse,
meta=response.meta)
# next_page_url有且仅有一个,多出来的肯定是重复的
break
@enrich_wrapper
def enrich_base_data(self, item_loader, response):
item_loader.add_value('spiderid', response.meta.get('spiderid'))
item_loader.add_value('url', response.meta.get("url"))
item_loader.add_value("seed", response.meta.get("seed", ""))
item_loader.add_value("timestamp", time.strftime("%Y%m%d%H%M%S"))
item_loader.add_value('status_code', response.status)
item_loader.add_value("status_msg", response_status_message(response.status))
item_loader.add_value('domain', urlparse(response.url).hostname.split(".", 1)[1])
item_loader.add_value('crawlid', response.meta.get('crawlid'))
item_loader.add_value('response_url', response.url)
item_loader.add_value("item_type", getattr(self, "item_type", "product"))
item_loader.add_value("proxy", response.meta.get("proxy"))
item_loader.add_value("fingerprint", sha1(FINGERPRINT.get(self.name, lambda x: x)(
response.url).encode("utf-8")).hexdigest())
meta = dict()
code_list = ["tags", "extend", "full", "type", "upc", "ean", "mpn", "roc_id", "all_sku"]
for code in code_list:
meta[code] = response.meta.get(code)
item_loader.add_value("meta", meta)
if response.meta.get("seed", "") or response.meta.get("type") == "explore":
collection_name = "jay_%ss" % response.meta.get('spiderid')
else:
collection_name = "jay_%s_updates" % response.meta.get('spiderid')
item_loader.add_value("collection_name", collection_name)
@enrich_wrapper
def enrich_data(self, item_loader, response):
pass
@parse_method_wrapper
def parse_item(self, response):
response.meta["request_count_per_item"] = 1
base_loader = self.get_base_loader(response)
meta = response.request.meta
item_collector = ItemCollector()
meta["item_collector"] = item_collector
meta["path"] = ItemCollectorPath()
item_collector.add_item_loader(meta["path"], base_loader)
self.enrich_base_data(base_loader, response)
requests = self.enrich_data(base_loader, response)
return self.yield_item(requests, item_collector, response)
@parse_method_wrapper
def parse_next(self, response):
response.meta["request_count_per_item"] += 1
meta = response.request.meta
item_collector = meta["item_collector"]
path = meta["path"]
loader = item_collector.item_loader(path)
prop = path.last_prop()
requests = getattr(self, "enrich_%s"%prop)(loader, response)
return self.yield_item(requests, item_collector, response)
def yield_item(self, requests, item_collector, response):
if requests:
item_collector.add_requests(requests)
if item_collector.have_request():
req = item_collector.pop_request()
response.request.meta.update(req["meta"])
response.request.meta["priority"] += 1
req["meta"] = response.request.meta
req["callback"] = "parse_next"
req["errback"] = "errback"
return Request(**req)
else:
item = item_collector.load_item()
if item.get("status_code") != 999:
self.logger.info("crawlid: %s, product_id: %s, %s requests send for successful yield item" % (
item.get("crawlid"), item.get("product_id", "unknow"), response.meta.get("request_count_per_item", 1)))
self.crawler.stats.inc_crawled_pages(response.meta['crawlid'])
else:
item["status_msg"] = "".join(response.xpath("//html/body/p/text()").extract())
return item
def errback(self, failure):
if failure and failure.value and hasattr(failure.value, 'response'):
response = failure.value.response
if response:
loader = self.get_base_loader(response)
self.enrich_base_data(loader, response)
item = loader.load_item()
if item["status_msg"].count("Unknown Status"):
item["status_msg"] = "errback: %s"% failure.value
self.logger.error("errback: %s" % item)
if not isinstance(failure.value, IgnoreRequest):
self.crawler.stats.inc_crawled_pages(response.meta['crawlid'])
return item
else:
self.logger.error("failure has NO response")
else:
self.logger.error("failure or failure.value is NULL, failure: %s" % failure)
| [
"[email protected]"
]
| |
06c45efbe18b822fa8d30305bf3275b8c87b3b59 | 4ade586eb178b3cfb80f4fcabef023b1f1001d0c | /tips/DFS/arc_031_2.py | 0abc82e408dc433f1ca32f30a0ad15e637d377b9 | []
| no_license | TakeruEndo/atcoder | e3c5ef8ca802aa4995c471deca7b25daf56a06ef | 5c812377096ae255b2fa51b3a29c1b2ea686ad57 | refs/heads/master | 2022-06-02T08:05:55.003353 | 2020-05-02T08:59:32 | 2020-05-02T08:59:32 | 234,338,212 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,280 | py | import sys
sys.setrecursionlimit(1000000)
# 4方向への移動bベクトル
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
def dfs(h, w, type_):
if type_ == 'first':
pass
else:
d[h][w] = 1
global count
count += 1
# 4方向を探索
for dire in range(4):
nh = h + dy[dire]
nw = w + dx[dire]
# 場外アウト、壁ならスルー
if nh < 0 or nh >= H or nw < 0 or nw >= W:
continue
if d[nh][nw] == 1:
continue
if field[nh][nw] == 'x':
continue
dfs(nh, nw, 'other')
if __name__=='__main__':
H, W = 10, 10
field = []
# 陸地のカウント数
land_c = 0
# 適当な陸地座標
lx, ly = 0, 0
for i in range(H):
field.append(list(input()))
# oの数をカウントする
o_count = 0
for h in range(H):
for w in range(W):
if field[h][w] == 'o':
o_count += 1
for h in range(H):
for w in range(W):
if field[h][w] == 'x':
d = [[0]*W for i in range(H)]
count = 0
dfs(h, w, 'first')
if count-1 == o_count:
print('YES')
sys.exit()
print('NO')
| [
"[email protected]"
]
| |
ec3c89592d4d8c69c233e4564f3b388d26f5e4f4 | 91fb65972d69ca25ddd892b9d5373919ee518ee7 | /pibm-training/sample-programs/exception_002.py | 74b1fd23e26fd08cf017cd245626f8fdde4a1499 | []
| no_license | zeppertrek/my-python-sandpit | c36b78e7b3118133c215468e0a387a987d2e62a9 | c04177b276e6f784f94d4db0481fcd2ee0048265 | refs/heads/master | 2022-12-12T00:27:37.338001 | 2020-11-08T08:56:33 | 2020-11-08T08:56:33 | 141,911,099 | 0 | 0 | null | 2022-12-08T04:09:28 | 2018-07-22T16:12:55 | Python | UTF-8 | Python | false | false | 251 | py | #exception_002.py
while True:
try:
n = input("Please enter an integer: ")
n = int(n)
break
except ValueError:
print("No valid integer! Please try again ...")
print ("Great, you successfully entered an integer!") | [
"[email protected]"
]
| |
708ea2020f4815fbe87b1959cbb649477a0ad86b | b28c2e04e2a093a7e83b214c877ea30978ff862e | /twitter_clustering/fetch_tweets.py | 52d24a15e40e4d372cfb9cb8f5584ff41e3151f6 | []
| no_license | markmo/experiments | ec00dcb6219cd422873ae3a018fc2bc8cadedd5c | f7d3f25dfef2472ec1b5bed30be7b46daa448257 | refs/heads/master | 2020-05-31T17:55:21.537201 | 2011-04-12T20:53:41 | 2011-04-12T20:53:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,094 | py | # -*- coding: utf-8 =*-
import codecs
# import json
import sys
import twitter
HASHTAG = sys.argv[1]
PAGES = int(sys.argv[2])
RPP = int(sys.argv[3])
# http://search.twitter.com/search.json?pages=15&rpp=100&q=%23webstock&show_user=true
# Twitter will only return a max of approx. 1500 results (rpp * pages),
# showing a mix of recent and popular results
t = twitter.Twitter(domain='search.twitter.com')
search_results = []
for page in range(1, PAGES):
search_results.append(t.search(q=HASHTAG, rpp=RPP, show_user=False))
# print json.dumps(tweets, sort_keys=True, indent=1)
f = codecs.open('./output/tweets', 'w', encoding="UTF-8")
count = 0
for result in search_results:
for t in result['results']:
count += 1
f.write(''.join([
t['from_user_id_str'], '\t',
t['from_user'], '\t',
' '.join(t['text'].splitlines()), '\n' # creates a list from text breaking at line boundaries, and joins them back up using the object of the join method as the delimiter
]))
print "Wrote %i records." % (count)
f.close()
| [
"[email protected]"
]
| |
71a3bd14e7095ed858fc0f5c4537109f5b7edef0 | ad13583673551857615498b9605d9dcab63bb2c3 | /output/instances/nistData/union/duration-decimal/Schema+Instance/NISTXML-SV-IV-union-duration-decimal-enumeration-4-4.py | 31399b0d101328ef12787056cf9e2b96842cc399 | [
"MIT"
]
| permissive | tefra/xsdata-w3c-tests | 397180205a735b06170aa188f1f39451d2089815 | 081d0908382a0e0b29c8ee9caca6f1c0e36dd6db | refs/heads/main | 2023-08-03T04:25:37.841917 | 2023-07-29T17:10:13 | 2023-07-30T12:11:13 | 239,622,251 | 2 | 0 | MIT | 2023-07-25T14:19:04 | 2020-02-10T21:59:47 | Python | UTF-8 | Python | false | false | 616 | py | from output.models.nist_data.union.duration_decimal.schema_instance.nistschema_sv_iv_union_duration_decimal_enumeration_4_xsd.nistschema_sv_iv_union_duration_decimal_enumeration_4 import NistschemaSvIvUnionDurationDecimalEnumeration4
from output.models.nist_data.union.duration_decimal.schema_instance.nistschema_sv_iv_union_duration_decimal_enumeration_4_xsd.nistschema_sv_iv_union_duration_decimal_enumeration_4 import NistschemaSvIvUnionDurationDecimalEnumeration4Type
obj = NistschemaSvIvUnionDurationDecimalEnumeration4(
value=NistschemaSvIvUnionDurationDecimalEnumeration4Type.VALUE_MINUS_6_6957506428
)
| [
"[email protected]"
]
| |
ce27f610b1f9156233d4b024e14ac4d729503599 | 1375f57f96c4021f8b362ad7fb693210be32eac9 | /kubernetes/test/test_v1_replication_controller_status.py | b142b6da9d514589c5adfdf4056cc4689abbee8d | [
"Apache-2.0"
]
| permissive | dawidfieluba/client-python | 92d637354e2f2842f4c2408ed44d9d71d5572606 | 53e882c920d34fab84c76b9e38eecfed0d265da1 | refs/heads/master | 2021-12-23T20:13:26.751954 | 2017-10-06T22:29:14 | 2017-10-06T22:29:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 973 | py | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.7.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
import unittest
import kubernetes.client
from kubernetes.client.rest import ApiException
from kubernetes.client.models.v1_replication_controller_status import V1ReplicationControllerStatus
class TestV1ReplicationControllerStatus(unittest.TestCase):
""" V1ReplicationControllerStatus unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testV1ReplicationControllerStatus(self):
"""
Test V1ReplicationControllerStatus
"""
model = kubernetes.client.models.v1_replication_controller_status.V1ReplicationControllerStatus()
if __name__ == '__main__':
unittest.main()
| [
"[email protected]"
]
| |
f2f2341b156aee87b251c8e69a037bcec17fe382 | a8062308fb3bf6c8952257504a50c3e97d801294 | /problems/N1015_Smallest_Integer_Divisible_By_K.py | ecc44268c08d271cd52b6ffb21cb2292647e28db | []
| no_license | wan-catherine/Leetcode | 650d697a873ad23c0b64d08ad525bf9fcdb62b1b | 238995bd23c8a6c40c6035890e94baa2473d4bbc | refs/heads/master | 2023-09-01T00:56:27.677230 | 2023-08-31T00:49:31 | 2023-08-31T00:49:31 | 143,770,000 | 5 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,431 | py | class Solution(object):
"""
num = a*K + r ==> num%K == r%K
num_1 = num*10 + 1 = 10*a*K + 10*r + 1 ==> num_1%K == (10*r + 1)%K
so for all num, num%K == (10*(last r) + 1)%K
r = num%K ==> r < K
so the while at most run K times, then :
1. it find num which num%K == 0
2. there is a cycle of r , we use used to check.
"""
def smallestRepunitDivByK(self, K):
"""
:type K: int
:rtype: int
"""
n = 1
res = 1
used = set()
while True:
r = n % K
if not r:
return res
if r in used:
return -1
used.add(r)
n = 10*r + 1
res += 1
"""
Here we check K % 2 and K % 5 , then all other will be divisible.
we have 1, 2, ..., k-3, k-2, k-1 remainder.
now if the num isn't divisible, it means ri, rj in those remainders are equal ==>
(10*ri + 1)%K == (10*rj + 1)%K
10*ri + 1 + a*K = 10*rj + 1
(rj-ri) = a*K/10 ==> 0 < a < 10
if K%2== 0 or K%5 == 0 , a can be 5 or 2, then rj can be same as ri.
so it won't be divisible.
"""
def smallestRepunitDivByK_(self, K):
if K % 2 == 0 or K % 5 == 0:
return -1
n = 1
res = 1
while True:
r = n % K
if not r:
return res
n = 10*r + 1
res += 1
| [
"[email protected]"
]
| |
9df1c852a8bc6e84f68ce40d11133309ae3de95a | d75cbad7a79e24b49f405c6529633ea65c9b286d | /basic_linear_regression.py | 37b7c00364080d4167bba791a2f3655a849f9e08 | []
| no_license | aj2622/ML_HW1 | bc49e61781f108c66dfd598423915e27c72f7b3a | 7497f8d71f6b731fc232058d6a0597af4884a53f | refs/heads/master | 2020-04-22T08:49:52.188349 | 2017-10-31T14:23:02 | 2017-10-31T14:23:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,108 | py | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
if __name__ == '__main__':
test_data = pd.read_csv('data/4_test.csv')
train_data = pd.read_csv('data/4_train.csv')
train_t = np.array(train_data['t'].values)
test_t = np.array(test_data['t'].values)
train_x = np.array(train_data['x'].values)
test_x = np.array(test_data['x'].values)
train_elist = []
test_elist = []
for order in range(0, 10):
Xm = np.zeros((len(train_x), order+1))
Xm[:, 0] = 1
for i in range(1, order+1):
Xm[:, i] = train_x**i
Xt = np.transpose(Xm)
w = np.dot(np.dot(np.linalg.inv(np.dot(Xt, Xm)), Xt), train_t)
w = np.flip(w, 0)
p = np.poly1d(w)
train_y = p(train_x)
test_y = p(test_x)
train_elist.append(np.sqrt(np.mean((train_y - train_t) ** 2)))
test_elist.append(np.sqrt(np.mean((test_y - test_t) ** 2)))
plt.plot(train_elist, marker='o')
plt.plot(test_elist, 'r-', marker='o')
plt.xlim(-1, 10)
plt.xlabel('M')
plt.ylabel('RMS Error')
plt.show() | [
"[email protected]"
]
| |
dc217de412ac4cd7870e2b1f1bb8531cab88a313 | accfe90fbd439fa4ef0655114a5b3d9d771ca837 | /euler53.py | f0facc7f50f6052f742c862cf253746770a693ac | []
| no_license | hackingmath/Project-Euler | 57641ba6e82706e5a3585e8072c70db81d97d984 | 83863e5351ba4425bd803ae0d01efeb824ffa7ca | refs/heads/master | 2022-02-22T09:06:10.215593 | 2019-07-13T16:21:47 | 2019-07-13T16:21:47 | 111,737,031 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 452 | py | '''Problem 53: Combinatoric selections'''
import time
t1 = time.time()
def fact(n):
if n <= 1:
return 1
return n*fact(n-1)
def combinations(n,r):
'''returns nCr'''
return fact(n)/(fact(r)*fact(n-r))
tot = 0
for n in range(1,101):
for r in range(1,101):
if combinations(n,r)>1000000:
tot += 1
print(tot)
t2 = time.time()
print(t2-t1)
#4075 Correct in 0.34 seconds
| [
"[email protected]"
]
| |
a9f2c564853bc7441c44a4c883e66286c4babe0a | 4d9bdaf3deb0f78dc99eb87b8cd4386e8f3069de | /scripts/PostStacksFiltering/genMissingLoci.py | 139e11d32999f22d8bad689cab5607c7e34c1d16 | []
| no_license | mfisher5/PCod-Compare-repo | 5b6f688097feb279a26cd12f43bf91f9a5a83e15 | 2320781656836c1d9534be1a406b1cae4c47ebe1 | refs/heads/master | 2020-03-07T12:33:25.000207 | 2018-06-10T23:05:23 | 2018-06-10T23:05:23 | 127,480,623 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,424 | py | ### This file generates Eleni's Missing Loci filtering file ###
## MF 2/24/2017
## Arguments:
##-- population map
#########################
import sys
popmap = open(sys.argv[1], "r")
script = open("FilterLoci_by_MissingValues.py", "w")
## Start writing the MAF filtering script ##
script.write("### This scripts removes loci with too much missing data (you set the threshold)\n#Adjusted from Eleni's script (June 15,2015) to take arguments\n#MF 2/28/2017\n\n#################\n\n\nimport sys\n\n")
script.write("# Open your files for reading and writing\ngenotypes_file = open(sys.argv[1],'r')\nclean_output_file = open(sys.argv[2],'w')\nblacklisted_output_file = open(sys.argv[3], 'w')\n\n")
## Count the missing genotypes in each population
#--- generate the same ordered dictionary used in the MAF filtering
import collections
PopDict = collections.OrderedDict()
PopList = []
for line in popmap:
linelist = line.strip().split()
newpop = linelist[1]
if newpop not in PopDict:
PopDict[newpop] = 1
PopList.append(newpop)
elif newpop in PopDict:
count = PopDict[newpop]
count += 1
PopDict[newpop] = count
#--- print message
length = str(len(PopList))
print "You have " + length + " populations."
print "These are your populations, with the number of samples in each:"
print PopDict
#--- initiate the for loop
script.write("\n#run for loop to counting missing genotypes by locus for each population\n\ncount = 0\nbad_count = 0\n\nfor mystring in genotypes_file: # Read in each line in the file as a string\n")
script.write("\tif count == 0:\n\t\tgenotypes_header = mystring\n\t\tclean_output_file.write(genotypes_header)\n\t\tblacklisted_output_file.write(genotypes_header)\n\t\tcount += 1\n")
script.write("\telse:\n\t\tcount += 1\n\t\toverall_percent_missingdata = []\n\t\t" + r"stripped_string = mystring.strip('\n')" + "\n\t\t" + "locus_name = stripped_string.split(',')[0]" + "\n")
#--- use dictionary to generate column indices (should be the same order as in MAF filtering)
PopList = PopDict.keys()
column = 1
column_indices = {}
for pop in PopList:
n_samples = PopDict[pop]
new_column = column + n_samples
column_indices[pop] = [column, new_column]
column = new_column
for pop in PopList:
cols = column_indices[pop]
newstr = pop + " = stripped_string.split(',')[" + str(cols[0]) + ":" + str(cols[1]) + "]"
script.write("\t\t" + newstr + "\n")
script.write("\n#per population counts\n")
#--- count missing data in each population
for pop in PopList:
newstr = "#next pop" + "\n\t\tCount_MissingGenotypesByLocus_" + pop + " = float(" + pop + ".count('0000'))" + "\n\t\tNumberOf_" + pop + "_individuals = float(len(" + pop + "))\n\t\tPercent_MissingData_" + pop + " = float(Count_MissingGenotypesByLocus_" + pop + "/NumberOf_" + pop + "_individuals)\n\t\t" + "overall_percent_missingdata.append(Percent_MissingData_" + pop + ")\n"
script.write(newstr)
#--- write good loci to one file, bad loci to another
script.write("\n#write loci to appropriate file\n\t\tif all(i < 0.50 for i in overall_percent_missingdata):\n\t\t\tclean_output_file.write(mystring)\n\t\telse: \n\t\t\tblacklisted_output_file.write(mystring)\n\t\t\tbad_count += 1")
#--- print output when finished
script.write("\n#print output\nn_loci = str(count - 1)\n" + "print 'processed ' + n_loci + ' loci'" + "\n" + "print 'Number of loci removed: ' + str(bad_count)")
script.close()
popmap.close()
| [
"[email protected]"
]
| |
4a29737770e7086e49a02c6b2ad4f68990dfe713 | dc7c62f22e5b7da4691d2bdf9a1da2f3ba9edd75 | /Course_case/2018_11_13/triangular2.py | d06a373b587ee46f8804945adac150cc981320b4 | []
| no_license | xiaohaiguicc/CS5001 | 563c17637f06f0074ccb743db4f0bdd2a326f978 | 51698ba8bfc2201639e6f4d358e0fc531780d2fc | refs/heads/master | 2020-04-06T17:32:55.046301 | 2018-12-20T23:53:05 | 2018-12-20T23:53:05 | 157,664,298 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 384 | py | import sys
def main(number):
print(add_up(number, 0, 0))
def add_up(number, counter, total):
if(counter == number):
return total
else:
counter += 1
total = total + counter
print(total)
return add_up(number, counter, total)
# Tail recursion should maintain some values so more than one arguments
main(int(sys.argv[1]))
| [
"[email protected]"
]
| |
121a4786acd33c8fae59095a863400cd9244e08f | 7a013424c82b71bc82aa312e0165a1af4170ac23 | /ABC/ABC130/ABC130C.py | bea89a0abcd66a950ed8682791281b50307f53ea | []
| no_license | kikugawa-shoma/Atcoder | fe3405e36dd3e4e25127b6110d6009db507e7095 | 7299116b7beb84815fe34d41f640a2ad1e74ba29 | refs/heads/master | 2020-12-21T19:10:12.471507 | 2020-10-10T16:38:18 | 2020-10-10T16:38:18 | 236,531,207 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 121 | py | W, H, x, y = map(float, input().split())
f = 0
if W / 2 == x and H / 2 == y:
f = 1
print("{} {}".format(W*H/2, f))
| [
"[email protected]"
]
| |
a8c8e4c916d17a090cfcb804aa6462fed27bdbb2 | 50948d4cb10dcb1cc9bc0355918478fb2841322a | /azure-mgmt-network/azure/mgmt/network/v2018_10_01/models/p2_svpn_profile_parameters_py3.py | 27b1bcd7ec17e77255ff1d4ced6bc9eb6304a6ed | [
"MIT"
]
| permissive | xiafu-msft/azure-sdk-for-python | de9cd680b39962702b629a8e94726bb4ab261594 | 4d9560cfd519ee60667f3cc2f5295a58c18625db | refs/heads/master | 2023-08-12T20:36:24.284497 | 2019-05-22T00:55:16 | 2019-05-22T00:55:16 | 187,986,993 | 1 | 0 | MIT | 2020-10-02T01:17:02 | 2019-05-22T07:33:46 | Python | UTF-8 | Python | false | false | 1,204 | py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class P2SVpnProfileParameters(Model):
"""Vpn Client Parameters for package generation.
:param authentication_method: VPN client Authentication Method. Possible
values are: 'EAPTLS' and 'EAPMSCHAPv2'. Possible values include: 'EAPTLS',
'EAPMSCHAPv2'
:type authentication_method: str or
~azure.mgmt.network.v2018_10_01.models.AuthenticationMethod
"""
_attribute_map = {
'authentication_method': {'key': 'authenticationMethod', 'type': 'str'},
}
def __init__(self, *, authentication_method=None, **kwargs) -> None:
super(P2SVpnProfileParameters, self).__init__(**kwargs)
self.authentication_method = authentication_method
| [
"[email protected]"
]
| |
0a76d52c519c2b9ff4438e8567ebfbc0b5e3cb2e | d8f16b24ba0db0abdcecbbce1cffdb2406a0e652 | /onlineshopping/myshopping/migrations/0007_auto_20200310_1644.py | 85939b0c355318b8cf5b90416ea6310e30142333 | []
| no_license | roshan-pokhrel2/djangoecommerce | 5c482221dd8dbd043fa8239345797444a4db2224 | 21b52e33396af9b0e2af338f0dd3186026f40edb | refs/heads/master | 2021-04-04T22:09:58.792737 | 2020-03-20T08:19:38 | 2020-03-20T08:19:38 | 248,493,578 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 471 | py | # Generated by Django 3.0.3 on 2020-03-10 16:44
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('myshopping', '0006_order_orderitem'),
]
operations = [
migrations.RemoveField(
model_name='orderitem',
name='item',
),
migrations.DeleteModel(
name='Order',
),
migrations.DeleteModel(
name='OrderItem',
),
]
| [
"[email protected]"
]
| |
19a3eee629fa47e078d018c096fe5cbfebf9e3ca | 9b527131c291b735a163226d1daac2397c25b712 | /Lecture5/roma_changing_signs.py | c0d266b142cfb3c1ac106e243bb79b49848d36dc | []
| no_license | arnabs542/BigO-Coding-material | dbc8895ec6370933069b2e40e0610d4b05dddcf2 | 3b31bddb1240a407aa22f8eec78956d06b42efbc | refs/heads/master | 2022-03-19T18:32:53.667852 | 2019-11-27T23:55:04 | 2019-11-27T23:55:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 760 | py |
if __name__ == '__main__':
n, k = map(int, input().split())
arr = list(map(int, input().split()))
i = 0
current_sum = 0
done = False
while k > 0:
if arr[i] < 0:
k -= 1
arr[i] *= (-1)
current_sum += arr[i]
elif arr[i] == 0:
k = 0
current_sum += sum(arr[i:])
done = True
else: #arr[i] > 0
if k % 2 == 0:
k = 0
current_sum += sum(arr[i:])
done = True
else: #k odd
k = 0
current_sum = max(current_sum - arr[i-1] + arr[i] - arr[i-1],
current_sum - arr[i])
if i < n-1 and k > 0:
i += 1
else:
break
if k > 0:
if k % 2 != 0:
current_sum -= arr[n-1]
arr[n-1] *= (-1)
current_sum += arr[n-1]
if i <= n-1 and not done:
current_sum += sum(arr[i+1:])
print(current_sum)
| [
"[email protected]"
]
| |
56291aa4a0f783a753deddf4f50d79d3d9595070 | d1f971b9fa0edfa633b62887cf9d173d6a86a440 | /concepts/Exercises/fractions_example.py | 9c1d73c4e52a77b235af4df8a39a46bdb6118ce0 | []
| no_license | papan36125/python_exercises | d45cf434c15aa46e10967c13fbe9658915826478 | 748eed2b19bccf4b5c700075675de87c7c70c46e | refs/heads/master | 2020-04-28T10:01:10.361108 | 2019-05-10T13:45:35 | 2019-05-10T13:45:35 | 175,187,760 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 161 | py | import fractions
# Output: 3/2
print(fractions.Fraction(1.5))
# Output: 5
print(fractions.Fraction(5))
# Output: 1/3
print(fractions.Fraction(1,3))
| [
"[email protected]"
]
| |
02214ea3f8469684440d875077648f0e178654d6 | 4142b8c513d87361da196631f7edd82f11465abb | /python/round690/1462A.py | a873968e7e5d1a7c9aafc73f818dd309e372ef2b | []
| no_license | npkhanhh/codeforces | b52b66780426682ea1a3d72c66aedbe6dc71d7fe | 107acd623b0e99ef0a635dfce3e87041347e36df | refs/heads/master | 2022-02-08T17:01:01.731524 | 2022-02-07T10:29:52 | 2022-02-07T10:29:52 | 228,027,631 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 302 | py | from sys import stdin
for _ in range(int(stdin.readline())):
n = int(stdin.readline())
a = list(map(int, stdin.readline().split()))
res = []
for i in range(n // 2):
res.append(a[i])
res.append(a[-i - 1])
if n % 2 == 1:
res.append(a[n // 2])
print(*res)
| [
"[email protected]"
]
| |
64d8680345a04444e6e646f2a2095d2dc6a64b52 | 256746f29f9995accd4fee35b9b8981264ca2e37 | /Ch05/2017-8-21_2.py | e37173b77da869c3f53193f47a2a80dc66a3786c | []
| no_license | Vagacoder/Python_for_everyone | adadd55561b2200d461afbc1752157ad7326698e | b2a1d1dcbc3cce5499ecc68447e1a04a8e59dc66 | refs/heads/master | 2021-06-22T00:26:02.169461 | 2019-05-25T16:06:04 | 2019-05-25T16:06:04 | 114,508,951 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,016 | py | ## Ch05 P 5.26
def read_digit(code):
bar1 = read_bar(code[0])
bar2 = read_bar(code[1])
bar3 = read_bar(code[2])
bar4 = read_bar(code[3])
bar5 = read_bar(code[4])
number = bar1 * 7 + bar2 * 4 + bar3 * 2 + bar4 * 1 + bar5 * 0
if number == 11:
number = 0
return number
def read_bar(bar):
if bar == '|':return 1
elif bar == ':':return 0
def read_zipcode(zip):
if len(zip) != 32 or zip[0] != '|' or zip[-1] != '|':
return 'Wrong bar code!'
digit1 = read_digit(zip[1:6])
digit2 = read_digit(zip[6:11])
digit3 = read_digit(zip[11:16])
digit4 = read_digit(zip[16:21])
digit5 = read_digit(zip[21:26])
check = read_digit(zip[26:31])
sum = digit1+digit2+digit3+digit4+digit5
if (sum + check) %10 != 0:
return 'Wrong check bar code!'
else:
return str(digit1) + str(digit2) + str(digit3) + str(digit4) + str(digit5)
print(read_zipcode('||:|::::||::::||||::::|:|:::|:||')) | [
"[email protected]"
]
| |
4fcf931f72068f5a92e1405169a021ee2d4e55a8 | 423ba09a145b3468a322acf4ddf7d2c2446e227d | /atcoder/nikkei2019-qual/nikkei2019-qual_a.py | 618827da3e3942e1cc9d874f950210e5c318784a | []
| no_license | hirosuzuki/procon | 13d3bc332d6e4368fd54fec742b32b09729658ed | 533f40e13456542b202905a61814ad926c3c206e | refs/heads/master | 2021-05-12T10:42:51.920561 | 2020-05-20T15:49:05 | 2020-05-20T15:49:05 | 117,356,746 | 0 | 0 | null | 2018-01-29T14:46:28 | 2018-01-13T15:56:40 | Python | UTF-8 | Python | false | false | 81 | py | N, A, B = [int(_) for _ in input().split()]
print(min(A, B), max(A + B - N, 0))
| [
"[email protected]"
]
| |
3bfd0f28ba277e393000a71c1308dee534790150 | d57148c74b79954ff762ce3a02c1b0ef3e79d6a1 | /libs/smartmeshsdk-REL-1.3.0.1/libs/VManagerSDK/vmanager/models/user_list_element.py | bcb914e1417f2a8286c6556ef01fbd45bcd0d182 | [
"BSD-3-Clause"
]
| permissive | realms-team/solmanager | 62fb748b140361cf620b7dd8ff6df755afd42bbe | 95fa049df041add5f8d37c053ef560d0e5d06dff | refs/heads/master | 2020-04-11T10:00:21.086457 | 2018-11-20T15:49:27 | 2018-11-20T15:49:27 | 40,271,406 | 0 | 0 | BSD-3-Clause | 2018-11-20T15:49:28 | 2015-08-05T22:15:39 | Python | UTF-8 | Python | false | false | 3,057 | py | # coding: utf-8
"""
Copyright 2015 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Ref: https://github.com/swagger-api/swagger-codegen
"""
from pprint import pformat
from six import iteritems
class UserListElement(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
"""
UserListElement - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'user_id': 'str'
}
self.attribute_map = {
'user_id': 'userId'
}
self._user_id = None
@property
def user_id(self):
"""
Gets the user_id of this UserListElement.
User identifier
:return: The user_id of this UserListElement.
:rtype: str
"""
return self._user_id
@user_id.setter
def user_id(self, user_id):
"""
Sets the user_id of this UserListElement.
User identifier
:param user_id: The user_id of this UserListElement.
:type: str
"""
self._user_id = user_id
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
| [
"[email protected]"
]
| |
d6bf95c21fddc999194bb12a05edb9c1c0d457aa | 2ed6e49f6bb841a36f51e7562a71788682f2f282 | /backend/backend/git_utils.py | 56837bde860f73ea789a3c21d8e06a4b3571e8bf | [
"Apache-2.0",
"MIT",
"CC-BY-4.0"
]
| permissive | arthur-flam/qaboard | 7fcaf3c351bd94d457dd14b9f9c6793a583d6841 | 7a11c3c2279595f87bc113c7d383d11241d83946 | refs/heads/master | 2022-10-07T13:55:13.356189 | 2020-06-05T07:07:05 | 2020-06-05T07:07:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,173 | py | from git import Repo
from git import RemoteProgress
from git.exc import NoSuchPathError
class Repos():
"""Holds data for multiple repositories."""
def __init__(self, git_server, clone_directory):
self._repos = {}
self.git_server = git_server
self.clone_directory = clone_directory
def __getitem__(self, project_path):
"""
Return a git-python Repo object representing a clone
of $QABOARD_GIT_SERVER/project_path at $QABOARD_DATA
project_path: the full git repository namespace, eg dvs/psp_swip
"""
clone_location = str(self.clone_directory / project_path)
try:
repo = Repo(clone_location)
except NoSuchPathError:
try:
print(f'Cloning <{project_path}> to {self.clone_directory}')
repo = Repo.clone_from(
# for now we expect everything to be on gitlab-srv via http
f'git@{self.git_server}:{project_path}',
str(clone_location)
)
except Exception as e:
print(f'[ERROR] Could not clone: {e}. Please set $QABOARD_DATA to a writable location and verify your network settings')
raise(e)
self._repos[project_path] = repo
return self._repos[project_path]
def git_pull(repo):
"""Updates the repo and warms the cache listing the latests commits.."""
class MyProgressPrinter(RemoteProgress):
def update(self, op_code, cur_count, max_count=100.0, message="[No message]"):
# print('...')
# print(op_code, cur_count, max_count, (cur_count or 0)/max_count, message)
pass
try:
for fetch_info in repo.remotes.origin.fetch(progress=MyProgressPrinter()):
# print(f"Updated {fetch_info.ref} to {fetch_info.commit}")
pass
except Exception as e:
print(e)
def find_branch(commit_hash, repo):
"""Tries to get from which branch a commit comes from. It's a *guess*."""
std_out = repo.git.branch(contains=commit_hash, remotes=True)
branches = [l.split(' ')[-1] for l in std_out.splitlines()]
important_branches = ['origin/release', 'origin/master', 'origin/develop']
for b in important_branches:
if b in branches:
return b
if branches:
return branches[0]
return 'unknown' | [
"[email protected]"
]
| |
9254d9688bf09016bb2da20222a8382e55e09309 | 22d4bdff084db5becb8c76d5d8c3ce6ea095d3d8 | /tcapy/vis/computationresults.py | a9064c413d1e8b0f07ce94559ac9eeb040c73b7c | [
"Apache-2.0"
]
| permissive | sbnair/tcapy | 1768220657bdd4d3bdc0f2e8248e971c76ed4953 | 380d49139d7af9fd4cf63d406029833c9a41cc70 | refs/heads/master | 2021-05-17T14:13:22.206884 | 2020-03-27T17:10:06 | 2020-03-27T17:10:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,549 | py | from __future__ import print_function
__author__ = 'saeedamen' # Saeed Amen / [email protected]
#
# Copyright 2018 Cuemacro Ltd. - http//www.cuemacro.com / @cuemacro
#
# See the License for the specific language governing permissions and limitations under the License.
#
import abc
from tcapy.util.utilfunc import UtilFunc
from tcapy.vis.displaylisteners import PlotRender
ABC = abc.ABCMeta('ABC', (object,), {'__slots__': ()})
class ComputationResults(ABC):
"""Abstract class holds the results of a computation in a friendly format, splitting out the various dataset which can be used
for charts. Also converts these datasets to Plotly Figure objects, ready to be plotted in HTML documents.
"""
def __init__(self, dict_of_df, computation_request, text_preamble=''):
self._plot_render = PlotRender()
self._util_func = UtilFunc()
self.text_preamble = text_preamble
self._computation_request = computation_request
self._rendered = False
@abc.abstractmethod
def render_computation_charts(self):
"""Takes the various dataframes computation results output, and then renders these as Plotly JSON charts (data and
all their graphical properties), which are easy to plot later.
Returns
-------
"""
pass
##### Other data (eg. text)
@property
def text_preamble(self):
return self.__text_preamble
@text_preamble.setter
def text_preamble(self, text_preamble):
self.__text_preamble = text_preamble | [
"[email protected]"
]
| |
a74d2f981d3af22b80dfd2637fd66240f655a8e6 | 96dcea595e7c16cec07b3f649afd65f3660a0bad | /tests/components/mysensors/test_light.py | 8d4ce445779881be401c869f41257377a2583ea5 | [
"Apache-2.0"
]
| permissive | home-assistant/core | 3455eac2e9d925c92d30178643b1aaccf3a6484f | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | refs/heads/dev | 2023-08-31T15:41:06.299469 | 2023-08-31T14:50:53 | 2023-08-31T14:50:53 | 12,888,993 | 35,501 | 20,617 | Apache-2.0 | 2023-09-14T21:50:15 | 2013-09-17T07:29:48 | Python | UTF-8 | Python | false | false | 8,086 | py | """Provide tests for mysensors light platform."""
from __future__ import annotations
from collections.abc import Callable
from unittest.mock import MagicMock, call
from mysensors.sensor import Sensor
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_RGB_COLOR,
ATTR_RGBW_COLOR,
DOMAIN as LIGHT_DOMAIN,
)
from homeassistant.core import HomeAssistant
async def test_dimmer_node(
hass: HomeAssistant,
dimmer_node: Sensor,
receive_message: Callable[[str], None],
transport_write: MagicMock,
) -> None:
"""Test a dimmer node."""
entity_id = "light.dimmer_node_1_1"
state = hass.states.get(entity_id)
assert state
assert state.state == "off"
# Test turn on
await hass.services.async_call(
LIGHT_DOMAIN,
"turn_on",
{"entity_id": entity_id},
blocking=True,
)
assert transport_write.call_count == 1
assert transport_write.call_args == call("1;1;1;1;2;1\n")
receive_message("1;1;1;0;2;1\n")
receive_message("1;1;1;0;3;100\n")
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == "on"
assert state.attributes[ATTR_BRIGHTNESS] == 255
transport_write.reset_mock()
# Test turn on brightness
await hass.services.async_call(
LIGHT_DOMAIN,
"turn_on",
{"entity_id": entity_id, "brightness": 128},
blocking=True,
)
assert transport_write.call_count == 1
assert transport_write.call_args == call("1;1;1;1;3;50\n")
receive_message("1;1;1;0;2;1\n")
receive_message("1;1;1;0;3;50\n")
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == "on"
assert state.attributes[ATTR_BRIGHTNESS] == 128
transport_write.reset_mock()
# Test turn off
await hass.services.async_call(
LIGHT_DOMAIN,
"turn_off",
{"entity_id": entity_id},
blocking=True,
)
assert transport_write.call_count == 1
assert transport_write.call_args == call("1;1;1;1;2;0\n")
receive_message("1;1;1;0;2;0\n")
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == "off"
async def test_rgb_node(
hass: HomeAssistant,
rgb_node: Sensor,
receive_message: Callable[[str], None],
transport_write: MagicMock,
) -> None:
"""Test a rgb node."""
entity_id = "light.rgb_node_1_1"
state = hass.states.get(entity_id)
assert state
assert state.state == "off"
# Test turn on
await hass.services.async_call(
LIGHT_DOMAIN,
"turn_on",
{"entity_id": entity_id},
blocking=True,
)
assert transport_write.call_count == 1
assert transport_write.call_args == call("1;1;1;1;2;1\n")
receive_message("1;1;1;0;2;1\n")
receive_message("1;1;1;0;3;100\n")
receive_message("1;1;1;0;40;ffffff\n")
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == "on"
assert state.attributes[ATTR_BRIGHTNESS] == 255
assert state.attributes[ATTR_RGB_COLOR] == (255, 255, 255)
transport_write.reset_mock()
# Test turn on brightness
await hass.services.async_call(
LIGHT_DOMAIN,
"turn_on",
{"entity_id": entity_id, "brightness": 128},
blocking=True,
)
assert transport_write.call_count == 1
assert transport_write.call_args == call("1;1;1;1;3;50\n")
receive_message("1;1;1;0;2;1\n")
receive_message("1;1;1;0;3;50\n")
receive_message("1;1;1;0;40;ffffff\n")
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == "on"
assert state.attributes[ATTR_BRIGHTNESS] == 128
assert state.attributes[ATTR_RGB_COLOR] == (255, 255, 255)
transport_write.reset_mock()
# Test turn off
await hass.services.async_call(
LIGHT_DOMAIN,
"turn_off",
{"entity_id": entity_id},
blocking=True,
)
assert transport_write.call_count == 1
assert transport_write.call_args == call("1;1;1;1;2;0\n")
receive_message("1;1;1;0;2;0\n")
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == "off"
transport_write.reset_mock()
# Test turn on rgb
await hass.services.async_call(
LIGHT_DOMAIN,
"turn_on",
{"entity_id": entity_id, ATTR_RGB_COLOR: (255, 0, 0)},
blocking=True,
)
assert transport_write.call_count == 2
assert transport_write.call_args_list[0] == call("1;1;1;1;2;1\n")
assert transport_write.call_args_list[1] == call("1;1;1;1;40;ff0000\n")
receive_message("1;1;1;0;2;1\n")
receive_message("1;1;1;0;3;50\n")
receive_message("1;1;1;0;40;ff0000\n")
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == "on"
assert state.attributes[ATTR_BRIGHTNESS] == 128
assert state.attributes[ATTR_RGB_COLOR] == (255, 0, 0)
async def test_rgbw_node(
hass: HomeAssistant,
rgbw_node: Sensor,
receive_message: Callable[[str], None],
transport_write: MagicMock,
) -> None:
"""Test a rgbw node."""
entity_id = "light.rgbw_node_1_1"
state = hass.states.get(entity_id)
assert state
assert state.state == "off"
# Test turn on
await hass.services.async_call(
LIGHT_DOMAIN,
"turn_on",
{"entity_id": entity_id},
blocking=True,
)
assert transport_write.call_count == 1
assert transport_write.call_args == call("1;1;1;1;2;1\n")
receive_message("1;1;1;0;2;1\n")
receive_message("1;1;1;0;3;100\n")
receive_message("1;1;1;0;41;ffffffff\n")
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == "on"
assert state.attributes[ATTR_BRIGHTNESS] == 255
assert state.attributes[ATTR_RGBW_COLOR] == (255, 255, 255, 255)
transport_write.reset_mock()
# Test turn on brightness
await hass.services.async_call(
LIGHT_DOMAIN,
"turn_on",
{"entity_id": entity_id, "brightness": 128},
blocking=True,
)
assert transport_write.call_count == 1
assert transport_write.call_args == call("1;1;1;1;3;50\n")
receive_message("1;1;1;0;2;1\n")
receive_message("1;1;1;0;3;50\n")
receive_message("1;1;1;0;41;ffffffff\n")
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == "on"
assert state.attributes[ATTR_BRIGHTNESS] == 128
assert state.attributes[ATTR_RGBW_COLOR] == (255, 255, 255, 255)
transport_write.reset_mock()
# Test turn off
await hass.services.async_call(
LIGHT_DOMAIN,
"turn_off",
{"entity_id": entity_id},
blocking=True,
)
assert transport_write.call_count == 1
assert transport_write.call_args == call("1;1;1;1;2;0\n")
receive_message("1;1;1;0;2;0\n")
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == "off"
transport_write.reset_mock()
# Test turn on rgbw
await hass.services.async_call(
LIGHT_DOMAIN,
"turn_on",
{"entity_id": entity_id, ATTR_RGBW_COLOR: (255, 0, 0, 0)},
blocking=True,
)
assert transport_write.call_count == 2
assert transport_write.call_args_list[0] == call("1;1;1;1;2;1\n")
assert transport_write.call_args_list[1] == call("1;1;1;1;41;ff000000\n")
receive_message("1;1;1;0;2;1\n")
receive_message("1;1;1;0;3;50\n")
receive_message("1;1;1;0;41;ff000000\n")
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == "on"
assert state.attributes[ATTR_BRIGHTNESS] == 128
assert state.attributes[ATTR_RGBW_COLOR] == (255, 0, 0, 0)
| [
"[email protected]"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.