function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
sequence
def create_autospec(spec, spec_set=False, instance=False, _parent=None, _name=None, **kwargs): """Create a mock object using another object as a spec. Attributes on the mock will use the corresponding attribute on the `spec` object as their spec. Functions or methods being mocked will have their arguments checked in a similar way to `mocksignature` to check that they are called with the correct signature. If `spec_set` is True then attempting to set attributes that don't exist on the spec object will raise an `AttributeError`. If a class is used as a spec then the return value of the mock (the instance of the class) will have the same spec. You can use a class as the spec for an instance object by passing `instance=True`. The returned mock will only be callable if instances of the mock are callable. `create_autospec` also takes arbitrary keyword arguments that are passed to the constructor of the created mock.""" if _is_list(spec): # can't pass a list instance to the mock constructor as it will be # interpreted as a list of strings spec = type(spec) is_type = isinstance(spec, ClassTypes) _kwargs = {'spec': spec} if spec_set: _kwargs = {'spec_set': spec} elif spec is None: # None we mock with a normal mock without a spec _kwargs = {} _kwargs.update(kwargs) Klass = MagicMock if type(spec) in DescriptorTypes: # descriptors don't have a spec # because we don't know what type they return _kwargs = {} elif not _callable(spec): Klass = NonCallableMagicMock elif is_type and instance and not _instance_callable(spec): Klass = NonCallableMagicMock _new_name = _name if _parent is None: # for a top level object no _new_name should be set _new_name = '' mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name, name=_name, **_kwargs) if isinstance(spec, FunctionTypes): # should only happen at the top level because we don't # recurse for functions mock = _set_signature(mock, spec) else: _check_signature(spec, mock, is_type, instance) if _parent is not None and not instance: _parent._mock_children[_name] = mock if is_type and not instance and 'return_value' not in kwargs: # XXXX could give a name to the return_value mock? mock.return_value = create_autospec(spec, spec_set, instance=True, _name='()', _parent=mock) for entry in dir(spec): if _is_magic(entry): # MagicMock already does the useful magic methods for us continue if isinstance(spec, FunctionTypes) and entry in FunctionAttributes: # allow a mock to actually be a function from mocksignature continue # XXXX do we need a better way of getting attributes without # triggering code execution (?) Probably not - we need the actual # object to mock it so we would rather trigger a property than mock # the property descriptor. Likewise we want to mock out dynamically # provided attributes. # XXXX what about attributes that raise exceptions on being fetched # we could be resilient against it, or catch and propagate the # exception when the attribute is fetched from the mock original = getattr(spec, entry) kwargs = {'spec': original} if spec_set: kwargs = {'spec_set': original} if not isinstance(original, FunctionTypes): new = _SpecState(original, spec_set, mock, entry, instance) mock._mock_children[entry] = new else: parent = mock if isinstance(spec, FunctionTypes): parent = mock.mock new = MagicMock(parent=parent, name=entry, _new_name=entry, _new_parent=parent, **kwargs) mock._mock_children[entry] = new skipfirst = _must_skip(spec, entry, is_type) _check_signature(original, new, skipfirst=skipfirst) # so functions created with mocksignature become instance attributes, # *plus* their underlying mock exists in _mock_children of the parent # mock. Adding to _mock_children may be unnecessary where we are also # setting as an instance attribute? if isinstance(new, FunctionTypes): setattr(mock, entry, new) return mock
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def _get_class(obj): try: return obj.__class__ except AttributeError: # in Python 2, _sre.SRE_Pattern objects have no __class__ return type(obj)
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __init__(self, spec, spec_set=False, parent=None, name=None, ids=None, instance=False): self.spec = spec self.ids = ids self.spec_set = spec_set self.parent = parent self.instance = instance self.name = name
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __init__(self, features): """Initialize `ExampleParser`. The `features` argument must be an object that can be converted to an `OrderedDict`. The keys should be strings and will be used to name the output. Values should be either `VarLenFeature` or `FixedLenFeature`. If `features` is a dict, it will be sorted by key. Args: features: An object that can be converted to an `OrderedDict` mapping column names to feature definitions. """ super(ExampleParser, self).__init__() if isinstance(features, dict): self._ordered_features = collections.OrderedDict(sorted(features.items( ), key=lambda f: f[0])) else: self._ordered_features = collections.OrderedDict(features)
npuichigo/ttsflow
[ 16, 6, 16, 1, 1500635633 ]
def name(self): return "ExampleParser"
npuichigo/ttsflow
[ 16, 6, 16, 1, 1500635633 ]
def input_valency(self): return 1
npuichigo/ttsflow
[ 16, 6, 16, 1, 1500635633 ]
def _output_names(self): return list(self._ordered_features.keys())
npuichigo/ttsflow
[ 16, 6, 16, 1, 1500635633 ]
def feature_definitions(self): return self._ordered_features
npuichigo/ttsflow
[ 16, 6, 16, 1, 1500635633 ]
def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() super(Jinja2, self).__init__(params) environment = options.pop('environment', 'jinja2.Environment') environment_cls = import_string(environment) options.setdefault('autoescape', True) options.setdefault('loader', jinja2.FileSystemLoader(self.template_dirs)) options.setdefault('auto_reload', settings.DEBUG) options.setdefault('undefined', jinja2.DebugUndefined if settings.DEBUG else jinja2.Undefined) self.env = environment_cls(**options)
Vvucinic/Wander
[ 1, 1, 1, 11, 1449375044 ]
def get_template(self, template_name): try: return Template(self.env.get_template(template_name)) except jinja2.TemplateNotFound as exc: six.reraise( TemplateDoesNotExist, TemplateDoesNotExist(exc.name, backend=self), sys.exc_info()[2], ) except jinja2.TemplateSyntaxError as exc: new = TemplateSyntaxError(exc.args) new.template_debug = get_exception_info(exc) six.reraise(TemplateSyntaxError, new, sys.exc_info()[2])
Vvucinic/Wander
[ 1, 1, 1, 11, 1449375044 ]
def __init__(self, template): self.template = template self.origin = Origin( name=template.filename, template_name=template.name, )
Vvucinic/Wander
[ 1, 1, 1, 11, 1449375044 ]
def __init__(self, name, template_name): self.name = name self.template_name = template_name
Vvucinic/Wander
[ 1, 1, 1, 11, 1449375044 ]
def check_token(self, user, token): """Check that a registration token is correct for a given user.""" # If the user is active, the hash can't be valid. if user.is_active: return False
ithinksw/philo
[ 50, 12, 50, 3, 1274327279 ]
def _make_token_with_timestamp(self, user, timestamp): ts_b36 = int_to_base36(timestamp)
ithinksw/philo
[ 50, 12, 50, 3, 1274327279 ]
def make_token(self, user, email): """Returns a token that can be used once to do an email change for the given user and email.""" return self._make_token_with_timestamp(user, email, self._num_days(self._today()))
ithinksw/philo
[ 50, 12, 50, 3, 1274327279 ]
def check_token(self, user, email, token): if email == user.email: return False
ithinksw/philo
[ 50, 12, 50, 3, 1274327279 ]
def _make_token_with_timestamp(self, user, email, timestamp): ts_b36 = int_to_base36(timestamp)
ithinksw/philo
[ 50, 12, 50, 3, 1274327279 ]
def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def process_poi(self, poi): props = {} add_parts = [] for child in poi: if child.tag in TAGS and child.tag in MAPPING: if child.tag in ('latitude', 'longitude'): props[MAPPING[child.tag]] = float(child.text) else: props[MAPPING[child.tag]] = child.text elif child.tag in TAGS and child.tag not in MAPPING: props[child.tag] = child.text elif child.tag in ('address1', 'address2', 'address3', ): add_parts.append(child.text if child.text else '') props.update({'addr_full': ', '.join(filter(None, add_parts))}) return GeojsonPointItem(**props)
iandees/all-the-places
[ 379, 151, 379, 602, 1465952958 ]
def gene_1_2(value, system): # https://encodedcc.atlassian.net/browse/ENCD-5005 # go_annotations are replaced by a link on UI to GO value.pop('go_annotations', None)
ENCODE-DCC/encoded
[ 104, 54, 104, 70, 1354841541 ]
def __init__( self, plotly_name="sourceattribution", parent_name="layout.mapbox.layer", **kwargs
plotly/python-api
[ 13052, 2308, 13052, 1319, 1385013188 ]
def __init__(self, machine): """Initialise P-ROC.""" super().__init__(machine) # validate config for p_roc self.config = self.machine.config_validator.validate_config("p_roc", self.machine.config.get('p_roc', {})) self._configure_device_logging_and_debug('P-Roc', self.config) if self.config['driverboards']: self.machine_type = self.pinproc.normalize_machine_type(self.config['driverboards']) else: self.machine_type = self.pinproc.normalize_machine_type(self.machine.config['hardware']['driverboards']) self.dmd = None self.alpha_display = None self.aux_port = None self._use_extended_matrix = False self._use_first_eight_direct_inputs = False
missionpinball/mpf
[ 176, 127, 176, 108, 1403853986 ]
def _get_default_subtype(self): """Return default subtype for P-Roc.""" return "matrix"
missionpinball/mpf
[ 176, 127, 176, 108, 1403853986 ]
def get_info_string(self): """Dump infos about boards.""" infos = "Firmware Version: {} Firmware Revision: {} Hardware Board ID: {}\n".format( self.version, self.revision, self.hardware_version) return infos
missionpinball/mpf
[ 176, 127, 176, 108, 1403853986 ]
def get_coil_config_section(cls): """Return coil config section.""" return "p_roc_coils"
missionpinball/mpf
[ 176, 127, 176, 108, 1403853986 ]
def configure_switch(self, number: str, config: SwitchConfig, platform_config: dict): """Configure a P-ROC switch. Args: ---- number: String number of the switch to configure. config: SwitchConfig settings. platform_config: Platform specific settings. Returns: A configured switch object. """ del platform_config try: if number.startswith("SD") and 0 <= int(number[2:]) <= 7: self._use_first_eight_direct_inputs = True _, y = number.split('/', 2) if int(y) > 7: self._use_extended_matrix = True except ValueError: pass if self._use_extended_matrix and self._use_first_eight_direct_inputs: raise AssertionError( "P-Roc vannot use extended matrix and the first eight direct inputs at the same " "time. Either only use SD8 to SD31 or only use matrix X/Y with Y <= 7. Offending " "switch: {}".format(number)) if self.machine_type == self.pinproc.MachineTypePDB: proc_num = self.pdbconfig.get_proc_switch_number(str(number)) if proc_num == -1: raise AssertionError("Switch {} cannot be controlled by the P-ROC. ".format(str(number))) else: proc_num = self.pinproc.decode(self.machine_type, str(number)) return self._configure_switch(config, proc_num)
missionpinball/mpf
[ 176, 127, 176, 108, 1403853986 ]
def configure_dmd(self): """Configure a hardware DMD connected to a classic P-ROC.""" self.dmd = PROCDMD(self, self.machine) return self.dmd
missionpinball/mpf
[ 176, 127, 176, 108, 1403853986 ]
def process_events(self, events): """Process events from the P-Roc.""" for event in events: event_type = event['type'] event_value = event['value'] if event_type == self.pinproc.EventTypeDMDFrameDisplayed: # ignore this for now pass elif event_type in (self.pinproc.EventTypeSwitchClosedDebounced, self.pinproc.EventTypeSwitchClosedNondebounced): self.machine.switch_controller.process_switch_by_num( state=1, num=event_value, platform=self) elif event_type in (self.pinproc.EventTypeSwitchOpenDebounced, self.pinproc.EventTypeSwitchOpenNondebounced): self.machine.switch_controller.process_switch_by_num( state=0, num=event_value, platform=self) else: self.log.warning("Received unrecognized event from the P-ROC. " "Type: %s, Value: %s", event_type, event_value)
missionpinball/mpf
[ 176, 127, 176, 108, 1403853986 ]
def __init__(self, platform, machine): """Set up DMD.""" self.platform = platform # type: PROCBasePlatform self.machine = machine # type: MachineController # dmd_timing defaults should be 250, 400, 180, 800 if self.machine.config['p_roc']['dmd_timing_cycles']: dmd_timing = Util.string_to_event_list( self.machine.config['p_roc']['dmd_timing_cycles']) self.platform.run_proc_cmd_no_wait("dmd_update_config", dmd_timing)
missionpinball/mpf
[ 176, 127, 176, 108, 1403853986 ]
def update(self, data): """Update the DMD with a new frame. Args: ---- data: A 4096-byte raw string. """ if len(data) == 4096: self.platform.run_proc_cmd_no_wait("_dmd_send", data) else: self.machine.log.warning("Received DMD frame of length %s instead" "of 4096. Discarding...", len(data))
missionpinball/mpf
[ 176, 127, 176, 108, 1403853986 ]
def __init__(self, platform): """Initialise aux port.""" self.platform = platform self._commands = []
missionpinball/mpf
[ 176, 127, 176, 108, 1403853986 ]
def reserve_index(self): """Return index of next free command slot and reserve it.""" self._commands += [[]] return len(self._commands) - 1
missionpinball/mpf
[ 176, 127, 176, 108, 1403853986 ]
def _write_commands(self): """Write commands to hardware.""" # disable program commands = [self.platform.pinproc.aux_command_disable()] # build command list for command_set in self._commands: commands += command_set self.platform.run_proc_cmd_no_wait("aux_send_commands", 0, commands) # jump from slot 0 to slot 1. overwrites the disable self.platform.run_proc_cmd_no_wait("aux_send_commands", 0, [self.platform.pinproc.aux_command_jump(1)])
missionpinball/mpf
[ 176, 127, 176, 108, 1403853986 ]
def __init__(self, display, index): """Initialise alpha numeric display.""" super().__init__(index) self.display = display
missionpinball/mpf
[ 176, 127, 176, 108, 1403853986 ]
def __init__(self, platform, aux_controller): """Initialise the alphanumeric display.""" self.platform = platform self.aux_controller = aux_controller self.aux_index = aux_controller.reserve_index() self.texts = [" "] * 4
missionpinball/mpf
[ 176, 127, 176, 108, 1403853986 ]
def build_list_request( resource_group_name: str, subscription_id: str, resource_name: str, **kwargs: Any
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def build_get_request( resource_group_name: str, subscription_id: str, resource_name: str, configuration_id: str, **kwargs: Any
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def build_update_request( resource_group_name: str, subscription_id: str, resource_name: str, configuration_id: str, *, json: JSONType = None, content: Any = None, **kwargs: Any
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def list( self, resource_group_name: str, resource_name: str, **kwargs: Any
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def get( self, resource_group_name: str, resource_name: str, configuration_id: str, **kwargs: Any
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def update( self, resource_group_name: str, resource_name: str, configuration_id: str, proactive_detection_properties: "_models.ApplicationInsightsComponentProactiveDetectionConfiguration", **kwargs: Any
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def __init__( self, credential, # type: "TokenCredential" synapse_dns_suffix="dev.azuresynapse.net", # type: str livy_api_version="2019-11-01-preview", # type: str **kwargs # type: Any
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def _configure( self, **kwargs # type: Any
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def test_manifest(self): with open(MANIFEST) as f: m = json.load(f) for img in m: r = requests.head(img['url']) r.raise_for_status() self.assertEqual(r.headers['Content-Type'], "application/x-xz") if not img['sparse']: assert img['hash'] == img['hash_raw']
commaai/openpilot
[ 38913, 7077, 38913, 364, 1479951210 ]
def __init__(self, contributor_orcid=None, credit_name=None, contributor_email=None, contributor_attributes=None): # noqa: E501 """FundingContributorV30Rc1 - a model defined in Swagger""" # noqa: E501 self._contributor_orcid = None self._credit_name = None self._contributor_email = None self._contributor_attributes = None self.discriminator = None if contributor_orcid is not None: self.contributor_orcid = contributor_orcid if credit_name is not None: self.credit_name = credit_name if contributor_email is not None: self.contributor_email = contributor_email if contributor_attributes is not None: self.contributor_attributes = contributor_attributes
Royal-Society-of-New-Zealand/NZ-ORCID-Hub
[ 13, 7, 13, 28, 1486087622 ]
def contributor_orcid(self): """Gets the contributor_orcid of this FundingContributorV30Rc1. # noqa: E501 :return: The contributor_orcid of this FundingContributorV30Rc1. # noqa: E501 :rtype: ContributorOrcidV30Rc1 """ return self._contributor_orcid
Royal-Society-of-New-Zealand/NZ-ORCID-Hub
[ 13, 7, 13, 28, 1486087622 ]
def contributor_orcid(self, contributor_orcid): """Sets the contributor_orcid of this FundingContributorV30Rc1. :param contributor_orcid: The contributor_orcid of this FundingContributorV30Rc1. # noqa: E501 :type: ContributorOrcidV30Rc1 """ self._contributor_orcid = contributor_orcid
Royal-Society-of-New-Zealand/NZ-ORCID-Hub
[ 13, 7, 13, 28, 1486087622 ]
def credit_name(self): """Gets the credit_name of this FundingContributorV30Rc1. # noqa: E501 :return: The credit_name of this FundingContributorV30Rc1. # noqa: E501 :rtype: CreditNameV30Rc1 """ return self._credit_name
Royal-Society-of-New-Zealand/NZ-ORCID-Hub
[ 13, 7, 13, 28, 1486087622 ]
def credit_name(self, credit_name): """Sets the credit_name of this FundingContributorV30Rc1. :param credit_name: The credit_name of this FundingContributorV30Rc1. # noqa: E501 :type: CreditNameV30Rc1 """ self._credit_name = credit_name
Royal-Society-of-New-Zealand/NZ-ORCID-Hub
[ 13, 7, 13, 28, 1486087622 ]
def contributor_email(self): """Gets the contributor_email of this FundingContributorV30Rc1. # noqa: E501 :return: The contributor_email of this FundingContributorV30Rc1. # noqa: E501 :rtype: ContributorEmailV30Rc1 """ return self._contributor_email
Royal-Society-of-New-Zealand/NZ-ORCID-Hub
[ 13, 7, 13, 28, 1486087622 ]
def contributor_email(self, contributor_email): """Sets the contributor_email of this FundingContributorV30Rc1. :param contributor_email: The contributor_email of this FundingContributorV30Rc1. # noqa: E501 :type: ContributorEmailV30Rc1 """ self._contributor_email = contributor_email
Royal-Society-of-New-Zealand/NZ-ORCID-Hub
[ 13, 7, 13, 28, 1486087622 ]
def contributor_attributes(self): """Gets the contributor_attributes of this FundingContributorV30Rc1. # noqa: E501 :return: The contributor_attributes of this FundingContributorV30Rc1. # noqa: E501 :rtype: FundingContributorAttributesV30Rc1 """ return self._contributor_attributes
Royal-Society-of-New-Zealand/NZ-ORCID-Hub
[ 13, 7, 13, 28, 1486087622 ]
def contributor_attributes(self, contributor_attributes): """Sets the contributor_attributes of this FundingContributorV30Rc1. :param contributor_attributes: The contributor_attributes of this FundingContributorV30Rc1. # noqa: E501 :type: FundingContributorAttributesV30Rc1 """ self._contributor_attributes = contributor_attributes
Royal-Society-of-New-Zealand/NZ-ORCID-Hub
[ 13, 7, 13, 28, 1486087622 ]
def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict())
Royal-Society-of-New-Zealand/NZ-ORCID-Hub
[ 13, 7, 13, 28, 1486087622 ]
def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, FundingContributorV30Rc1): return False return self.__dict__ == other.__dict__
Royal-Society-of-New-Zealand/NZ-ORCID-Hub
[ 13, 7, 13, 28, 1486087622 ]
def main(): global hold, fill, draw, look hold = [] fill = '#000000' connect() root = Tk() root.title('Paint 1.0') root.resizable(False, False) upper = LabelFrame(root, text='Your Canvas') lower = LabelFrame(root, text='Their Canvas') draw = Canvas(upper, bg='#ffffff', width=400, height=300, highlightthickness=0) look = Canvas(lower, bg='#ffffff', width=400, height=300, highlightthickness=0) cursor = Button(upper, text='Cursor Color', command=change_cursor) canvas = Button(upper, text='Canvas Color', command=change_canvas) draw.bind('<Motion>', motion) draw.bind('<ButtonPress-1>', press) draw.bind('<ButtonRelease-1>', release) draw.bind('<Button-3>', delete) upper.grid(padx=5, pady=5) lower.grid(padx=5, pady=5) draw.grid(row=0, column=0, padx=5, pady=5, columnspan=2) look.grid(padx=5, pady=5) cursor.grid(row=1, column=0, padx=5, pady=5, sticky=EW) canvas.grid(row=1, column=1, padx=5, pady=5, sticky=EW) root.mainloop()
ActiveState/code
[ 1884, 686, 1884, 41, 1500923597 ]
def connect(): try: start_client() except: start_server() thread.start_new_thread(processor, ())
ActiveState/code
[ 1884, 686, 1884, 41, 1500923597 ]
def start_server(): global QRI server = socket.socket() server.bind(('', PORT)) server.listen(1) QRI = spots.qri(server.accept()[0])
ActiveState/code
[ 1884, 686, 1884, 41, 1500923597 ]
def call(func, *args, **kwargs): try: QRI.call((func, args, kwargs), 0.001) except: pass
ActiveState/code
[ 1884, 686, 1884, 41, 1500923597 ]
def change_cursor(): global fill color = tkColorChooser.askcolor(color=fill)[1] if color is not None: fill = color
ActiveState/code
[ 1884, 686, 1884, 41, 1500923597 ]
def motion(event): if hold: hold.extend([event.x, event.y]) event.widget.create_line(hold[-4:], fill=fill, tag='TEMP') call('create_line', hold[-4:], fill=fill, tag='TEMP')
ActiveState/code
[ 1884, 686, 1884, 41, 1500923597 ]
def release(event): global hold if len(hold) > 2: event.widget.delete('TEMP') event.widget.create_line(hold, fill=fill, smooth=True) call('delete', 'TEMP') call('create_line', hold, fill=fill, smooth=True) hold = []
ActiveState/code
[ 1884, 686, 1884, 41, 1500923597 ]
def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def __init__(self): """ The constructor ... :return: """ # Call the constructor of the base class super(ModelGenerator, self).__init__() # The dictionary with the parameter ranges self.ranges = OrderedDict() # The dictionary with the list of the model parameters self.parameters = OrderedDict()
Stargrazer82301/CAAPR
[ 8, 2, 8, 1, 1453231962 ]
def parameter_names(self): """ This function ... :return: """ return self.ranges.keys()
Stargrazer82301/CAAPR
[ 8, 2, 8, 1, 1453231962 ]
def nparameters(self): """ This function ... :return: """ return len(self.ranges)
Stargrazer82301/CAAPR
[ 8, 2, 8, 1, 1453231962 ]
def nmodels(self): """ This function ... :return: """ return len(self.parameters[self.ranges.keys()[0]])
Stargrazer82301/CAAPR
[ 8, 2, 8, 1, 1453231962 ]
def parameter_minima(self): """ This function ... :return: """ minima = [] for name in self.ranges: minima.append(self.ranges[name].min) # Return the minimal parameter values return minima
Stargrazer82301/CAAPR
[ 8, 2, 8, 1, 1453231962 ]
def parameter_maxima(self): """ This function ... :return: """ maxima = [] for name in self.ranges: maxima.append(self.ranges[name].max) # Return the maximal parameter values return maxima
Stargrazer82301/CAAPR
[ 8, 2, 8, 1, 1453231962 ]
def add_parameter(self, name, par_range): """ This function ... :param name: :param par_range: :return: """ self.ranges[name] = par_range
Stargrazer82301/CAAPR
[ 8, 2, 8, 1, 1453231962 ]
def run(self): """ This function ... :return: """ # 1. Call the setup function self.setup() # 2. Load the necessary input self.load_input() # 3. Initialize the animations self.initialize_animations() # 4. Generate the model parameters self.generate()
Stargrazer82301/CAAPR
[ 8, 2, 8, 1, 1453231962 ]
def setup(self): """ This function ... :return: """ # Call the setup of the base class super(ModelGenerator, self).setup()
Stargrazer82301/CAAPR
[ 8, 2, 8, 1, 1453231962 ]
def load_input(self): """ This function ... :return: """ pass
Stargrazer82301/CAAPR
[ 8, 2, 8, 1, 1453231962 ]
def initialize_animations(self): """ This function ... :return: """ # Inform the user log.info("Initializing the animations ...") # Initialize the scatter animation self.scatter_animation = ScatterAnimation(self.ranges["FUV young"], self.ranges["FUV ionizing"], self.ranges["Dust mass"]) self.scatter_animation.x_label = "FUV luminosity of young stars" self.scatter_animation.y_label = "FUV luminosity of ionizing stars" self.scatter_animation.z_label = "Dust mass" # Initialize the young FUV luminosity distribution animation self.fuv_young_animation = DistributionAnimation(self.ranges["FUV young"][0], self.ranges["FUV young"][1], "FUV luminosity of young stars", "New models") self.fuv_young_animation.add_reference_distribution("Previous models", self.distributions["FUV young"]) # Initialize the ionizing FUV luminosity distribution animation self.fuv_ionizing_animation = DistributionAnimation(self.ranges["FUV ionizing"][0], self.ranges["FUV ionizing"][1], "FUV luminosity of ionizing stars", "New models") self.fuv_ionizing_animation.add_reference_distribution("Previous models", self.distributions["FUV ionizing"]) # Initialize the dust mass distribution animation self.dust_mass_animation = DistributionAnimation(self.ranges["Dust mass"][0], self.ranges["Dust mass"][1], "Dust mass", "New models") self.dust_mass_animation.add_reference_distribution("Previous models", self.distributions["Dust mass"])
Stargrazer82301/CAAPR
[ 8, 2, 8, 1, 1453231962 ]
def generate(self): """ This function ... :return: """ pass
Stargrazer82301/CAAPR
[ 8, 2, 8, 1, 1453231962 ]
def update_animations(self, young_luminosity, ionizing_luminosity, dust_mass): """ This function ... :param young_luminosity: :param ionizing_luminosity: :param dust_mass: :return: """ # Add the point (and thus a frame) to the animation of parameter points self.scatter_animation.add_point(young_luminosity, ionizing_luminosity, dust_mass) # Update the distribution animations if self.nmodels > 1: # Add a frame to the animation of the distribution of the FUV luminosity of young starss self.fuv_young_animation.add_value(young_luminosity) # Add a frame to the animation of the distribution of the FUV luminosity of ionizing stars self.fuv_ionizing_animation.add_value(ionizing_luminosity) # Add a frame to the animation of the distribution of the dust mass self.dust_mass_animation.add_value(dust_mass)
Stargrazer82301/CAAPR
[ 8, 2, 8, 1, 1453231962 ]
def __init__(self, *args, **kwargs): super(OrgLDIFHiAMixin, self).__init__(*args, **kwargs) self.attr2syntax['mobile'] = self.attr2syntax['telephoneNumber'] self.attr2syntax['roomNumber'] = (None, None, normalize_string)
unioslo/cerebrum
[ 9, 3, 9, 40, 1396362121 ]
def get_contact_aliases(self, contact_type=None, source_system=None, convert=None, verify=None, normalize=None): """Return a dict {entity_id: [list of contact aliases]}.""" # The code mimics a reduced modules/OrgLDIF.py:get_contacts(). entity = Entity.EntityContactInfo(self.db) cont_tab = defaultdict(list) if not convert: convert = text_type if not verify: verify = bool for row in entity.list_contact_info(source_system=source_system, contact_type=contact_type): alias = convert(text_type(row['contact_alias'])) if alias and verify(alias): cont_tab[int(row['entity_id'])].append(alias) return dict((key, attr_unique(values, normalize=normalize)) for key, values in cont_tab.iteritems())
unioslo/cerebrum
[ 9, 3, 9, 40, 1396362121 ]
def _(text, disambiguation=None, context='Page'): """Translate text.""" return qt.QCoreApplication.translate(context, text, disambiguation)
veusz/veusz
[ 634, 96, 634, 303, 1296746008 ]
def _resolveLinkedAxis(axis): """Follow a chain of axis function dependencies.""" loopcheck = set() while axis is not None and axis.isLinked(): loopcheck.add(axis) axis = axis.getLinkedAxis() if axis in loopcheck: # fail if loop return None return axis
veusz/veusz
[ 634, 96, 634, 303, 1296746008 ]
def __init__(self): # map widgets to widgets it depends on self.deps = collections.defaultdict(list) # list of axes self.axes = [] # list of plotters associated with each axis self.axis_plotter_map = collections.defaultdict(list) # ranges for each axis self.ranges = {} # pairs of dependent widgets self.pairs = [] # track axes which map from one axis to another self.axis_to_axislinked = {} self.axislinked_to_axis = {}
veusz/veusz
[ 634, 96, 634, 303, 1296746008 ]
def breakCycles(self, origcyclic): """Remove cycles if possible.""" numcyclic = len(origcyclic) best = -1 for i in range(len(self.pairs)): if not self.pairs[i][0][0].isaxis: p = self.pairs[:i] + self.pairs[i+1:] ordered, cyclic = utils.topological_sort(p) if len(cyclic) <= numcyclic: numcyclic = len(cyclic) best = i # delete best, or last one if none better found p = self.pairs[best] del self.pairs[best] try: idx = self.deps[p[1]].index(p[0]) del self.deps[p[1]][idx] except ValueError: pass
veusz/veusz
[ 634, 96, 634, 303, 1296746008 ]
def _updateRangeFromPlotter(self, axis, plotter, plotterdep): """Update the range for axis from the plotter.""" if axis.isLinked(): # take range and map back to real axis therange = list(defaultrange) plotter.getRange(axis, plotterdep, therange) if therange != defaultrange: # follow up chain loopcheck = set() while axis.isLinked(): loopcheck.add(axis) therange = axis.invertFunctionVals(therange) axis = axis.getLinkedAxis() if axis in loopcheck: axis = None if axis is not None and therange is not None: self.ranges[axis] = [ N.nanmin((self.ranges[axis][0], therange[0])), N.nanmax((self.ranges[axis][1], therange[1])) ] else: plotter.getRange(axis, plotterdep, self.ranges[axis])
veusz/veusz
[ 634, 96, 634, 303, 1296746008 ]
def processDepends(self): """Go through dependencies of widget. If the dependency has no dependency itself, then update the axis with the widget or vice versa Algorithm: Iterate over dependencies for widget. If the widget has a dependency on a widget which doesn't have a dependency itself, update range from that widget. Then delete that depency from the dependency list. """ # get ordered list, breaking cycles while True: ordered, cyclic = utils.topological_sort(self.pairs) if not cyclic: break self.breakCycles(cyclic) # iterate over widgets in order for dep in ordered: self.processWidgetDeps(dep) # process deps for any axis functions while dep[0] in self.axis_to_axislinked: dep = (self.axis_to_axislinked[dep[0]], None) self.processWidgetDeps(dep)
veusz/veusz
[ 634, 96, 634, 303, 1296746008 ]
def addSettings(klass, s): widget.Widget.addSettings(s) # page sizes are initially linked to the document page size s.add( setting.DistancePhysical( 'width', setting.Reference('/width'), descr=_('Width of page'), usertext=_('Page width'), formatting=True) ) s.add( setting.DistancePhysical( 'height', setting.Reference('/height'), descr=_('Height of page'), usertext=_('Page height'), formatting=True) ) s.add( setting.Notes( 'notes', '', descr=_('User-defined notes'), usertext=_('Notes')) ) s.add( setting.PageBrush( 'Background', descr = _('Background page fill'), usertext=_('Background')), pixmap='settings_bgfill', )
veusz/veusz
[ 634, 96, 634, 303, 1296746008 ]
def allowedParentTypes(klass): from . import root return (root.Root,)
veusz/veusz
[ 634, 96, 634, 303, 1296746008 ]
def userdescription(self): """Return user-friendly description.""" return textwrap.fill(self.settings.notes, 60)
veusz/veusz
[ 634, 96, 634, 303, 1296746008 ]
def updateControlItem(self, cgi): """Call helper to set page size.""" cgi.setPageSize()
veusz/veusz
[ 634, 96, 634, 303, 1296746008 ]
def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError(_("Passwords don't match")) return password2
JustinWingChungHui/okKindred
[ 14, 9, 14, 7, 1414365205 ]
def clean_password(self): # Regardless of what the user provides, return the initial value. # This is done here, rather than on the field, because the # field does not have access to the initial value return self.initial["password"]
JustinWingChungHui/okKindred
[ 14, 9, 14, 7, 1414365205 ]
def child_visibility(appliance, network_provider, relationship, view): network_provider_view = navigate_to(network_provider, 'Details') if network_provider_view.entities.relationships.get_text_of(relationship) == "0": pytest.skip("There are no relationships for {}".format(relationship)) network_provider_view.entities.relationships.click_at(relationship) relationship_view = appliance.browser.create_view(view) try: if relationship != "Floating IPs": assert relationship_view.entities.entity_names else: assert relationship_view.entities.entity_ids actual_visibility = True except AssertionError: actual_visibility = False return actual_visibility
RedHatQE/cfme_tests
[ 69, 165, 69, 133, 1360187957 ]
def test_tagvis_network_provider_children(provider, appliance, request, relationship, view, tag, user_restricted): """ Polarion: assignee: anikifor initialEstimate: 1/8h casecomponent: Tagging """ collection = appliance.collections.network_providers.filter({'provider': provider}) network_provider = collection.all()[0] network_provider.add_tag(tag=tag) request.addfinalizer(lambda: network_provider.remove_tag(tag=tag)) actual_visibility = child_visibility(appliance, network_provider, relationship, view) assert actual_visibility with user_restricted: actual_visibility = child_visibility(appliance, network_provider, relationship, view) assert not actual_visibility
RedHatQE/cfme_tests
[ 69, 165, 69, 133, 1360187957 ]
def entity(request, appliance): collection_name = request.param item_collection = getattr(appliance.collections, collection_name) items = item_collection.all() if items: return items[0] else: pytest.skip("No content found for test")
RedHatQE/cfme_tests
[ 69, 165, 69, 133, 1360187957 ]
def setUp(self): self.oFile = vhdlFile.vhdlFile(lFile) self.assertIsNone(eError) self.oFile.set_indent_map(dIndentMap)
jeremiah-c-leary/vhdl-style-guide
[ 129, 31, 129, 57, 1499106283 ]
def main():
mikel-egana-aranguren/SADI-Galaxy-Docker
[ 1, 3, 1, 1, 1417087373 ]
def _timesheet_get_portal_domain(self): """ WE revert this functionality of odoo. We want to show details of ordered quantities also Only the timesheets with a product invoiced on delivered quantity are concerned. since in ordered quantity, the timesheet quantity is not invoiced, thus there is no meaning of showing invoice with ordered quantity. """ domain = super(AccountAnalyticLine, self)._timesheet_get_portal_domain() return expression.AND( [domain, [('timesheet_invoice_type', 'in', ['billable_time', 'non_billable', 'billable_fixed'])]])
ingadhoc/sale
[ 42, 53, 42, 22, 1453129543 ]
def get_mandate_action(self): """ return an action for an ext.mandate contains into the domain a specific tuples to get concerned mandates """ self.ensure_one() res_ids = self._get_assemblies()._get_mandates().ids domain = [("id", "in", res_ids)] # get model's action to update its domain action = self.env["ir.actions.act_window"]._for_xml_id( "mozaik_mandate.ext_mandate_action" ) action["domain"] = domain return action
mozaik-association/mozaik
[ 28, 20, 28, 4, 1421746811 ]