Python types.SimpleNamespace() Examples
The following are 30
code examples of types.SimpleNamespace().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
types
, or try the search function
.
Example #1
Source File: hetero_nn_param.py From FATE with Apache License 2.0 | 6 votes |
def _parse_optimizer(opt): """ Examples: 1. "optimize": "SGD" 2. "optimize": { "optimizer": "SGD", "learning_rate": 0.05 } """ kwargs = {} if isinstance(opt, str): return SimpleNamespace(optimizer=opt, kwargs=kwargs) elif isinstance(opt, dict): optimizer = opt.get("optimizer", kwargs) if not optimizer: raise ValueError(f"optimizer config: {opt} invalid") kwargs = {k: v for k, v in opt.items() if k != "optimizer"} return SimpleNamespace(optimizer=optimizer, kwargs=kwargs) else: raise ValueError(f"invalid type for optimize: {type(opt)}")
Example #2
Source File: test_standarddir.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
def test_exists_race_condition(self, mocker, tmpdir, typ): """Make sure there can't be a TOCTOU issue when creating the file. See https://github.com/qutebrowser/qutebrowser/issues/942. """ (tmpdir / typ).ensure(dir=True) m = mocker.patch('qutebrowser.utils.standarddir.os') m.makedirs = os.makedirs m.sep = os.sep m.path.join = os.path.join m.expanduser = os.path.expanduser m.path.exists.return_value = False m.path.abspath = lambda x: x args = types.SimpleNamespace(basedir=str(tmpdir)) standarddir._init_dirs(args) func = getattr(standarddir, typ) func()
Example #3
Source File: general_mf_param.py From FATE with Apache License 2.0 | 6 votes |
def _parse_early_stop(self, param): """ Examples: "early_stop": { "early_stop": "diff", "eps": 0.0001 } """ default_eps = 0.0001 if isinstance(param, dict): early_stop = param.get("early_stop", None) eps = param.get("eps", default_eps) if not early_stop: raise ValueError(f"early_stop config: {param} invalid") return SimpleNamespace(converge_func=early_stop, eps=eps) else: raise ValueError(f"invalid type for early_stop: {type(param)}")
Example #4
Source File: fontList.py From fontgoggles with Apache License 2.0 | 6 votes |
def getColors(self): appearanceName = AppKit.NSAppearance.currentAppearance().name() if appearanceName != self._lastAppearanceName: self._lastAppearanceName = appearanceName colors = SimpleNamespace() colors.foregroundColor = AppKit.NSColor.textColor() colors.selectedColor = colors.foregroundColor.blendedColorWithFraction_ofColor_( 0.9, AppKit.NSColor.systemRedColor()) colors.selectedSpaceColor = colors.selectedColor.colorWithAlphaComponent_(0.2) colors.hoverColor = AppKit.NSColor.systemBlueColor() colors.hoverSelectedColor = colors.hoverColor.blendedColorWithFraction_ofColor_( 0.5, colors.selectedColor) colors.hoverSpaceColor = colors.hoverColor.colorWithAlphaComponent_(0.2) colors.hoverSelectedSpaceColor = colors.hoverSelectedColor.colorWithAlphaComponent_(0.2) self._colors = colors return self._colors
Example #5
Source File: svd_param.py From FATE with Apache License 2.0 | 6 votes |
def _parse_optimizer(self, param): """ Examples: "optimize": { "optimizer": "SGD", "learning_rate": 0.05 } """ kwargs = {} if isinstance(param, str): return SimpleNamespace(optimizer=param, kwargs=kwargs) elif isinstance(param, dict): optimizer = param.get("optimizer", kwargs) if not optimizer: raise ValueError(f"optimizer config: {param} invalid") kwargs = {k: v for k, v in param.items() if k != "optimizer"} return SimpleNamespace(optimizer=optimizer, kwargs=kwargs) else: raise ValueError(f"invalid type for optimize: {type(param)}")
Example #6
Source File: test_standarddir.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
def test_basedir(self, tmpdir, typ): """Test --basedir.""" basedir = tmpdir / 'basedir' assert not basedir.exists() args = types.SimpleNamespace(basedir=str(basedir)) standarddir._init_dirs(args) func = getattr(standarddir, typ) func() assert basedir.exists() if typ == 'download' or (typ == 'runtime' and not utils.is_linux): assert not (basedir / typ).exists() else: assert (basedir / typ).exists() if utils.is_posix: assert (basedir / typ).stat().mode & 0o777 == 0o700
Example #7
Source File: matrix_factorization_param.py From FATE with Apache License 2.0 | 6 votes |
def _parse_early_stop(self, param): """ Examples: 1. "early_stop": "diff" 2. "early_stop": { "early_stop": "diff", "eps": 0.0001 } """ default_eps = 0.0001 if isinstance(param, str): return SimpleNamespace(converge_func=param, eps=default_eps) if isinstance(param, dict): early_stop = param.get("early_stop", None) eps = param.get("eps", default_eps) if not early_stop: raise ValueError(f"early_stop config: {param} invalid") return SimpleNamespace(converge_func=early_stop, eps=eps) else: raise ValueError(f"invalid type for early_stop: {type(param)}")
Example #8
Source File: matrix_factorization_param.py From FATE with Apache License 2.0 | 6 votes |
def _parse_optimizer(self, param): """ Examples: 1. "optimize": "SGD" 2. "optimize": { "optimizer": "SGD", "learning_rate": 0.05 } """ kwargs = {} if isinstance(param, str): return SimpleNamespace(optimizer=param, kwargs=kwargs) elif isinstance(param, dict): optimizer = param.get("optimizer", kwargs) if not optimizer: raise ValueError(f"optimizer config: {param} invalid") kwargs = {k: v for k, v in param.items() if k != "optimizer"} return SimpleNamespace(optimizer=optimizer, kwargs=kwargs) else: raise ValueError(f"invalid type for optimize: {type(param)}")
Example #9
Source File: test_version.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
def _do_import(self, name): """Helper for fake_import and fake_importlib_import to do the work. Return: The imported fake module, or None if normal importing should be used. """ if name not in self.modules: # Not one of the modules to test -> use real import return None elif self.modules[name]: ns = types.SimpleNamespace() if self.version_attribute is not None: setattr(ns, self.version_attribute, self.version) return ns else: raise ImportError("Fake ImportError for {}.".format(name))
Example #10
Source File: __init__.py From fontgoggles with Apache License 2.0 | 6 votes |
def getSortInfoUFO(fontPath: PathLike, fontNum: int): from fontTools.ufoLib import UFOReader assert fontNum == 0 suffix = fontPath.suffix.lower().lstrip(".") reader = UFOReader(fontPath, validate=False) info = SimpleNamespace() reader.readInfo(info) sortInfo = dict(suffix=suffix) ufoAttrs = [ ("familyName", "familyName"), ("styleName", "styleName"), ("weight", "openTypeOS2WeightClass"), ("width", "openTypeOS2WidthClass"), ("italicAngle", "italicAngle"), ] for key, attr in ufoAttrs: val = getattr(info, attr, None) if val is not None: if key == "italicAngle": val = -val # negative for intuitive sort order sortInfo[key] = val return sortInfo
Example #11
Source File: svdpp_param.py From FATE with Apache License 2.0 | 6 votes |
def _parse_early_stop(self, param): """ Examples: "early_stop": { "early_stop": "diff", "eps": 0.0001 } """ default_eps = 0.0001 if isinstance(param, dict): early_stop = param.get("early_stop", None) eps = param.get("eps", default_eps) if not early_stop: raise ValueError(f"early_stop config: {param} invalid") return SimpleNamespace(converge_func=early_stop, eps=eps) else: raise ValueError(f"invalid type for early_stop: {type(param)}")
Example #12
Source File: ufoFont.py From fontgoggles with Apache License 2.0 | 6 votes |
def load(self, outputWriter): if hasattr(self, "reader"): self._cachedGlyphs = {} return self._setupReaderAndGlyphSet() self.info = SimpleNamespace() self.reader.readInfo(self.info) self.lib = self.reader.readLib() self._cachedGlyphs = {} if self.ufoState is None: includedFeatureFiles = extractIncludedFeatureFiles(self.fontPath, self.reader) self.ufoState = UFOState(self.reader, self.glyphSet, getUnicodesAndAnchors=self._getUnicodesAndAnchors, includedFeatureFiles=includedFeatureFiles) fontData = await compileUFOToBytes(self.fontPath, outputWriter) f = io.BytesIO(fontData) self.ttFont = TTFont(f, lazy=True) self.shaper = self._getShaper(fontData)
Example #13
Source File: polar.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 6 votes |
def start_pan(self, x, y, button): angle = np.deg2rad(self.get_rlabel_position()) mode = '' if button == 1: epsilon = np.pi / 45.0 t, r = self.transData.inverted().transform_point((x, y)) if angle - epsilon <= t <= angle + epsilon: mode = 'drag_r_labels' elif button == 3: mode = 'zoom' self._pan_start = types.SimpleNamespace( rmax=self.get_rmax(), trans=self.transData.frozen(), trans_inverse=self.transData.inverted().frozen(), r_label_angle=self.get_rlabel_position(), x=x, y=y, mode=mode)
Example #14
Source File: episode_buffer.py From mackrl with Apache License 2.0 | 6 votes |
def __init__(self, data_scheme, n_bs, n_t, n_agents, is_cuda=False, is_shared_mem=False, sizes=None): self.n_agents = n_agents self._data_scheme = data_scheme self._n_bs = n_bs self._n_t = n_t self.is_cuda = is_cuda self.is_shared_mem = is_shared_mem self.data = SN() self.columns = SN() self._setup_data(self._data_scheme, sizes, self._n_bs, self._n_t) self.seq_lens = [0 for _ in range(len(self))] self.format = "bs" # this is ALWAYS the order of contiguous batch histories pass
Example #15
Source File: google_auth.py From kubernetes_asyncio with Apache License 2.0 | 6 votes |
def google_auth_credentials(provider): if 'cmd-path' not in provider or 'cmd-args' not in provider: raise ValueError('GoogleAuth via gcloud is supported! Values for cmd-path, cmd-args are required.') cmd = shlex.split(' '.join((provider['cmd-path'], provider['cmd-args']))) cmd_exec = asyncio.create_subprocess_exec(*cmd, stdin=None, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) proc = await cmd_exec data = await proc.stdout.read() data = data.decode('ascii').rstrip() data = json.loads(data) await proc.wait() return SimpleNamespace( token=data['credential']['access_token'], expiry=data['credential']['token_expiry'] )
Example #16
Source File: dense_model.py From FATE with Apache License 2.0 | 6 votes |
def build(self, input_shape=None, layer_config=None, model_builder=None, restore_stage=False): if not input_shape: if self.role == "host": raise ValueError("host input is empty!") else: self.is_empty_model = True return self.model_builder = model_builder self.layer_config = layer_config self.model = model_builder(input_shape=input_shape, nn_define=layer_config, optimizer=SimpleNamespace(optimizer="SGD", kwargs={}), loss="keep_predict_loss", metrics=None) dense_layer = self.model.get_layer_by_index(0) if not restore_stage: self._init_model_weight(dense_layer) if self.role == "host": self.activation_func = dense_layer.activation self.__build_activation_layer_gradients_func(dense_layer)
Example #17
Source File: homo_nn_param.py From FATE with Apache License 2.0 | 6 votes |
def _parse_early_stop(param): """ Examples: 1. "early_stop": "diff" 2. "early_stop": { "early_stop": "diff", "eps": 0.0001 } """ default_eps = 0.0001 if isinstance(param, str): return SimpleNamespace(converge_func=param, eps=default_eps) elif isinstance(param, dict): early_stop = param.get("early_stop", None) eps = param.get("eps", default_eps) if not early_stop: raise ValueError(f"early_stop config: {param} invalid") return SimpleNamespace(converge_func=early_stop, eps=eps) else: raise ValueError(f"invalid type for early_stop: {type(param)}")
Example #18
Source File: homo_nn_param.py From FATE with Apache License 2.0 | 6 votes |
def _parse_optimizer(param): """ Examples: 1. "optimize": "SGD" 2. "optimize": { "optimizer": "SGD", "learning_rate": 0.05 } """ kwargs = {} if isinstance(param, str): return SimpleNamespace(optimizer=param, kwargs=kwargs) elif isinstance(param, dict): optimizer = param.get("optimizer", kwargs) if not optimizer: raise ValueError(f"optimizer config: {param} invalid") kwargs = {k: v for k, v in param.items() if k != "optimizer"} return SimpleNamespace(optimizer=optimizer, kwargs=kwargs) else: raise ValueError(f"invalid type for optimize: {type(param)}")
Example #19
Source File: playlist.py From VLC-Scheduler with MIT License | 6 votes |
def prepare_source(self, source): prepared = types.SimpleNamespace( active=True, path=source['path'], shuffle=bool(source.get('shuffle', False)), recursive=bool(source.get('recursive', self._recursive)), item_play_duration=int(source.get('item_play_duration', 0)), play_every_minutes=int(source.get('play_every_minutes', 0)), start_time=None, end_time=None ) if source.get('playing_time'): prepared.start_time, prepared.end_time = ( datetime.datetime.strptime(i, '%H:%M').time() for i in utils.parse_time_interval(source['playing_time']) ) return prepared
Example #20
Source File: kube_config_test.py From kubernetes_asyncio with Apache License 2.0 | 6 votes |
def test_async_load_gcp_token_with_refresh(self): async def cred(): return SimpleNamespace( token=TEST_ANOTHER_DATA_BASE64, expiry=datetime.datetime.now() ) loader = KubeConfigLoader( config_dict=self.TEST_KUBE_CONFIG, active_context="expired_gcp", get_google_credentials=cred) res = await loader.load_gcp_token() self.assertTrue(res) self.assertEqual(BEARER_TOKEN_FORMAT % TEST_ANOTHER_DATA_BASE64, loader.token)
Example #21
Source File: test_analyze_run_result.py From benchexec with Apache License 2.0 | 6 votes |
def create_run(self, info_result=RESULT_UNKNOWN): runSet = types.SimpleNamespace() runSet.log_folder = "." runSet.result_files_folder = "." runSet.options = [] runSet.real_name = None runSet.propertytag = None runSet.benchmark = lambda: None runSet.benchmark.base_dir = "." runSet.benchmark.benchmark_file = "Test.xml" runSet.benchmark.columns = [] runSet.benchmark.name = "Test" runSet.benchmark.instance = "Test" runSet.benchmark.rlimits = {} runSet.benchmark.tool = BaseTool() def determine_result(self, returncode, returnsignal, output, isTimeout=False): return info_result runSet.benchmark.tool.determine_result = determine_result return Run( identifier="test.c", sourcefiles=["test.c"], fileOptions=[], runSet=runSet )
Example #22
Source File: conftest.py From torf with GNU General Public License v3.0 | 6 votes |
def singlefile_content(tmp_path_factory): random.seed(0) # Make sure random file names and content are identical every time content_path = _mktempdir(tmp_path_factory) filepath = _generate_random_file(content_path, filename='sinģle fíle') random.seed() # Re-enable randomness exp_pieces = b'\xc8\xfa\x0fV\x95\xecl\x97t\xb2v\x84S\x98{\x92[ \x13\xe5\x04\xef-\xb0;sF\xc2\x93W\xcf\xc6X\x14\x9b]_r\xfb\x80\'}\xe5\xc4\x05\xdct\xb5^\xe9\x7f0b|\xc9\xf1\x9d\xd7G\x06 ,l8m\x01\xbf2\xf6:\x03r-\x8d\x1f,\x8bk:\xad\xdbN\xa2V\x96/\xf2@w\xa5\x98\xf8\t3fU\x13;\x90\xc0F\xe3[\x15\xea\x8f\x92\xcdN:\xc1\x0fG\x9b\xeb\xd9\x93A\xca\xa7L\xd2\x9ef|\xddd\xd4\x94.f\xee\xea3\xa8\x04|\xe9h\xa7\xa1t\xa2\xb5\xb3*\x89\xf7\x14\xdf\x16M/\xc6\xa5\x85\xdaF\xca\xa7?\x9d\xe1zd\xc8\xe1\x1d\x1epC\x06+\xe1Q\x0fi\x9fv\x19\xa2(\xd0\x90\xb3\xb0\xcf\xa9\x1cy\xf0\x96\x17\n\x05\xa5*IZJ\x8c\xbb\x87\xdd\xed|d.\xf0\xb9\xfe\x00\xa6\nufY\x18\xe35\xee\xdf\xa6D\xed<\xc5W\x0fa\x80\xc6}\xdd\xf4\xbd\xc1:\xe3\xda\nj\xbag\x93\xd0\xdc\xbd\xb8\xfb\xc2\x99\x9a/&\x1d\xf3\xe9\xa3,\x9b>\'\xa5\xaa~\xabb\x81\x88\x80^\xddd\xc7\xea\x83n\x05%\x8f4\x8a\x82\xe2\xff[\xab\xa8\x92\x1f\xaarG\xc5\x00\xcae\x9e\x93\xc4\x9015\x02\xe7\x8a\xb1I\xa6\x16DF\x8a\x0b\xeb\xca@\th?WL\xe0Vf\xc9X>##?t\x08\xdf[\xac\x16\x7f\xe9\x1a\xc4\x11\x0c\xc9\xac?\xded\xed\xf5\x1b\xd0Qq\x90_\x88]\xbf\xb7\xbc\xf5\x8et4f<\x14\xb6\x98\xbb\xdd0H\x14\xfaZ\xc1\x07l3\xd6""l\x99X@\xb7\x9c\xbc/h\xe9\xc0\x83\x0e\xfb\x91\x83\xdf\x1d+\xf6\xd1_\xb8\x04\xdd\xb8\x05\'\x1c\x1b\x94\x1cl\x9a_[An:\xcdw\xe8\xfb\xbf\xb9\x82olQ6<U\r\x9e0/\x89\xc6\xe4\x9cl<\xd5\xf9\xca\x96\x01\xd5\xc3\x1dk\x1b1\xc2X\xe9\x164\x9d\x05\x19\x85c\x0e\x847b\xdb[\xa8\x8e\xc1\x04,\x1c\xc2\x0e\x85`+3\xb1\xe6\xac&F\xb9\xf6\x0e\\\x1fS\xbd\xed\xc6l\x89\x18\x8eI?\x9aqR1&k\x14ce i\xb4;C\xfe\x1dh\xe4\xd3>\xa4\x15\x9f\xd2c#\x1b\x9a\xb6\x84\x88@\x89\xdd\x01\x18H\xbce\rK1aS\xd8\xb8\xffD\x9f\x89\xd4\xb59y7\xff\x8b\xc1\xc3\t\xdd\x9e\xa6\xa7\x02:\xa5\xea<\xb9\x95\xd7ePU~\xbc\x16\x9a\x0f\xb1h\xad4\xfa\x18yv\x95\x96\x0cRo\x88\xe6L\x08\xfd\x94gh\x92\'w\xb3\xd1BCqC\x12_\x1f\x92\xfc\xc6\xfd\t\xcd\xab\xe0\xbd\xcc\x06\xf9\xa7\xb1e\xa9\xbe\x0c\x8d\xfcI\x00\x0e\xd7\xbe\x0c&\xf2\xc5\xa5Yl\xf8\xc0\x8e.\x97\x0c\xd5zp~8\xc0g\xa6C\x16\xd0v\x1e\xa1\xa37\xceM[\xd6\x18\xc6\xa5\xc9\xbc\x11\x99\xc4\xe9\x0f9\xab\x98\x01\xaf\xe22\n_\x83\x9b\xdegG\xb4#\xd6\x17\xf1z4\x11v\xef\xcf!\x03\xdc\x14_\x9e;\'\xdckvHh\xd5x\xf48\xdaFa\xae\x02\xf0\x16| \xa3\x97\xe5\xed\xf6\x11$\xe4\xacb\xaf\x8a\x07fH\x96\x00\x00\x98\x87(\x97\xcd!\xff\xf8a\x02\xc4\xca\xff\xef\xe1P\x01_\x9b\x9b\x83:\x7f\xdd\x92\xfb\xe9\x94\xc3SEWh\x18\xb3\x9c\xd8\xf9M\x1d!\xd25\xcb' exp_metainfo = {'announce' : 'http://localhost:123', 'created by' : 'mktorrent 1.0', 'creation date' : 1513522263, 'info': {'name' : os.path.basename(filepath), 'piece length' : 2**14, 'pieces' : exp_pieces, 'length' : os.path.getsize(filepath)}} exp_attrs = SimpleNamespace(path=str(filepath), infohash='7febf5a5a6e6bac79df2eb4340a63009109fecd5', infohash_base32=b'P7V7LJNG425MPHPS5NBUBJRQBEIJ73GV', size=os.path.getsize(filepath), pieces=math.ceil(os.path.getsize(filepath) / exp_metainfo['info']['piece length'])) return SimpleNamespace(path=exp_attrs.path, exp_metainfo=exp_metainfo, exp_attrs=exp_attrs)
Example #23
Source File: _base.py From Mastering-Elasticsearch-7.0 with MIT License | 6 votes |
def start_pan(self, x, y, button): """ Called when a pan operation has started. *x*, *y* are the mouse coordinates in display coords. button is the mouse button number: * 1: LEFT * 2: MIDDLE * 3: RIGHT .. note:: Intended to be overridden by new projection types. """ self._pan_start = types.SimpleNamespace( lim=self.viewLim.frozen(), trans=self.transData.frozen(), trans_inverse=self.transData.inverted().frozen(), bbox=self.bbox.frozen(), x=x, y=y)
Example #24
Source File: test_sapp.py From geo-br with GNU General Public License v3.0 | 6 votes |
def test_cities(self): print ("running test_cities...") with gzip.open('data.json.gz', 'rb') as db: cities = json.load(db) states = set() errors, count = 0, 0 for city in cities: c = SimpleNamespace(**city) states.add(c.uf) r = sapp._search(c.latitude, c.longitude) if r is None: errors += 1 else: if r["found"]: if c.nome_municipio == r["city"] and c.uf == r["state"]: count += 1 else: errors += 1 else: errors += 1 self.assertTrue(errors==0) self.assertTrue(count==5540) self.assertTrue(len(states)==27)
Example #25
Source File: test_sapp.py From geo-br with GNU General Public License v3.0 | 6 votes |
def test_capitals(self): print ("running test_capitals...") with gzip.open('capitais.json.gz', 'rb') as db: all_capitals = json.load(db) with gzip.open('data.json.gz', 'rb') as db: cities = json.load(db) cities = [x for x in cities if x['capital']] found = [] for capital in all_capitals: c = SimpleNamespace(**capital) for city in cities: d = SimpleNamespace(**city) if({d.nome_municipio, d.uf, d.estado} & {c.capital, c.sigla, c.estado}): found.append(capital) break self.assertTrue(len(found)==27)
Example #26
Source File: _base.py From GraphicDesignPatternByPython with MIT License | 6 votes |
def start_pan(self, x, y, button): """ Called when a pan operation has started. *x*, *y* are the mouse coordinates in display coords. button is the mouse button number: * 1: LEFT * 2: MIDDLE * 3: RIGHT .. note:: Intended to be overridden by new projection types. """ self._pan_start = types.SimpleNamespace( lim=self.viewLim.frozen(), trans=self.transData.frozen(), trans_inverse=self.transData.inverted().frozen(), bbox=self.bbox.frozen(), x=x, y=y)
Example #27
Source File: interactive_game.py From safelife with Apache License 2.0 | 6 votes |
def __init__(self, level_generator): self.level_generator = level_generator self.state = SimpleNamespace( screen="INTRO", game=None, total_points=0, total_steps=0, total_safety_score=0, level_start_steps=0, level_start_points=0, total_undos=0, edit_mode=0, history=deque(maxlen=MAX_HISTORY_LENGTH), side_effects=None, total_side_effects=defaultdict(lambda: 0), message="", last_command="", level_num=0, )
Example #28
Source File: polar.py From Mastering-Elasticsearch-7.0 with MIT License | 6 votes |
def start_pan(self, x, y, button): angle = np.deg2rad(self.get_rlabel_position()) mode = '' if button == 1: epsilon = np.pi / 45.0 t, r = self.transData.inverted().transform_point((x, y)) if angle - epsilon <= t <= angle + epsilon: mode = 'drag_r_labels' elif button == 3: mode = 'zoom' self._pan_start = types.SimpleNamespace( rmax=self.get_rmax(), trans=self.transData.frozen(), trans_inverse=self.transData.inverted().frozen(), r_label_angle=self.get_rlabel_position(), x=x, y=y, mode=mode)
Example #29
Source File: polar.py From GraphicDesignPatternByPython with MIT License | 6 votes |
def start_pan(self, x, y, button): angle = np.deg2rad(self.get_rlabel_position()) mode = '' if button == 1: epsilon = np.pi / 45.0 t, r = self.transData.inverted().transform_point((x, y)) if angle - epsilon <= t <= angle + epsilon: mode = 'drag_r_labels' elif button == 3: mode = 'zoom' self._pan_start = types.SimpleNamespace( rmax=self.get_rmax(), trans=self.transData.frozen(), trans_inverse=self.transData.inverted().frozen(), r_label_angle=self.get_rlabel_position(), x=x, y=y, mode=mode)
Example #30
Source File: debugger.py From CQ-editor with Apache License 2.0 | 6 votes |
def _inject_locals(self,module): cq_objects = {} def _show_object(obj,name=None, options={}): if name: cq_objects.update({name : SimpleNamespace(shape=obj,options=options)}) else: cq_objects.update({str(id(obj)) : SimpleNamespace(shape=obj,options=options)}) def _debug(obj,name=None): _show_object(obj,name,options=dict(color='red',alpha=0.2)) module.__dict__['show_object'] = _show_object module.__dict__['debug'] = _debug module.__dict__['log'] = lambda x: info(str(x)) module.__dict__['cq'] = cq return cq_objects, set(module.__dict__)-{'cq'}