code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class RotateSwitchingMarkovChain(RotateGaussianMarkovChain): <NEW_LINE> <INDENT> def __init__(self, X, B, Z, B_rotator): <NEW_LINE> <INDENT> self.X_node = X <NEW_LINE> self.B_node = B <NEW_LINE> self.Z_node = Z._convert(CategoricalMoments) <NEW_LINE> self.B_rotator = B_rotator <NEW_LINE> (N,D) = self.X_node.dims[0] <NEW_LINE> K = self.Z_node.dims[0][0] <NEW_LINE> if len(self.Z_node.plates) == 0 and self.Z_node.plates[-1] != N-1: <NEW_LINE> <INDENT> raise ValueError("Incorrect plate length in Z") <NEW_LINE> <DEDENT> if self.B_node.plates[-2:] != (K,D): <NEW_LINE> <INDENT> raise ValueError("Incorrect plates in B") <NEW_LINE> <DEDENT> if len(self.Z_node.dims[0]) != 1: <NEW_LINE> <INDENT> raise ValueError("Z should have exactly one variable axis") <NEW_LINE> <DEDENT> if len(self.B_node.dims[0]) != 1: <NEW_LINE> <INDENT> raise ValueError("B should have exactly one variable axes") <NEW_LINE> <DEDENT> super().__init__(X, B_rotator) <NEW_LINE> <DEDENT> def _computations_for_A_and_X(self, XpXn, XpXp): <NEW_LINE> <INDENT> (B, BB) = self.B_node.get_moments() <NEW_LINE> CovB = BB - B[...,:,None]*B[...,None,:] <NEW_LINE> u_Z = self.Z_node.get_moments() <NEW_LINE> Z = u_Z[0] <NEW_LINE> Z_XpXn = np.einsum('...nij,...nk->...kij', XpXn, Z) <NEW_LINE> A_XpXn = np.einsum('...kil,...klj->...ij', B, Z_XpXn) <NEW_LINE> A_XpXn = sum_to_plates(A_XpXn, (), ndim=2, plates_from=self.X_node.plates) <NEW_LINE> Z_XpXp = np.einsum('...nij,...nk->...kij', XpXp, Z) <NEW_LINE> B_Z_XpXp = np.einsum('...kil,...klj->...kij', B, Z_XpXp) <NEW_LINE> A_XpXp_A = np.einsum('...kil,...kjl->...ij', B_Z_XpXp, B) <NEW_LINE> A_XpXp_A = sum_to_plates(A_XpXp_A, (), ndim=2, plates_from=self.X_node.plates) <NEW_LINE> CovA_XpXp = np.einsum('...kij,...kdij->...d', Z_XpXp, CovB) <NEW_LINE> CovA_XpXp = sum_to_plates(CovA_XpXp, (), ndim=1, plates_from=self.X_node.plates) <NEW_LINE> return (A_XpXn, A_XpXp_A, CovA_XpXp)
Rotation for :class:`bayespy.nodes.VaryingGaussianMarkovChain` Assume the following model. Constant, unit isotropic innovation noise. :math:`A_n = B_{z_n}` Gaussian B: (..., K, D) x (D) Categorical Z: (..., N-1) x (K) GaussianMarkovChain X: (...) x (N,D) No plates for X.
62598f9f56ac1b37e6301ff8
class Array(LLike): <NEW_LINE> <INDENT> o, c = '(array ', ')'
An n-dimensional array.
62598f9ff7d966606f747df5
class State(garlicsim.data_structures.State): <NEW_LINE> <INDENT> def __init__(self, players, round=-1, match=0, n_rounds=7): <NEW_LINE> <INDENT> assert -1 <= round <= (n_rounds - 1) <NEW_LINE> self.round = round <NEW_LINE> assert 0 <= match <= infinity <NEW_LINE> self.match = match <NEW_LINE> assert all(isinstance(player, BasePlayer) for player in players) <NEW_LINE> self.players = players <NEW_LINE> assert n_rounds >= 1 <NEW_LINE> self.n_rounds = n_rounds <NEW_LINE> self.handicap = Handicap('The thing', meow='The meow') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def create_root(n_players=70, n_rounds=7): <NEW_LINE> <INDENT> state = State( players=[player_types_list[i % len(player_types_list)]() for i in xrange(n_players)], n_rounds=n_rounds ) <NEW_LINE> state._prepare_for_new_match(replace_loser=False) <NEW_LINE> return state <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def create_messy_root(n_players=70, n_rounds=7): <NEW_LINE> <INDENT> state = State( players=[PlayerType.create_player_of_random_type() for i in xrange(n_players)], n_rounds=n_rounds ) <NEW_LINE> state._prepare_for_new_match(replace_loser=False) <NEW_LINE> return state <NEW_LINE> <DEDENT> def inplace_step(self): <NEW_LINE> <INDENT> self.clock += 1 <NEW_LINE> self.round += 1 <NEW_LINE> if self.round == self.n_rounds: <NEW_LINE> <INDENT> self.round = -1 <NEW_LINE> self.match += 1 <NEW_LINE> self._prepare_for_new_match() <NEW_LINE> return <NEW_LINE> <DEDENT> for player_1, player_2 in self.player_pairs: <NEW_LINE> <INDENT> BasePlayer.play_game(player_1, player_2, self.round) <NEW_LINE> <DEDENT> <DEDENT> def _prepare_for_new_match(self, replace_loser=True): <NEW_LINE> <INDENT> assert self.round == -1 <NEW_LINE> if replace_loser: <NEW_LINE> <INDENT> loser = self.get_player_with_least_points() <NEW_LINE> self.players.remove(loser) <NEW_LINE> self.players.append(PlayerType.create_player_of_random_type()) <NEW_LINE> <DEDENT> self.player_pairs = random_tools.random_partition(self.players, 2) <NEW_LINE> <DEDENT> def get_player_with_least_points(self): <NEW_LINE> <INDENT> return min(self.players, key=lambda player: player.points) <NEW_LINE> <DEDENT> def get_n_players_of_given_type(self, player_type): <NEW_LINE> <INDENT> return len([player for player in self.players if isinstance(player, player_type)])
World state. A frozen moment in time in the simulation world.
62598f9f1f037a2d8b9e3ef5
class Entry(object): <NEW_LINE> <INDENT> def __init__(self, value, dirty, modified=None, updated=None): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> self.dirty = dirty <NEW_LINE> self.updated = updated if updated != None else time.time() <NEW_LINE> self.modified = modified if modified != None else time.time()
Cache entry.
62598f9f30dc7b766599f65b
class BisectCurrentUnitTests(BisectTestCase): <NEW_LINE> <INDENT> def testShowLog(self): <NEW_LINE> <INDENT> sio = StringIO() <NEW_LINE> cmds.BisectCurrent().show_rev_log(out=sio) <NEW_LINE> <DEDENT> def testShowLogSubtree(self): <NEW_LINE> <INDENT> current = cmds.BisectCurrent() <NEW_LINE> current.switch(self.subtree_rev) <NEW_LINE> sio = StringIO() <NEW_LINE> current.show_rev_log(out=sio) <NEW_LINE> <DEDENT> def testSwitchVersions(self): <NEW_LINE> <INDENT> current = cmds.BisectCurrent() <NEW_LINE> self.assertRevno(5) <NEW_LINE> current.switch(4) <NEW_LINE> self.assertRevno(4) <NEW_LINE> <DEDENT> def testReset(self): <NEW_LINE> <INDENT> current = cmds.BisectCurrent() <NEW_LINE> current.switch(4) <NEW_LINE> current.reset() <NEW_LINE> self.assertRevno(5) <NEW_LINE> assert not os.path.exists(cmds.bisect_rev_path) <NEW_LINE> <DEDENT> def testIsMergePoint(self): <NEW_LINE> <INDENT> current = cmds.BisectCurrent() <NEW_LINE> self.assertRevno(5) <NEW_LINE> assert not current.is_merge_point() <NEW_LINE> current.switch(2) <NEW_LINE> assert current.is_merge_point()
Test the BisectCurrent class.
62598f9f7b25080760ed72b6
class Restream(Subconstruct): <NEW_LINE> <INDENT> __slots__ = ["stream_reader", "stream_writer", "resizer"] <NEW_LINE> def __init__(self, subcon, stream_reader, stream_writer, resizer): <NEW_LINE> <INDENT> super(Restream, self).__init__(subcon) <NEW_LINE> self.stream_reader = stream_reader <NEW_LINE> self.stream_writer = stream_writer <NEW_LINE> self.resizer = resizer <NEW_LINE> <DEDENT> def _parse(self, stream, context): <NEW_LINE> <INDENT> stream2 = self.stream_reader(stream) <NEW_LINE> obj = self.subcon._parse(stream2, context) <NEW_LINE> stream2.close() <NEW_LINE> return obj <NEW_LINE> <DEDENT> def _build(self, obj, stream, context): <NEW_LINE> <INDENT> stream2 = self.stream_writer(stream) <NEW_LINE> self.subcon._build(obj, stream2, context) <NEW_LINE> stream2.close() <NEW_LINE> <DEDENT> def _sizeof(self, context): <NEW_LINE> <INDENT> return self.resizer(self.subcon._sizeof(context))
Wraps the stream with a read-wrapper (for parsing) or a write-wrapper (for building). The stream wrapper can buffer the data internally, reading it from- or writing it to the underlying stream as needed. For example, BitStreamReader reads whole bytes from the underlying stream, but returns them as individual bits. .. seealso:: The :func:`~construct.macros.Bitwise` macro. When the parsing or building is done, the stream's close method will be invoked. It can perform any finalization needed for the stream wrapper, but it must not close the underlying stream. .. warning:: Do not use pointers inside ``Restream``. :param subcon: the subcon :param stream_reader: the read-wrapper :param stream_writer: the write wrapper :param resizer: a function that takes the size of the subcon and "adjusts" or "resizes" it according to the encoding/decoding process. Example:: Restream(BitField("foo", 16), stream_reader = BitStreamReader, stream_writer = BitStreamWriter, resizer = lambda size: size / 8, )
62598f9fa8ecb0332587101b
class HostingComDriver(VCloudNodeDriver): <NEW_LINE> <INDENT> connectionCls = HostingComConnection
vCloud node driver for Hosting.com
62598f9fcc0a2c111447ae1b
class DateTimeField(Field): <NEW_LINE> <INDENT> def to_python(self, value): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return dateparser.parse(value)
Parses a datetime string to a string
62598f9f009cb60464d01333
class PageOffsetParser(SGMLParser): <NEW_LINE> <INDENT> def __init__(self, input_file, mapping): <NEW_LINE> <INDENT> input_file.seek(0) <NEW_LINE> self.input_file = input_file <NEW_LINE> self.mapping = mapping <NEW_LINE> self.current_offset = 0 <NEW_LINE> self.count = 0 <NEW_LINE> SGMLParser.__init__(self) <NEW_LINE> <DEDENT> def start_page(self, attrs): <NEW_LINE> <INDENT> self.count += 1 <NEW_LINE> self.mapping[str(self.count)] = self.current_offset <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> for line in self.input_file: <NEW_LINE> <INDENT> self.feed(line) <NEW_LINE> self.current_offset += len(line)
Parser to compute offsets for <page> starts by document index
62598f9f090684286d5935e1
class Plugin(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> if Ice.getType(self) == _M_Ice.Plugin: <NEW_LINE> <INDENT> raise RuntimeError('Ice.Plugin is an abstract class') <NEW_LINE> <DEDENT> <DEDENT> def initialize(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def destroy(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return IcePy.stringify(self, _M_Ice._t_Plugin) <NEW_LINE> <DEDENT> __repr__ = __str__
A communicator plug-in. A plug-in generally adds a feature to a communicator, such as support for a protocol. The communicator loads its plug-ins in two stages: the first stage creates the plug-ins, and the second stage invokes Plugin.initialize on each one.
62598f9f627d3e7fe0e06cb9
class ScatteringActivities(ScatteringData, _VibAct): <NEW_LINE> <INDENT> associated_genres = ( "ramanactiv", "ramact", "raman1", "roa1", "raman2", "roa2", "raman3", "roa3", ) <NEW_LINE> _full_name_ref = dict( ramanactiv="Raman scatt. activities", ramact="Raman scatt. activities", roa1="ROA inten. ICPu/SCPu(180)", raman1="Raman inten. ICPu/SCPu(180)", roa2="ROA inten. ICPd/SCPd(90)", raman2="Raman inten. ICPd/SCPd(90)", roa3="ROA inten. DCPI(180)", raman3="Raman inten. DCPI(180)", ) <NEW_LINE> _units = dict( ramanactiv="A^4/AMU", ramact="A^4/AMU", roa1="10^4 K", raman1="K", roa2="10^4 K", raman2="K", roa3="10^4 K", raman3="K", ) <NEW_LINE> _intensities_converters = { "ramanactiv": _as_is, "ramact": _as_is, "raman1": _as_is, "roa1": _as_is, "raman2": _as_is, "roa2": _as_is, "raman3": _as_is, "roa3": _as_is, } <NEW_LINE> @property <NEW_LINE> def intensities(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> converter = self._intensities_converters[self.genre] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return super().intensities <NEW_LINE> <DEDENT> return converter(self.values, self.frequencies, self.t, self.laser)
For handling scattering spectral activity data. .. list-table:: Genres associated with this class: :width: 100% * - ramanactiv - ramact - raman1 - roa1 * - raman2 - roa2 - raman3 - roa3
62598f9f2ae34c7f260aaeef
class StockViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = Stock.objects.all() <NEW_LINE> serializer_class = StockSerializer
This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions.
62598f9f6e29344779b0046a
class DemoException(Exception): <NEW_LINE> <INDENT> pass
Test exception
62598f9f498bea3a75a57930
class CalculateWindow(FirstTypeWindow): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> FirstTypeWindow.__init__(self) <NEW_LINE> self.title("Calculate checksum") <NEW_LINE> self.firstLabelField("Fill text field") <NEW_LINE> self.mesText = self.firstTextField() <NEW_LINE> self.secondLabelField("Or choose a file from your Desktop") <NEW_LINE> self.pathFileText = self.secondTextField() <NEW_LINE> self.firstButtonField(self.choosePathToFile, "Choose") <NEW_LINE> self.thirdLabelField("Checksum") <NEW_LINE> self.checkSumText = self.thirdTextField() <NEW_LINE> self.listCRC = self.firstComboboxField(list(functions.polynomials.keys())) <NEW_LINE> self.secondButtonField(self.calculateChecksum, "Calculate") <NEW_LINE> <DEDENT> def choosePathToFile(self): <NEW_LINE> <INDENT> filename = filedialog.askopenfilename(parent=self) <NEW_LINE> self.pathFileText.delete(1.0, END) <NEW_LINE> self.pathFileText.insert(1.0, filename) <NEW_LINE> <DEDENT> def calculateChecksum(self): <NEW_LINE> <INDENT> valueMesText = self.mesText.get(1.0, END).rstrip() <NEW_LINE> valuePathFileText = self.pathFileText.get(1.0, END).rstrip() <NEW_LINE> if valueMesText == '' and valuePathFileText == '': <NEW_LINE> <INDENT> showwarning("Warning!", "Please, fill message field or path of file field!", parent=self) <NEW_LINE> <DEDENT> elif self.mesText.get(1.0, END).rstrip() != '' and self.pathFileText.get(1.0, END).rstrip() != '': <NEW_LINE> <INDENT> showwarning("Warning!", "You can fill only one field. Message or path to file!", parent=self) <NEW_LINE> <DEDENT> elif valueMesText != '' and valuePathFileText == '': <NEW_LINE> <INDENT> textInt = functions.getPosSumText(self.mesText.get(1.0, END).rstrip()) <NEW_LINE> polynomial = functions.polynomials[self.listCRC.get()] <NEW_LINE> checkSum = functions.calculateCheckSum(textInt, polynomial) <NEW_LINE> checkSumHex = hex(checkSum)[2:] <NEW_LINE> self.checkSumText.delete(1.0, END) <NEW_LINE> self.checkSumText.insert(1.0, checkSumHex) <NEW_LINE> showinfo("Info", "Checksum was calculated!", parent=self) <NEW_LINE> <DEDENT> elif valueMesText == '' and valuePathFileText != '': <NEW_LINE> <INDENT> pathAndFilename = self.pathFileText.get(1.0, END).rstrip() <NEW_LINE> fileInt = functions.getPosSumFile(pathAndFilename) <NEW_LINE> polynomial = functions.polynomials[self.listCRC.get()] <NEW_LINE> checkSum = functions.calculateCheckSum(fileInt, polynomial) <NEW_LINE> checkSumHex = hex(checkSum)[2:] <NEW_LINE> self.checkSumText.delete(1.0, END) <NEW_LINE> self.checkSumText.insert(1.0, checkSumHex) <NEW_LINE> showinfo("Info", "Checksum was calculated!", parent=self)
Class, which describes window, where you can calculate checksum.
62598f9f30bbd7224646987e
class TupleTypeInfo(TypeInformation): <NEW_LINE> <INDENT> def __init__(self, field_types: List[TypeInformation]): <NEW_LINE> <INDENT> self._field_types = field_types <NEW_LINE> super(TupleTypeInfo, self).__init__() <NEW_LINE> <DEDENT> def get_field_types(self) -> List[TypeInformation]: <NEW_LINE> <INDENT> return self._field_types <NEW_LINE> <DEDENT> def get_java_type_info(self) -> JavaObject: <NEW_LINE> <INDENT> if not self._j_typeinfo: <NEW_LINE> <INDENT> j_types_array = get_gateway().new_array( get_gateway().jvm.org.apache.flink.api.common.typeinfo.TypeInformation, len(self._field_types)) <NEW_LINE> for i in range(len(self._field_types)): <NEW_LINE> <INDENT> field_type = self._field_types[i] <NEW_LINE> if isinstance(field_type, TypeInformation): <NEW_LINE> <INDENT> j_types_array[i] = field_type.get_java_type_info() <NEW_LINE> <DEDENT> <DEDENT> self._j_typeinfo = get_gateway().jvm .org.apache.flink.api.java.typeutils.TupleTypeInfo(j_types_array) <NEW_LINE> <DEDENT> return self._j_typeinfo <NEW_LINE> <DEDENT> def __eq__(self, other) -> bool: <NEW_LINE> <INDENT> if isinstance(other, TupleTypeInfo): <NEW_LINE> <INDENT> return self._field_types == other._field_types <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> return "TupleTypeInfo(%s)" % ', '.join( [str(field_type) for field_type in self._field_types])
TypeInformation for Tuple.
62598f9f4527f215b58e9cf3
class Players(DeclarativeBase): <NEW_LINE> <INDENT> __tablename__ = "players" <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> name = Column('name', String) <NEW_LINE> player_url = Column('player_url', String, nullable=True) <NEW_LINE> position = Column('position', String, nullable=True) <NEW_LINE> age = Column('age', Integer, nullable=True) <NEW_LINE> current_team = Column('current_team', String, nullable=True) <NEW_LINE> team_one_year_ago = Column('team_one_year_ago', String, nullable=True) <NEW_LINE> team_two_year_ago = Column('team_two_year_ago', String, nullable=True) <NEW_LINE> team_three_year_ago = Column('team_three_year_ago', String, nullable=True) <NEW_LINE> points_one_year_ago = Column('points_one_year_ago', Float, nullable=True) <NEW_LINE> points_two_year_ago = Column('points_two_year_ago', Float, nullable=True) <NEW_LINE> points_three_year_ago = Column('points_three_year_ago', Float, nullable=True)
Sqlalchemy Players model
62598f9f76e4537e8c3ef3c6
class Visits(object): <NEW_LINE> <INDENT> def __init__(self, client): <NEW_LINE> <INDENT> self.client = client <NEW_LINE> <DEDENT> def query_by_ids(self, ids=None, **kwargs): <NEW_LINE> <INDENT> kwargs['ids'] = ids.replace(' ', '') <NEW_LINE> response = self._get(path='/do/query', params=kwargs) <NEW_LINE> result = response.get('result') <NEW_LINE> if result['total_results'] == 0: <NEW_LINE> <INDENT> result['visit'] = [] <NEW_LINE> <DEDENT> elif result['total_results'] == 1: <NEW_LINE> <INDENT> result['visit'] = [result['visit']] <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def query_by_visitor_ids(self, visitor_ids=None, **kwargs): <NEW_LINE> <INDENT> kwargs['visitor_ids'] = visitor_ids.replace(' ', '') <NEW_LINE> response = self._get(path='/do/query', params=kwargs) <NEW_LINE> result = response.get('result') <NEW_LINE> if result['total_results'] == 0: <NEW_LINE> <INDENT> result['visit'] = [] <NEW_LINE> <DEDENT> elif result['total_results'] == 1: <NEW_LINE> <INDENT> result['visit'] = [result['visit']] <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def query_by_prospect_ids(self, prospect_ids=None, **kwargs): <NEW_LINE> <INDENT> kwargs['prospect_ids'] = prospect_ids.replace(' ', '') <NEW_LINE> response = self._get(path='/do/query', params=kwargs) <NEW_LINE> result = response.get('result') <NEW_LINE> if result['total_results'] == 0: <NEW_LINE> <INDENT> result['visit'] = [] <NEW_LINE> <DEDENT> elif result['total_results'] == 1: <NEW_LINE> <INDENT> result['visit'] = [result['visit']] <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def read(self, id=None, **kwargs): <NEW_LINE> <INDENT> response = self._post(path='/do/read/id/{id}'.format(id=id), params=kwargs) <NEW_LINE> return response <NEW_LINE> <DEDENT> def _get(self, object_name='visit', path=None, params=None): <NEW_LINE> <INDENT> if params is None: <NEW_LINE> <INDENT> params = {} <NEW_LINE> <DEDENT> response = self.client.get(object_name=object_name, path=path, params=params) <NEW_LINE> return response <NEW_LINE> <DEDENT> def _post(self, object_name='visit', path=None, params=None): <NEW_LINE> <INDENT> if params is None: <NEW_LINE> <INDENT> params = {} <NEW_LINE> <DEDENT> response = self.client.post(object_name=object_name, path=path, params=params) <NEW_LINE> return response
A class to query and use Pardot visits. Visit field reference: http://developer.pardot.com/kb/object-field-references/#visit
62598f9f21a7993f00c65d93
class NluEnrichmentRelations(object): <NEW_LINE> <INDENT> def __init__(self, model=None): <NEW_LINE> <INDENT> self.model = model <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _from_dict(cls, _dict): <NEW_LINE> <INDENT> args = {} <NEW_LINE> if 'model' in _dict: <NEW_LINE> <INDENT> args['model'] = _dict.get('model') <NEW_LINE> <DEDENT> return cls(**args) <NEW_LINE> <DEDENT> def _to_dict(self): <NEW_LINE> <INDENT> _dict = {} <NEW_LINE> if hasattr(self, 'model') and self.model is not None: <NEW_LINE> <INDENT> _dict['model'] = self.model <NEW_LINE> <DEDENT> return _dict <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return json.dumps(self._to_dict(), indent=2) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
An object specifying the relations enrichment and related parameters. :attr str model: (optional) *For use with `natural_language_understanding` enrichments only.* The enrichement model to use with relationship extraction. May be a custom model provided by Watson Knowledge Studio, the public model for use with Knowledge Graph `en-news`, the default is`en-news`.
62598f9f4e4d562566372233
@patch_getnameinfo <NEW_LINE> class _TestKeysignHostBasedAuth(ServerTestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> async def start_server(cls): <NEW_LINE> <INDENT> return await cls.create_server(_HostBasedServer, known_client_hosts='known_hosts') <NEW_LINE> <DEDENT> @async_context_manager <NEW_LINE> async def _connect_keysign(self, client_host_keysign=True, client_host_keys=None, keysign_dirs=('.',)): <NEW_LINE> <INDENT> with patch('asyncio.create_subprocess_exec', create_subprocess_exec_stub): <NEW_LINE> <INDENT> with patch('asyncssh.keysign._DEFAULT_KEYSIGN_DIRS', keysign_dirs): <NEW_LINE> <INDENT> with patch('asyncssh.public_key._DEFAULT_HOST_KEY_DIRS', ['.']): <NEW_LINE> <INDENT> with patch('asyncssh.public_key._DEFAULT_HOST_KEY_FILES', ['skey', 'xxx']): <NEW_LINE> <INDENT> return await self.connect( username='user', client_host_keysign=client_host_keysign, client_host_keys=client_host_keys, client_username='user') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> @asynctest <NEW_LINE> async def test_keysign(self): <NEW_LINE> <INDENT> async with self._connect_keysign(): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> @asynctest <NEW_LINE> async def test_explciit_keysign(self): <NEW_LINE> <INDENT> async with self._connect_keysign(client_host_keysign='.'): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> @asynctest <NEW_LINE> async def test_keysign_explicit_host_keys(self): <NEW_LINE> <INDENT> async with self._connect_keysign(client_host_keys='skey.pub'): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> @asynctest <NEW_LINE> async def test_invalid_keysign_response(self): <NEW_LINE> <INDENT> with patch('asyncssh.keysign.KEYSIGN_VERSION', 0): <NEW_LINE> <INDENT> with self.assertRaises(asyncssh.PermissionDenied): <NEW_LINE> <INDENT> await self._connect_keysign() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @asynctest <NEW_LINE> async def test_keysign_error(self): <NEW_LINE> <INDENT> with patch('asyncssh.keysign.KEYSIGN_VERSION', 1): <NEW_LINE> <INDENT> with self.assertRaises(asyncssh.PermissionDenied): <NEW_LINE> <INDENT> await self._connect_keysign() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @asynctest <NEW_LINE> async def test_invalid_keysign_version(self): <NEW_LINE> <INDENT> with patch('asyncssh.keysign.KEYSIGN_VERSION', 99): <NEW_LINE> <INDENT> with self.assertRaises(asyncssh.PermissionDenied): <NEW_LINE> <INDENT> await self._connect_keysign() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @asynctest <NEW_LINE> async def test_keysign_not_found(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> await self._connect_keysign(keysign_dirs=()) <NEW_LINE> <DEDENT> <DEDENT> @asynctest <NEW_LINE> async def test_explicit_keysign_not_found(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> await self._connect_keysign(client_host_keysign='xxx') <NEW_LINE> <DEDENT> <DEDENT> @asynctest <NEW_LINE> async def test_keysign_dir_not_present(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> await self._connect_keysign(keysign_dirs=('xxx',))
Unit tests for host-based authentication using ssh-keysign
62598f9fcc0a2c111447ae1c
class TextFormatResponse(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.swaggerTypes = { 'TextFormat': 'TextFormat', 'Code': 'str', 'Status': 'str' } <NEW_LINE> self.attributeMap = { 'TextFormat': 'TextFormat','Code': 'Code','Status': 'Status'} <NEW_LINE> self.TextFormat = None <NEW_LINE> self.Code = None <NEW_LINE> self.Status = None
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598f9f8e71fb1e983bb8c6
class GetToken(Resource): <NEW_LINE> <INDENT> decorators = [auth.login_required] <NEW_LINE> def get(self): <NEW_LINE> <INDENT> token = g.user.generate_auth_token() <NEW_LINE> return jsonify({"token": token.decode("ascii")})
Usage: for browser to request a token
62598f9f009cb60464d01334
@export <NEW_LINE> class Biaxial110(CartesianStrain): <NEW_LINE> <INDENT> def __init__(self, C11, C12, C44, zeta): <NEW_LINE> <INDENT> ezz = 1 <NEW_LINE> exx = (2 * C44 - C12) / (2 * C44 + C11 + C12) <NEW_LINE> exy = (-C11 - 2 * C12) / (2 * C44 + C11 + C12) <NEW_LINE> deformation_matrix = np.array([[exx, exy, 0], [exy, exx, 0], [0, 0, ezz]]) <NEW_LINE> pos_displacement_matrices = [(1, -2 * exy * zeta * np.diag([0, 0, 1]))] <NEW_LINE> super(Biaxial110, self).__init__( deformation_matrix=deformation_matrix, pos_displacement_matrices=pos_displacement_matrices )
Bi-axial [110] strain for III-V semiconductors.
62598f9f92d797404e388a6e
class UpDateAnswer(MethodView): <NEW_LINE> <INDENT> @jwt_required <NEW_LINE> def put(self, qstn_id, ans_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> qstn_id_validation = validate.validate_entered_id(qstn_id) <NEW_LINE> if qstn_id_validation: <NEW_LINE> <INDENT> return qstn_id_validation <NEW_LINE> <DEDENT> ans_id_validation = validate.validate_entered_id(ans_id) <NEW_LINE> if ans_id_validation: <NEW_LINE> <INDENT> return ans_id_validation <NEW_LINE> <DEDENT> loggedin_user = get_jwt_identity() <NEW_LINE> user = get_user_by_username(user_name=loggedin_user["username"], password=loggedin_user["password"]) <NEW_LINE> current_user = user["username"] <NEW_LINE> answer = get_answer_by_id(ans_id=ans_id, qstn_id=qstn_id) <NEW_LINE> question = get_question_by_id(qstn_id=qstn_id) <NEW_LINE> ans_owner = get_answer_details(qstn_id, ans_id) <NEW_LINE> question_details = get_single_question(qstn_id=qstn_id) <NEW_LINE> if question: <NEW_LINE> <INDENT> if answer: <NEW_LINE> <INDENT> if current_user == ans_owner["ans_owner"]: <NEW_LINE> <INDENT> data = request.get_json() <NEW_LINE> if "answer" in data.keys(): <NEW_LINE> <INDENT> answer = data.get("answer").strip() <NEW_LINE> ans_validation2 = validate.validate_answer(answer) <NEW_LINE> if ans_validation2: <NEW_LINE> <INDENT> return ans_validation2 <NEW_LINE> <DEDENT> ans_validation = validate.validate_characters(answer) <NEW_LINE> if not ans_validation: <NEW_LINE> <INDENT> return jsonify({"message": "wrong answer format entered, Please try again"}), 400 <NEW_LINE> <DEDENT> update = update_answer(answer=answer, ans_id=ans_id, qstn_id=qstn_id) <NEW_LINE> updated_answer = get_answer_details(qstn_id=qstn_id, ans_id=ans_id) <NEW_LINE> return jsonify({"message": update, "Updated answer": updated_answer}), 200 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return jsonify({"message": "Answer 'key' is missing"}), 400 <NEW_LINE> <DEDENT> <DEDENT> if current_user == question_details["qstn_owner"]: <NEW_LINE> <INDENT> status = "Accepted" <NEW_LINE> accept = accept_answer(status=status, qstn_id=qstn_id, ans_id=ans_id) <NEW_LINE> updated_answer = get_answer_details(qstn_id=qstn_id, ans_id=ans_id) <NEW_LINE> return jsonify({"message": accept, "Updated answer": updated_answer}), 200 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return jsonify({"message": "Action not allowed"}), 401 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return jsonify({"message": "No such answer exists"}), 404 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return jsonify({"message": "No such question exists any more"}), 404 <NEW_LINE> <DEDENT> <DEDENT> except Exception as exception: <NEW_LINE> <INDENT> return jsonify({"message": exception}), 400
class to update an answer to a question
62598f9f67a9b606de545dd9
class DsrMessageType (pyxb.binding.datatypes.string, pyxb.binding.basis.enumeration_mixin): <NEW_LINE> <INDENT> _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'DsrMessageType') <NEW_LINE> _XSDLocation = pyxb.utils.utility.Location('http://ddex.net/xml/20120404/ddex.xsd', 1794, 3) <NEW_LINE> _Documentation = 'A ddex:Type of ddex:Message in the Sales Reporting Message Suite Standard.'
A ddex:Type of ddex:Message in the Sales Reporting Message Suite Standard.
62598f9f7cff6e4e811b5833
class RastriginFunction(MultiModalFunction): <NEW_LINE> <INDENT> def __init__(self, xdim = 1, a = 1, xopt = None): <NEW_LINE> <INDENT> self.a = a <NEW_LINE> FunctionEnvironment.__init__(self, xdim, xopt) <NEW_LINE> <DEDENT> def f(self, x): <NEW_LINE> <INDENT> s = 0 <NEW_LINE> for i, xi in enumerate(x): <NEW_LINE> <INDENT> ai = power(self.a, (i-1)/(self.xdim-1)) <NEW_LINE> s += (ai*xi)**2 - 10* cos(2*pi*ai*xi) <NEW_LINE> <DEDENT> return s + 10*len(x)
A classical multimodal benchmark with plenty of local minima, globally arranged on a bowl.
62598f9fd6c5a102081e1f55
class Config(object): <NEW_LINE> <INDENT> SECRET_KEY = os.environ.get("SECRET_KEY") or "I_want_to_have_insane_coding_skills_254" <NEW_LINE> MAIN_URL = os.getenv("DB_URL")
This class carries all of courier_app configurations.
62598f9f3c8af77a43b67e47
class Options: <NEW_LINE> <INDENT> def __init__(self) -> None: <NEW_LINE> <INDENT> self._args: argparse.Namespace = None <NEW_LINE> self.parse(sys.argv) <NEW_LINE> <DEDENT> def get_archiver(self) -> command_mod.Command: <NEW_LINE> <INDENT> return self._archiver <NEW_LINE> <DEDENT> def get_archives(self) -> List[str]: <NEW_LINE> <INDENT> return self._args.archives <NEW_LINE> <DEDENT> def _parse_args(self, args: List[str]) -> None: <NEW_LINE> <INDENT> parser = argparse.ArgumentParser( description="Unpack a compressed archive in ZIP format.", ) <NEW_LINE> parser.add_argument( '-v', dest='view_flag', action='store_true', help="Show contents of archive.", ) <NEW_LINE> parser.add_argument( '-test', dest='test_flag', action='store_true', help="Test archive data only.", ) <NEW_LINE> parser.add_argument( 'archives', nargs='+', metavar='file.zip', help="Archive file.", ) <NEW_LINE> self._args = parser.parse_args(args) <NEW_LINE> <DEDENT> def parse(self, args: List[str]) -> None: <NEW_LINE> <INDENT> self._parse_args(args[1:]) <NEW_LINE> if os.name == 'nt': <NEW_LINE> <INDENT> self._archiver = command_mod.Command( 'pkzip32.exe', errors='ignore' ) <NEW_LINE> if not self._archiver.is_found(): <NEW_LINE> <INDENT> self._archiver = command_mod.Command('unzip', errors='stop') <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self._archiver = command_mod.Command('unzip', errors='stop') <NEW_LINE> <DEDENT> if args[1] in ('view', 'test'): <NEW_LINE> <INDENT> self._archiver.set_args(args[1:]) <NEW_LINE> subtask_mod.Exec(self._archiver.get_cmdline()).run() <NEW_LINE> <DEDENT> if os.path.basename(self._archiver.get_file()) == 'pkzip32.exe': <NEW_LINE> <INDENT> if self._args.view_flag: <NEW_LINE> <INDENT> self._archiver.set_args(['-view']) <NEW_LINE> <DEDENT> elif self._args.test_flag: <NEW_LINE> <INDENT> self._archiver.set_args(['-test']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._archiver.set_args(['-extract', '-directories']) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if self._args.view_flag: <NEW_LINE> <INDENT> self._archiver.set_args(['-v']) <NEW_LINE> <DEDENT> elif self._args.test_flag: <NEW_LINE> <INDENT> self._archiver.set_args(['-t'])
Options class
62598f9fe64d504609df92c0
class TestCSVFileBase(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self, test_header=None, test_in_data=None): <NEW_LINE> <INDENT> self.test_header = test_header or 'ett|två|tre|fyra|fem|lista' <NEW_LINE> self.test_in_data = test_in_data or 'ett|två|tre|fyra|fem|lista\n' ' 1|2|3|4||1;2;3;;4;5 \n' 'a1|a2| a3 |a4|a5|a1;a2; a3 ;a4;a5\n' <NEW_LINE> self.test_out_data = 'ett|två|tre|fyra|fem|lista\n' '1|2|3|4|5|1;2;3;4;5\n' 'a1|a2|a3|a4|a5|a1;a2;a3;a4;a5\n' <NEW_LINE> self.test_infile = tempfile.NamedTemporaryFile() <NEW_LINE> self.test_outfile = tempfile.NamedTemporaryFile(delete=False) <NEW_LINE> self.test_infile.write(self.test_in_data.encode('utf-8')) <NEW_LINE> self.test_infile.seek(0) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.test_infile.close() <NEW_LINE> os.remove(self.test_outfile.name)
Test base for open_csv_file, csv_file_to_dict and dict_to_csv_file.
62598f9f442bda511e95c26b
class Main(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.silent = "-s" in sys.argv <NEW_LINE> self.login = "-l" in sys.argv <NEW_LINE> self.users = [ arg.capitalize() for arg in sys.argv[1:] if "-" not in arg ] <NEW_LINE> if not self.users: <NEW_LINE> <INDENT> sys.exit("Запуск без пользователей невозможен") <NEW_LINE> <DEDENT> if " " in self.users[0]: <NEW_LINE> <INDENT> self.users = self.users[0].split() <NEW_LINE> <DEDENT> <DEDENT> def launch(self): <NEW_LINE> <INDENT> if self.login: <NEW_LINE> <INDENT> if len(self.users) > 1: <NEW_LINE> <INDENT> sys.exit("Логин возможен только для одного пользователя") <NEW_LINE> <DEDENT> user = self.users[0] <NEW_LINE> params = SESSIONS.get(user) <NEW_LINE> bot = FarmBot(user, params, self.silent) <NEW_LINE> bot.connect() <NEW_LINE> sys.exit("Код уже был введен!") <NEW_LINE> <DEDENT> for _, user in enumerate(self.users): <NEW_LINE> <INDENT> params = SESSIONS.get(user) <NEW_LINE> if not params: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> worker = threading.Thread(target=self.launch_user, args=(user, params)) <NEW_LINE> worker.start() <NEW_LINE> <DEDENT> <DEDENT> def launch_user(self, user, params): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> bot = FarmBot(user, params, self.silent) <NEW_LINE> try: <NEW_LINE> <INDENT> bot.run() <NEW_LINE> <DEDENT> except OSError as err: <NEW_LINE> <INDENT> bot.logger.log("Ошибка: " + str(err)) <NEW_LINE> time.sleep(60 * r.random()) <NEW_LINE> <DEDENT> except telethon.errors.RPCError as err: <NEW_LINE> <INDENT> bot.logger.log("Ошибка РПЦ: " + str(err)) <NEW_LINE> time.sleep(60 * r.random()) <NEW_LINE> <DEDENT> except telethon.errors.BadMessageError: <NEW_LINE> <INDENT> bot.logger.log("Плохое сообщение, немного посплю") <NEW_LINE> time.sleep(120 + 60 * r.random()) <NEW_LINE> <DEDENT> except RuntimeError: <NEW_LINE> <INDENT> if str(err) != "Number of retries reached 0.": <NEW_LINE> <INDENT> raise err <NEW_LINE> <DEDENT> bot.logger.log("Попытки уравнялись нулю") <NEW_LINE> time.sleep(3600) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> exc_type, exc_value, exc_traceback = sys.exc_info() <NEW_LINE> exc = traceback.format_exception(exc_type, exc_value, exc_traceback) <NEW_LINE> text = ''.join(exc) <NEW_LINE> bot.send(params['supergroup'], text) <NEW_LINE> bot.logger.log(text) <NEW_LINE> raise err
Запуск бота
62598f9fbd1bec0571e14fcb
class HierarchyError(Exception): <NEW_LINE> <INDENT> pass
Gets thrown when something is wrong with the parameter hierarchy.
62598f9f3539df3088ecc0c5
class TestNodeCommand(test_v2_engine.BaseCLITest): <NEW_LINE> <INDENT> def test_node_list(self): <NEW_LINE> <INDENT> args = 'node list' <NEW_LINE> self.exec_v2_command(args) <NEW_LINE> self.m_get_client.assert_called_once_with('node', mock.ANY) <NEW_LINE> self.m_client.get_all.assert_called_once_with(environment_id=None) <NEW_LINE> <DEDENT> def test_node_list_with_env(self): <NEW_LINE> <INDENT> env_id = 42 <NEW_LINE> args = 'node list --env {env}'.format(env=env_id) <NEW_LINE> self.exec_v2_command(args) <NEW_LINE> self.m_get_client.assert_called_once_with('node', mock.ANY) <NEW_LINE> self.m_client.get_all.assert_called_once_with(environment_id=env_id) <NEW_LINE> <DEDENT> def test_node_show(self): <NEW_LINE> <INDENT> node_id = 42 <NEW_LINE> args = 'node show {node_id}'.format(node_id=node_id) <NEW_LINE> self.exec_v2_command(args) <NEW_LINE> self.m_get_client.assert_called_once_with('node', mock.ANY) <NEW_LINE> self.m_client.get_by_id.assert_called_once_with(node_id)
Tests for fuel2 node * commands.
62598f9f460517430c431f63
class UserChoiceField(forms.ModelChoiceField): <NEW_LINE> <INDENT> def label_from_instance(self, obj): <NEW_LINE> <INDENT> label = obj.get_full_name() <NEW_LINE> if label.strip(): <NEW_LINE> <INDENT> return label <NEW_LINE> <DEDENT> return super(UserChoiceField, self).label_from_instance(obj)
A ModelChoiceField for User models which shows the full name if available
62598f9f67a9b606de545dda
class DumpSchemaUI(metaclass=ABCMeta): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def dumped_schema(self, schema): <NEW_LINE> <INDENT> pass
Abstract base class for UI for DumpSchema.
62598f9f498bea3a75a57931
class LocalVeritasPropertiesSubmitter(LocalVeritasSubmitter): <NEW_LINE> <INDENT> def _submit_job(self,inpfn,outfn="stdout",jobname="",loc=""): <NEW_LINE> <INDENT> exe = BIN+"properties < %s"%inpfn <NEW_LINE> prep_commands = [] <NEW_LINE> final_commands = [] <NEW_LINE> if self.nn != 1 or self.np != 1: <NEW_LINE> <INDENT> print("Refusing to run properties in parallel!") <NEW_LINE> self.nn = 1 <NEW_LINE> self.np = 1 <NEW_LINE> <DEDENT> if jobname == "": <NEW_LINE> <INDENT> jobname = outfn <NEW_LINE> <DEDENT> if loc == "": <NEW_LINE> <INDENT> loc = os.getcwd() <NEW_LINE> <DEDENT> qid = self._qsub(exe,prep_commands,final_commands,jobname,outfn,loc) <NEW_LINE> return qid
Fully defined submission class. Defines interaction with specific program to be run.
62598f9f6e29344779b0046c
class AzureSpnExposure(Vulnerability, Event): <NEW_LINE> <INDENT> def __init__(self, container, evidence=""): <NEW_LINE> <INDENT> Vulnerability.__init__( self, Azure, "Azure SPN Exposure", category=MountServicePrincipalTechnique, vid="KHV004", ) <NEW_LINE> self.container = container <NEW_LINE> self.evidence = evidence
The SPN is exposed, potentially allowing an attacker to gain access to the Azure subscription
62598f9f8a43f66fc4bf1f8c
class CfdConsoleProcess: <NEW_LINE> <INDENT> def __init__(self, finishedHook=None, stdoutHook=None, stderrHook=None): <NEW_LINE> <INDENT> self.process = QtCore.QProcess() <NEW_LINE> self.finishedHook = finishedHook <NEW_LINE> self.stdoutHook = stdoutHook <NEW_LINE> self.stderrHook = stderrHook <NEW_LINE> self.process.finished.connect(self.finished) <NEW_LINE> self.process.readyReadStandardOutput.connect(self.readStdout) <NEW_LINE> self.process.readyReadStandardError.connect(self.readStderr) <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> self.terminate() <NEW_LINE> <DEDENT> def start(self, cmd, env_vars=None, working_dir=None): <NEW_LINE> <INDENT> env = QtCore.QProcessEnvironment.systemEnvironment() <NEW_LINE> if env_vars: <NEW_LINE> <INDENT> for key in env_vars: <NEW_LINE> <INDENT> env.insert(key, env_vars[key]) <NEW_LINE> <DEDENT> <DEDENT> self.process.setProcessEnvironment(env) <NEW_LINE> if working_dir: <NEW_LINE> <INDENT> self.process.setWorkingDirectory(working_dir) <NEW_LINE> <DEDENT> if platform.system() == "Windows": <NEW_LINE> <INDENT> cmd = [os.path.join(FreeCAD.getHomePath(), "bin", "python.exe"), '-u', os.path.join(os.path.dirname(__file__), "WindowsRunWrapper.py")] + cmd <NEW_LINE> <DEDENT> print("Raw command: ", cmd) <NEW_LINE> self.process.start(cmd[0], cmd[1:]) <NEW_LINE> <DEDENT> def terminate(self): <NEW_LINE> <INDENT> if platform.system() == "Windows": <NEW_LINE> <INDENT> self.process.write("terminate\n") <NEW_LINE> self.process.waitForBytesWritten() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.process.terminate() <NEW_LINE> <DEDENT> self.process.waitForFinished() <NEW_LINE> <DEDENT> def finished(self, exit_code): <NEW_LINE> <INDENT> if self.finishedHook: <NEW_LINE> <INDENT> self.finishedHook(exit_code) <NEW_LINE> <DEDENT> <DEDENT> def readStdout(self): <NEW_LINE> <INDENT> text = "" <NEW_LINE> while self.process.canReadLine(): <NEW_LINE> <INDENT> text += str(self.process.readLine()) <NEW_LINE> <DEDENT> print(text, end='') <NEW_LINE> if self.stdoutHook: <NEW_LINE> <INDENT> self.stdoutHook(text) <NEW_LINE> <DEDENT> <DEDENT> def readStderr(self): <NEW_LINE> <INDENT> self.process.setReadChannel(QtCore.QProcess.StandardError) <NEW_LINE> text = "" <NEW_LINE> while self.process.canReadLine(): <NEW_LINE> <INDENT> text += str(self.process.readLine()) <NEW_LINE> <DEDENT> if self.stderrHook: <NEW_LINE> <INDENT> self.stderrHook(text) <NEW_LINE> <DEDENT> FreeCAD.Console.PrintError(text) <NEW_LINE> self.process.setReadChannel(QtCore.QProcess.StandardOutput) <NEW_LINE> <DEDENT> def state(self): <NEW_LINE> <INDENT> return self.process.state() <NEW_LINE> <DEDENT> def waitForStarted(self): <NEW_LINE> <INDENT> return self.process.waitForStarted() <NEW_LINE> <DEDENT> def waitForFinished(self): <NEW_LINE> <INDENT> return self.process.waitForFinished(-1) <NEW_LINE> <DEDENT> def exitCode(self): <NEW_LINE> <INDENT> return self.process.exitCode()
Class to run a console process asynchronously, printing output and errors to the FreeCAD console and allowing clean termination in Linux and Windows
62598f9f32920d7e50bc5e66
class Order(models.Model): <NEW_LINE> <INDENT> product = models.ForeignKey(Product, related_name=_("orders")) <NEW_LINE> quantity = models.IntegerField(_("Product Quantity")) <NEW_LINE> amount = models.DecimalField(_("Total Amount"), max_digits=6, decimal_places=2) <NEW_LINE> delivery_status = models.CharField(_("Delivery Status"), max_length=1, default="1", choices=ORDER_DELIVERY_STATUS) <NEW_LINE> user = models.ForeignKey(Profile, related_name=_("user_ordered")) <NEW_LINE> ordered_at = models.DateTimeField(_("Order Placed At"), auto_now_add=True) <NEW_LINE> delivery_at = models.DateTimeField(_("Order Delivery At")) <NEW_LINE> delete = models.BooleanField(_("Delete"), default=False) <NEW_LINE> objects = OrderManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _("Order") <NEW_LINE> verbose_name_plural = _("Orders") <NEW_LINE> app_label = "orders" <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return "%s" % str(self.product.name)
models to store final order data
62598f9f1b99ca400228f436
class AppendCellsRequest(TypedDict): <NEW_LINE> <INDENT> fields: str <NEW_LINE> rows: List[RowData] <NEW_LINE> sheetId: int
Adds new cells after the last row with data in a sheet, inserting new rows into the sheet if necessary.
62598f9f91f36d47f2230da9
class SchemaChanges(CoClass): <NEW_LINE> <INDENT> _reg_clsid_ = GUID('{ED337BE8-C03C-4D0B-A29F-727565609B4E}') <NEW_LINE> _idlflags_ = [] <NEW_LINE> _typelib_path_ = typelib_path <NEW_LINE> _reg_typelib_ = ('{A7C74158-1062-4664-B404-8694D490FCD1}', 10, 2)
Esri Schema Changes object.
62598f9f38b623060ffa8ea4
class ContainerViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = Container.objects.all() <NEW_LINE> serializer_class = ContainerSerializer <NEW_LINE> ordering_fields = ('name',) <NEW_LINE> ordering = 'name'
A list of containers
62598f9f8da39b475be02ff0
class FileSelectorPage(ccwx.xrcwiz.XrcWizPage): <NEW_LINE> <INDENT> zope.interface.implements(p6.ui.interfaces.IWizardPage) <NEW_LINE> def __init__(self, parent, headline=_('Select Your Files')): <NEW_LINE> <INDENT> ccwx.xrcwiz.XrcWizPage.__init__(self, parent, os.path.join(p6.api.getResourceDir(), "p6.xrc"), "FILE_SELECTOR", headline) <NEW_LINE> self.__initUserInterface() <NEW_LINE> <DEDENT> def __initUserInterface(self): <NEW_LINE> <INDENT> self.__fileList = FileListControl(self) <NEW_LINE> self.GetSizer().Add(self.__fileList, flag=wx.EXPAND|wx.ALL) <NEW_LINE> self.__fileList.SetDropTarget(FileDropTarget()) <NEW_LINE> self.Bind(wx.EVT_BUTTON, self.onBrowse, XRCCTRL(self, "CMD_BROWSE")) <NEW_LINE> self.Bind(wx.EVT_BUTTON, self.onDelete, XRCCTRL(self, "CMD_DELETE")) <NEW_LINE> self.Bind(wx.EVT_KEY_UP, self.onKeyUp, self) <NEW_LINE> <DEDENT> def onBrowse(self, event): <NEW_LINE> <INDENT> fileBrowser = wx.FileDialog(self.GetParent(), style=wx.OPEN|wx.MULTIPLE|wx.FILE_MUST_EXIST) <NEW_LINE> if fileBrowser.ShowModal() == wx.ID_OK: <NEW_LINE> <INDENT> for filename in fileBrowser.GetPaths(): <NEW_LINE> <INDENT> zope.component.handle( p6.storage.events.ItemSelected( p6.storage.items.FileItem(filename) ) ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def onDelete(self, event): <NEW_LINE> <INDENT> to_remove = [] <NEW_LINE> selectedItem = self.__fileList.GetFirstSelected() <NEW_LINE> while(selectedItem != -1): <NEW_LINE> <INDENT> to_remove.append( self.__fileList.GetVirtualItem(selectedItem)) <NEW_LINE> selectedItem = self.__fileList.GetNextSelected(selectedItem) <NEW_LINE> <DEDENT> for item in to_remove: <NEW_LINE> <INDENT> zope.component.handle( p6.storage.events.ItemDeselected(item) ) <NEW_LINE> <DEDENT> <DEDENT> def onKeyUp(self, event): <NEW_LINE> <INDENT> if (event.GetKeyCode() == wx.WXK_DELETE): <NEW_LINE> <INDENT> self.onDelete(event) <NEW_LINE> <DEDENT> <DEDENT> def validate(self, event): <NEW_LINE> <INDENT> if event.direction: <NEW_LINE> <INDENT> if self.__fileList.GetItemCount() > 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> wx.MessageDialog(self, _("You must select at least one file."), _("appname") + ": " + _("Error"), wx.OK).ShowModal() <NEW_LINE> return False <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return True
Page which displays a file selector and publishes events when items are selected or deselected.
62598f9f1f037a2d8b9e3ef9
class Tip(models.Model): <NEW_LINE> <INDENT> text = models.TextField() <NEW_LINE> has_links = models.BooleanField(default=False, help_text=u'Needed for escaping characters') <NEW_LINE> datetime_since = models.DateTimeField(auto_now_add=True, help_text=u'Since when is available for publishing') <NEW_LINE> datetime_until = models.DateTimeField(help_text=u'Date until it is viewable') <NEW_LINE> container_class = models.TextField(max_length=50, help_text=u'HTML class for the wrapper') <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return u'%s...' % self.text[30:]
Tips to show in the page. `text` is the text to be shown with autoescape off, so links are allowed. `datetime_since` date since when will be available `datetime_until` date since won't be available
62598f9f596a897236127a8d
class InterpretationWorkProduct(DictField): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(InterpretationWorkProduct, self).__init__( additional_properties=True, )
Some information about the interpretation of a work product
62598f9f67a9b606de545ddb
class Abspath_Field(URI_Field): <NEW_LINE> <INDENT> def get_links(self, links, resource, field_name, languages): <NEW_LINE> <INDENT> return get_abspath_links(self, links, resource, field_name, languages) <NEW_LINE> <DEDENT> def update_links(self, resource, field_name, source, target, languages, old_base, new_base): <NEW_LINE> <INDENT> update_abspath_links(self, resource, field_name, source, target, languages, old_base, new_base) <NEW_LINE> <DEDENT> def update_incoming_links(self, resource, field_name, source, languages): <NEW_LINE> <INDENT> pass
Same that URI_Field but when we update links we use abspath
62598f9f097d151d1a2c0e3a
class Parallelio(CMakePackage): <NEW_LINE> <INDENT> homepage = "https://ncar.github.io/ParallelIO/" <NEW_LINE> url = "https://github.com/NCAR/ParallelIO/archive/pio2_5_2.tar.gz" <NEW_LINE> maintainers = ['tkameyama'] <NEW_LINE> version('2_5_2', sha256='935bc120ef3bf4fe09fb8bfdf788d05fb201a125d7346bf6b09e27ac3b5f345c') <NEW_LINE> variant('pnetcdf', default=False, description='enable pnetcdf') <NEW_LINE> depends_on('mpi') <NEW_LINE> depends_on('netcdf-c +mpi', type='link') <NEW_LINE> depends_on('netcdf-fortran', type='link') <NEW_LINE> depends_on('parallel-netcdf', type='link', when='+pnetcdf') <NEW_LINE> resource(name='CMake_Fortran_utils', git='https://github.com/CESM-Development/CMake_Fortran_utils.git', tag='master') <NEW_LINE> resource(name='genf90', git='https://github.com/PARALLELIO/genf90.git', tag='genf90_200608') <NEW_LINE> def cmake_args(self): <NEW_LINE> <INDENT> define = self.define <NEW_LINE> spec = self.spec <NEW_LINE> env['CC'] = spec['mpi'].mpicc <NEW_LINE> env['FC'] = spec['mpi'].mpifc <NEW_LINE> src = self.stage.source_path <NEW_LINE> args = [ define('NetCDF_C_PATH', spec['netcdf-c'].prefix), define('NetCDF_Fortran_PATH', spec['netcdf-fortran'].prefix), define('USER_CMAKE_MODULE_PATH', join_path(src, 'CMake_Fortran_utils')), define('GENF90_PATH', join_path(src, 'genf90')), ] <NEW_LINE> if spec.satisfies('+pnetcdf'): <NEW_LINE> <INDENT> args.extend([ define('PnetCDF_C_PATH', spec['parallel-netcdf'].prefix), define('PnetCDF_Fortran_PATH', spec['parallel-netcdf'].prefix), ]) <NEW_LINE> <DEDENT> return args
The Parallel IO libraries (PIO) are high-level parallel I/O C and Fortran libraries for applications that need to do netCDF I/O from large numbers of processors on a HPC system.
62598f9f2ae34c7f260aaef2
class Colors(str): <NEW_LINE> <INDENT> NAVIGABLE_CELL = '#fff' <NEW_LINE> OBSTACLE_CELL = '#aaa' <NEW_LINE> SHELVE_CELL = '#ffcc00' <NEW_LINE> PATH_CELL = '#007aff' <NEW_LINE> TARGET_BOOK_CELL = '#4cd964' <NEW_LINE> TITLE_FONT = '#5856d6' <NEW_LINE> CHEVRON = '#ff3b30' <NEW_LINE> PATH_LINE = CHEVRON
Colors based on "Apple Human Interface Guidelines - Colors" (https://developer.apple.com/ios/human-interface-guidelines/visual-design/color/)
62598f9fa79ad16197769e77
class BufferedPipe (object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._lock = threading.Lock() <NEW_LINE> self._cv = threading.Condition(self._lock) <NEW_LINE> self._event = None <NEW_LINE> self._buffer = array.array('B') <NEW_LINE> self._closed = False <NEW_LINE> <DEDENT> def set_event(self, event): <NEW_LINE> <INDENT> self._event = event <NEW_LINE> if len(self._buffer) > 0: <NEW_LINE> <INDENT> event.set() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> event.clear() <NEW_LINE> <DEDENT> <DEDENT> def feed(self, data): <NEW_LINE> <INDENT> self._lock.acquire() <NEW_LINE> try: <NEW_LINE> <INDENT> if self._event is not None: <NEW_LINE> <INDENT> self._event.set() <NEW_LINE> <DEDENT> self._buffer.fromstring(data) <NEW_LINE> self._cv.notifyAll() <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self._lock.release() <NEW_LINE> <DEDENT> <DEDENT> def read_ready(self): <NEW_LINE> <INDENT> self._lock.acquire() <NEW_LINE> try: <NEW_LINE> <INDENT> if len(self._buffer) == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self._lock.release() <NEW_LINE> <DEDENT> <DEDENT> def read(self, nbytes, timeout=None): <NEW_LINE> <INDENT> out = '' <NEW_LINE> self._lock.acquire() <NEW_LINE> try: <NEW_LINE> <INDENT> if len(self._buffer) == 0: <NEW_LINE> <INDENT> if self._closed: <NEW_LINE> <INDENT> return out <NEW_LINE> <DEDENT> if timeout == 0.0: <NEW_LINE> <INDENT> raise PipeTimeout() <NEW_LINE> <DEDENT> while (len(self._buffer) == 0) and not self._closed: <NEW_LINE> <INDENT> then = time.time() <NEW_LINE> self._cv.wait(timeout) <NEW_LINE> if timeout is not None: <NEW_LINE> <INDENT> timeout -= time.time() - then <NEW_LINE> if timeout <= 0.0: <NEW_LINE> <INDENT> raise PipeTimeout() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> if len(self._buffer) <= nbytes: <NEW_LINE> <INDENT> out = self._buffer.tostring() <NEW_LINE> del self._buffer[:] <NEW_LINE> if (self._event is not None) and not self._closed: <NEW_LINE> <INDENT> self._event.clear() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> out = self._buffer[:nbytes].tostring() <NEW_LINE> del self._buffer[:nbytes] <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> self._lock.release() <NEW_LINE> <DEDENT> return out <NEW_LINE> <DEDENT> def empty(self): <NEW_LINE> <INDENT> self._lock.acquire() <NEW_LINE> try: <NEW_LINE> <INDENT> out = self._buffer.tostring() <NEW_LINE> del self._buffer[:] <NEW_LINE> if (self._event is not None) and not self._closed: <NEW_LINE> <INDENT> self._event.clear() <NEW_LINE> <DEDENT> return out <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self._lock.release() <NEW_LINE> <DEDENT> <DEDENT> def close(self): <NEW_LINE> <INDENT> self._lock.acquire() <NEW_LINE> try: <NEW_LINE> <INDENT> self._closed = True <NEW_LINE> self._cv.notifyAll() <NEW_LINE> if self._event is not None: <NEW_LINE> <INDENT> self._event.set() <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> self._lock.release() <NEW_LINE> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> self._lock.acquire() <NEW_LINE> try: <NEW_LINE> <INDENT> return len(self._buffer) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self._lock.release()
A buffer that obeys normal read (with timeout) & close semantics for a file or socket, but is fed data from another thread. This is used by `.Channel`.
62598f9fbd1bec0571e14fcc
class ChemicalSearchResultSet(ResultSet): <NEW_LINE> <INDENT> def getJSONFromString(self, str): <NEW_LINE> <INDENT> return json.loads(str) <NEW_LINE> <DEDENT> def get_Response(self): <NEW_LINE> <INDENT> return self._output.get('Response', None)
A ResultSet with methods tailored to the values returned by the ChemicalSearch Choreo. The ResultSet object is used to retrieve the results of a Choreo execution.
62598f9f67a9b606de545ddc
class EnvironmentResolver: <NEW_LINE> <INDENT> def clean(self, value): <NEW_LINE> <INDENT> return re.sub(r'[^a-z0-9]', '_', value, flags=re.I) <NEW_LINE> <DEDENT> def get(self, credential): <NEW_LINE> <INDENT> if 'name' in credential.parameters and 'provider' in credential.parameters: <NEW_LINE> <INDENT> key = self.clean('%s__%s' % (credential.parameters['provider'], credential.parameters['name'])) <NEW_LINE> if key in os.environ: <NEW_LINE> <INDENT> LOG.info("resolved %s from the environment" % key) <NEW_LINE> return os.environ[key]
Resolve values from the environment.
62598f9fbe383301e0253608
class BgpServiceCommunityListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[BgpServiceCommunity]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, value: Optional[List["BgpServiceCommunity"]] = None, next_link: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(BgpServiceCommunityListResult, self).__init__(**kwargs) <NEW_LINE> self.value = value <NEW_LINE> self.next_link = next_link
Response for the ListServiceCommunity API service call. :param value: A list of service community resources. :type value: list[~azure.mgmt.network.v2020_03_01.models.BgpServiceCommunity] :param next_link: The URL to get the next set of results. :type next_link: str
62598f9f435de62698e9bc06
class _DateParameterBase(Parameter): <NEW_LINE> <INDENT> def __init__(self, interval=1, start=None, **kwargs): <NEW_LINE> <INDENT> super(_DateParameterBase, self).__init__(**kwargs) <NEW_LINE> self.interval = interval <NEW_LINE> self.start = start if start is not None else _UNIX_EPOCH.date() <NEW_LINE> <DEDENT> @property <NEW_LINE> @abc.abstractmethod <NEW_LINE> def date_format(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def parse(self, s): <NEW_LINE> <INDENT> return datetime.datetime.strptime(s, self.date_format).date() <NEW_LINE> <DEDENT> def serialize(self, dt): <NEW_LINE> <INDENT> if dt is None: <NEW_LINE> <INDENT> return str(dt) <NEW_LINE> <DEDENT> return dt.strftime(self.date_format)
Base class Parameter for date (not datetime).
62598f9f435de62698e9bc05
class AdWordsHeaderHandlerTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.adwords_client = mock.Mock() <NEW_LINE> self.header_handler = googleads.adwords._AdWordsHeaderHandler( self.adwords_client, 'v12345') <NEW_LINE> <DEDENT> def testSetHeaders(self): <NEW_LINE> <INDENT> suds_client = mock.Mock() <NEW_LINE> ccid = 'client customer id' <NEW_LINE> dev_token = 'developer token' <NEW_LINE> user_agent = 'user agent!' <NEW_LINE> validate_only = True <NEW_LINE> partial_failure = False <NEW_LINE> oauth_header = {'oauth': 'header'} <NEW_LINE> self.adwords_client.client_customer_id = ccid <NEW_LINE> self.adwords_client.developer_token = dev_token <NEW_LINE> self.adwords_client.user_agent = user_agent <NEW_LINE> self.adwords_client.validate_only = validate_only <NEW_LINE> self.adwords_client.partial_failure = partial_failure <NEW_LINE> self.adwords_client.oauth2_client.CreateHttpHeader.return_value = ( oauth_header) <NEW_LINE> self.header_handler.SetHeaders(suds_client) <NEW_LINE> suds_client.factory.create.assert_called_once_with( '{https://adwords.google.com/api/adwords/cm/v12345}SoapHeader') <NEW_LINE> soap_header = suds_client.factory.create.return_value <NEW_LINE> self.assertEqual(ccid, soap_header.clientCustomerId) <NEW_LINE> self.assertEqual(dev_token, soap_header.developerToken) <NEW_LINE> self.assertEqual( ''.join([user_agent, googleads.adwords._AdWordsHeaderHandler._LIB_SIG]), soap_header.userAgent) <NEW_LINE> self.assertEqual(validate_only, soap_header.validateOnly) <NEW_LINE> self.assertEqual(partial_failure, soap_header.partialFailure) <NEW_LINE> suds_client.set_options.assert_any_call( soapheaders=soap_header, headers=oauth_header) <NEW_LINE> <DEDENT> def testGetReportDownloadHeaders(self): <NEW_LINE> <INDENT> ccid = 'client customer id' <NEW_LINE> dev_token = 'developer token' <NEW_LINE> user_agent = 'user agent!' <NEW_LINE> oauth_header = {'Authorization': 'header'} <NEW_LINE> self.adwords_client.client_customer_id = ccid <NEW_LINE> self.adwords_client.developer_token = dev_token <NEW_LINE> self.adwords_client.user_agent = user_agent <NEW_LINE> self.adwords_client.oauth2_client.CreateHttpHeader.return_value = dict( oauth_header) <NEW_LINE> expected_return_value = { 'Content-type': 'application/x-www-form-urlencoded', 'developerToken': dev_token, 'clientCustomerId': ccid, 'returnMoneyInMicros': 'False', 'Authorization': 'header', 'User-Agent': ''.join([ user_agent, googleads.adwords._AdWordsHeaderHandler._LIB_SIG, ',gzip']) } <NEW_LINE> expected_return_value['returnMoneyInMicros'] = 'True' <NEW_LINE> self.assertEqual(expected_return_value, self.header_handler.GetReportDownloadHeaders(True)) <NEW_LINE> expected_return_value['returnMoneyInMicros'] = 'False' <NEW_LINE> self.adwords_client.oauth2_client.CreateHttpHeader.return_value = dict( oauth_header) <NEW_LINE> self.assertEqual(expected_return_value, self.header_handler.GetReportDownloadHeaders(False)) <NEW_LINE> del expected_return_value['returnMoneyInMicros'] <NEW_LINE> self.adwords_client.oauth2_client.CreateHttpHeader.return_value = dict( oauth_header) <NEW_LINE> self.assertEqual(expected_return_value, self.header_handler.GetReportDownloadHeaders())
Tests for the googleads.adwords._AdWordsHeaderHandler class.
62598f9fd7e4931a7ef3beab
class BaseTeamSchema(ModelSchema): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Team <NEW_LINE> fields = ( 'id', 'title', ) <NEW_LINE> dump_only = ( 'id', )
Base team schema exposes only the most general fields.
62598f9fcb5e8a47e493c07e
class SplineRegression(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.betas = None <NEW_LINE> self.intercepts = None <NEW_LINE> self.cutpoints = None <NEW_LINE> self._betas = None <NEW_LINE> <DEDENT> def fit(self, xs, ys, cutpoints = []): <NEW_LINE> <INDENT> if isinstance(xs, np.ndarray) and isinstance(ys, np.ndarray) and len(xs) == len(ys): <NEW_LINE> <INDENT> cutpoints = list(cutpoints) <NEW_LINE> if cutpoints == [] or type(cutpoints[0]) in [int,float,long]: <NEW_LINE> <INDENT> lr = LinearRegression() <NEW_LINE> self.cutpoints = cutpoints <NEW_LINE> cuts = [min(xs)] + cutpoints + [max(xs)] <NEW_LINE> betas = [] <NEW_LINE> intercepts = [] <NEW_LINE> for i in range(1, len(cuts)): <NEW_LINE> <INDENT> sub_mask = (xs >= cuts[i - 1]) & (xs <= cuts[i]) <NEW_LINE> lr.fit(xs[sub_mask].reshape(-1, 1), ys[sub_mask].reshape(-1, 1)) <NEW_LINE> betas.append(lr.coef_[0][0]) <NEW_LINE> intercepts.append(lr.intercept_[0]) <NEW_LINE> self.betas = np.array(betas) <NEW_LINE> self._betas = self.betas - np.hstack([0, self.betas[:-1]]) <NEW_LINE> self.intercepts = np.array(intercepts) <NEW_LINE> <DEDENT> return self.betas, self.intercepts <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("The values in cutpoints must be numeric") <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Make sure xs and ys are both Numpy Arrays of the same length") <NEW_LINE> <DEDENT> <DEDENT> def predict(self, xs): <NEW_LINE> <INDENT> if self.betas is None: <NEW_LINE> <INDENT> raise BaseException("Cannot call predict before a model is fitted") <NEW_LINE> <DEDENT> if isinstance(xs, np.ndarray) and len(xs) > 0: <NEW_LINE> <INDENT> zero = np.zeros(len(xs)) <NEW_LINE> result = self.intercepts[0] + xs * self._betas[0] <NEW_LINE> for beta, cutpoint in zip(self._betas[1:], self.cutpoints): <NEW_LINE> <INDENT> result += np.maximum(zero, xs - cutpoint) * beta <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> elif not xs: <NEW_LINE> <INDENT> raise ValueError("xs array cannot be empty!") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError("xs must be a Numpy Array")
Class which implements linear regression using simple splines to fit non-linear patterns
62598f9f60cbc95b0636415f
class MaxWidth(MaxExtent): <NEW_LINE> <INDENT> def __init__(self, artist_list): <NEW_LINE> <INDENT> super().__init__(artist_list, "width")
Size whose absolute part is the largest width of the given *artist_list*.
62598f9f9c8ee82313040077
class AcceptPreferenceList(PreferenceList): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(AcceptPreferenceList, self).__init__(AcceptPreference, **kwargs)
Subclass of :class:`PreferenceList` for HTTP ``Accept`` headers.
62598f9f097d151d1a2c0e3b
class ExceptionInfo(object): <NEW_LINE> <INDENT> tb_info_type = TracebackInfo <NEW_LINE> def __init__(self, exc_type, exc_msg, tb_info): <NEW_LINE> <INDENT> self.exc_type = exc_type <NEW_LINE> self.exc_msg = exc_msg <NEW_LINE> self.tb_info = tb_info <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_exc_info(cls, exc_type, exc_value, traceback): <NEW_LINE> <INDENT> type_str = exc_type.__name__ <NEW_LINE> type_mod = exc_type.__module__ <NEW_LINE> if type_mod not in ("__main__", "__builtin__", "exceptions", "builtins"): <NEW_LINE> <INDENT> type_str = '%s.%s' % (type_mod, type_str) <NEW_LINE> <DEDENT> val_str = _some_str(exc_value) <NEW_LINE> tb_info = cls.tb_info_type.from_traceback(traceback) <NEW_LINE> return cls(type_str, val_str, tb_info) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_current(cls): <NEW_LINE> <INDENT> return cls.from_exc_info(*sys.exc_info()) <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> return {'exc_type': self.exc_type, 'exc_msg': self.exc_msg, 'exc_tb': self.tb_info.to_dict()} <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> cn = self.__class__.__name__ <NEW_LINE> try: <NEW_LINE> <INDENT> len_frames = len(self.tb_info.frames) <NEW_LINE> last_frame = ', last=%r' % (self.tb_info.frames[-1],) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> len_frames = 0 <NEW_LINE> last_frame = '' <NEW_LINE> <DEDENT> args = (cn, self.exc_type, self.exc_msg, len_frames, last_frame) <NEW_LINE> return '<%s [%s: %s] (%s frames%s)>' % args <NEW_LINE> <DEDENT> def get_formatted(self): <NEW_LINE> <INDENT> tb_str = self.tb_info.get_formatted() <NEW_LINE> return ''.join([tb_str, '%s: %s' % (self.exc_type, self.exc_msg)]) <NEW_LINE> <DEDENT> def get_formatted_exception_only(self): <NEW_LINE> <INDENT> return '%s: %s' % (self.exc_type, self.exc_msg)
An ExceptionInfo object ties together three main fields suitable for representing an instance of an exception: The exception type name, a string representation of the exception itself (the exception message), and information about the traceback (stored as a :class:`TracebackInfo` object). These fields line up with :func:`sys.exc_info`, but unlike the values returned by that function, ExceptionInfo does not hold any references to the real exception or traceback. This property makes it suitable for serialization or long-term retention, without worrying about formatting pitfalls, circular references, or leaking memory. Args: exc_type (str): The exception type name. exc_msg (str): String representation of the exception value. tb_info (TracebackInfo): Information about the stack trace of the exception. Like the :class:`TracebackInfo`, ExceptionInfo is most commonly instantiated from one of its classmethods: :meth:`from_exc_info` or :meth:`from_current`.
62598f9f01c39578d7f12b90
class Conjugated(XForm): <NEW_LINE> <INDENT> def __init__(self, original, conjugate_by): <NEW_LINE> <INDENT> self.A = original <NEW_LINE> self.B = conjugate_by <NEW_LINE> self.B_inv = conjugate_by.inverse <NEW_LINE> if self.B_inv is None: <NEW_LINE> <INDENT> raise ValueError("conjugate_by must have an inverse") <NEW_LINE> <DEDENT> <DEDENT> def transform(self, point): <NEW_LINE> <INDENT> change_coords = self.B_inv.transform(point) <NEW_LINE> xformed = self.A.transform(change_coords) <NEW_LINE> restore_coords = self.B.transform(xformed) <NEW_LINE> return restore_coords <NEW_LINE> <DEDENT> def jacobian(self, point): <NEW_LINE> <INDENT> jac_B = self.B.jacobian(point) <NEW_LINE> jac_A = self.A.jacobian(point) <NEW_LINE> jac_B_inv = self.B_inv.jacobian(point) <NEW_LINE> return jac_B * jac_A * jac_B_inv <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def cylindrical_xform(cls, xform): <NEW_LINE> <INDENT> return cls(xform, CylindricalToCartesian)
Conjugate XForm A by an invertible XForm B by applying: C = B * A * B^(-1) This is useful for changing coordinate systems. For example, to apply a radial scaling, conjugate by a transformation to Cylindrical coordinates (well, in this case a Conjugated(Scale(scale_factor, 1, 1), CylindricalToCartesian())
62598f9f30bbd72246469880
class IEC104_IO_C_RP_NA_1_IOA(IEC104_IO_C_RP_NA_1): <NEW_LINE> <INDENT> name = 'C_RP_NA_1 (+ioa)' <NEW_LINE> fields_desc = [LEThreeBytesField('information_object_address', 0)] + IEC104_IO_C_RP_NA_1.fields_desc
extended version of IEC104_IO_C_RP_NA_1 containing an individual information object address
62598f9f442bda511e95c26e
class NumpyEncoder(json.JSONEncoder): <NEW_LINE> <INDENT> def default(self, obj): <NEW_LINE> <INDENT> if isinstance(obj, np.ndarray): <NEW_LINE> <INDENT> if obj.flags['C_CONTIGUOUS']: <NEW_LINE> <INDENT> obj_data = obj.data <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cont_obj = np.ascontiguousarray(obj) <NEW_LINE> assert(cont_obj.flags['C_CONTIGUOUS']) <NEW_LINE> obj_data = cont_obj.data <NEW_LINE> <DEDENT> data_b64 = base64.b64encode(obj_data) <NEW_LINE> return dict(__ndarray__=data_b64, dtype=str(obj.dtype), shape=obj.shape) <NEW_LINE> <DEDENT> return json.JSONEncoder(self, obj)
JSON encoder that supports numpy arrays. References ---------- http://stackoverflow.com/a/24375113/1150961
62598f9ff8510a7c17d7e081
class Solution: <NEW_LINE> <INDENT> def search(self, A, target): <NEW_LINE> <INDENT> start, end = 0, len(A) - 1 <NEW_LINE> while(start <= end): <NEW_LINE> <INDENT> i = (start + end) / 2 <NEW_LINE> if (A[i] == target): <NEW_LINE> <INDENT> return i <NEW_LINE> <DEDENT> if (A[i] > A[start]): <NEW_LINE> <INDENT> if(target >= A[start] and target < A[i]): <NEW_LINE> <INDENT> end = i - 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> start = i + 1 <NEW_LINE> <DEDENT> <DEDENT> elif (A[i] < A[start]): <NEW_LINE> <INDENT> if(target > A[i] and target <= A[end]): <NEW_LINE> <INDENT> start = i + 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> end = i - 1 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> start += 1 <NEW_LINE> <DEDENT> <DEDENT> return -1
@param A : a list of integers @param target : an integer to be searched @return : an integer
62598f9f0c0af96317c56194
class Product(models.Model): <NEW_LINE> <INDENT> category = models.ForeignKey(Category, related_name='products', on_delete=models.DO_NOTHING, verbose_name='Категория товара') <NEW_LINE> name = models.CharField(max_length=200, db_index=True, verbose_name='Имя товара') <NEW_LINE> slug = models.SlugField(max_length=200, db_index=True) <NEW_LINE> image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, verbose_name='Изображение товара') <NEW_LINE> description = models.TextField(blank=True, verbose_name='Описание') <NEW_LINE> price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='Цена') <NEW_LINE> stock = models.PositiveIntegerField() <NEW_LINE> available = models.BooleanField(default=True, verbose_name='Товар доступен для заказа') <NEW_LINE> created = models.DateTimeField(auto_now_add=True, verbose_name='Дата публикации товара') <NEW_LINE> updated = models.DateTimeField( auto_now=True, verbose_name='Дата обновления информации о товаре' ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ('name',) <NEW_LINE> index_together = (('id', 'slug'),) <NEW_LINE> verbose_name = 'Продукт' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('shop:product_detail', args=[self.id, self.slug])
The product
62598f9f56b00c62f0fb26c3
class TestCompareXLSXFiles(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.maxDiff = None <NEW_LINE> filename = 'set_column08.xlsx' <NEW_LINE> test_dir = 'xlsxwriter/test/comparison/' <NEW_LINE> self.image_dir = test_dir + 'images/' <NEW_LINE> self.got_filename = test_dir + '_test_' + filename <NEW_LINE> self.exp_filename = test_dir + 'xlsx_files/' + filename <NEW_LINE> self.ignore_files = [] <NEW_LINE> self.ignore_elements = {} <NEW_LINE> <DEDENT> def test_create_file(self): <NEW_LINE> <INDENT> filename = self.got_filename <NEW_LINE> workbook = Workbook(filename) <NEW_LINE> worksheet = workbook.add_worksheet() <NEW_LINE> bold = workbook.add_format({'bold': 1}) <NEW_LINE> italic = workbook.add_format({'italic': 1}) <NEW_LINE> data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] <NEW_LINE> worksheet.write('A1', 'Foo', bold) <NEW_LINE> worksheet.write('B1', 'Bar', italic) <NEW_LINE> worksheet.write_column('A2', data[0]) <NEW_LINE> worksheet.write_column('B2', data[1]) <NEW_LINE> worksheet.write_column('C2', data[2]) <NEW_LINE> worksheet.set_row(12, None, None, {'hidden': True}) <NEW_LINE> worksheet.set_column('F:F', None, None, {'hidden': True}) <NEW_LINE> worksheet.insert_image('E12', self.image_dir + 'logo.png') <NEW_LINE> workbook.close() <NEW_LINE> got, exp = _compare_xlsx_files(self.got_filename, self.exp_filename, self.ignore_files, self.ignore_elements) <NEW_LINE> self.assertEqual(got, exp) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> if os.path.exists(self.got_filename): <NEW_LINE> <INDENT> os.remove(self.got_filename)
Test file created by XlsxWriter against a file created by Excel.
62598f9f6aa9bd52df0d4cde
class Pitch(mlbgame.object.Object): <NEW_LINE> <INDENT> def nice_output(self): <NEW_LINE> <INDENT> return 'Pitch: {0} at {1}: {2}'.format( self.pitch_type, self.start_speed, self.des) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.nice_output()
Class that holds information about individual pitches. Properties: des des_es pitch_type start_speed sv_id type Additional properties if `self._endpoint == 'innings'`: id code tfs tfs_zulu x y event_num sv_id play_guid end_speed sz_top sz_bot pfx_x pfx_z px pz x0 y0 z0 vx0 vy0 vz0 ax ay az break_y break_angle break_length type_confidence zone nasty spin_dir spin_rate cc mt
62598f9f38b623060ffa8ea6
@python_2_unicode_compatible <NEW_LINE> class BrowserIDException(Exception): <NEW_LINE> <INDENT> def __init__(self, exc): <NEW_LINE> <INDENT> self.exc = exc <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return six.text_type(self.exc)
Raised when there is an issue verifying an assertion.
62598f9f1f037a2d8b9e3efb
@dataclass <NEW_LINE> class P148HasComponent: <NEW_LINE> <INDENT> URI = "http://erlangen-crm.org/current/P148_has_component"
Scope note: This property associates an instance of E89 Propositional Object with a structural part of it that is by itself an instance of E89 Propositional Object. This property is transitive Examples: - Dante's "Divine Comedy" (E89) has component Dante's "Hell" (E89) In First Order Logic: P148(x,y) &#8835; E89(x) P148(x,y) &#8835; E89(y)
62598f9f7cff6e4e811b5837
class MessageThread(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'message_threads' <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> user1 = db.Column(db.Integer, db.ForeignKey('users.id')) <NEW_LINE> user2 = db.Column(db.Integer, db.ForeignKey('users.id')) <NEW_LINE> title = db.Column(db.Unicode, nullable=True) <NEW_LINE> order_id = db.Column(db.Integer, db.ForeignKey('orders.id')) <NEW_LINE> messages = db.relationship('Message', backref='thread', lazy='dynamic') <NEW_LINE> def __init__(self, user1, user2, title=None): <NEW_LINE> <INDENT> self.user1 = user1 <NEW_LINE> self.user2 = user2 <NEW_LINE> self.title = title <NEW_LINE> <DEDENT> def isParticipant(self, user): <NEW_LINE> <INDENT> return self.user1 == user or self.user2 == user <NEW_LINE> <DEDENT> def otherUser(self, user): <NEW_LINE> <INDENT> if self.isParticipant(user): <NEW_LINE> <INDENT> user_id = self.user2 if self.user1 == user else self.user1 <NEW_LINE> return User.query.filter_by(id=user_id).first() <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def unseen(self, user): <NEW_LINE> <INDENT> other_id = self.otherUser(user).id <NEW_LINE> return self.messages.filter(and_(Message.sender_id == other_id, Message.seen is None)).count() <NEW_LINE> <DEDENT> def getTitle(self): <NEW_LINE> <INDENT> return self.title if self.title is not None else 'Untitled Thread'
Database model for message threads. Contains: - id: int, auto-incremented. - user1: int, foreign key. - user2: int, foreign key. - title: string. Optional. - order_id: int, foreign key (if about an order).
62598f9f3eb6a72ae038a455
class LaunchWindow(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=255) <NEW_LINE> description = models.TextField() <NEW_LINE> cron_format = models.CharField(max_length=255, blank=True, null=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.name
Defines a period of time that deployments can be made in
62598f9f67a9b606de545ddd
class BasePolicy(object): <NEW_LINE> <INDENT> __metaclass__ = abc.ABCMeta <NEW_LINE> @abc.abstractmethod <NEW_LINE> def get_action(self, state): <NEW_LINE> <INDENT> raise NotImplemented <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def evaluate(self, state): <NEW_LINE> <INDENT> raise NotImplemented
Base Policy
62598f9f24f1403a926857bc
class PathAccessError(AttributeError, KeyError, IndexError, GlomError): <NEW_LINE> <INDENT> def __init__(self, exc, path, part_idx): <NEW_LINE> <INDENT> self.exc = exc <NEW_LINE> self.path = path <NEW_LINE> self.part_idx = part_idx <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> cn = self.__class__.__name__ <NEW_LINE> return '%s(%r, %r, %r)' % (cn, self.exc, self.path, self.part_idx) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ('could not access %r, part %r of %r, got error: %r' % (self.path.values()[self.part_idx], self.part_idx, self.path, self.exc))
This :exc:`GlomError` subtype represents a failure to access an attribute as dictated by the spec. The most commonly-seen error when using glom, it maintains a copy of the original exception and produces a readable error message for easy debugging. If you see this error, you may want to: * Check the target data is accurate using :class:`~glom.Inspect` * Catch the exception and return a semantically meaningful error message * Use :class:`glom.Coalesce` to specify a default * Use the top-level ``default`` kwarg on :func:`~glom.glom()` In any case, be glad you got this error and not the one it was wrapping! Args: exc (Exception): The error that arose when we tried to access *path*. Typically an instance of KeyError, AttributeError, IndexError, or TypeError, and sometimes others. path (Path): The full Path glom was in the middle of accessing when the error occurred. part_idx (int): The index of the part of the *path* that caused the error. >>> target = {'a': {'b': None}} >>> glom(target, 'a.b.c') Traceback (most recent call last): ... PathAccessError: could not access 'c', part 2 of Path('a', 'b', 'c'), got error: ...
62598f9f009cb60464d01339
class WalletTransactionIdempotencyKey(ModelSimple): <NEW_LINE> <INDENT> allowed_values = { } <NEW_LINE> validations = { ('value',): { 'max_length': 128, 'min_length': 1, }, } <NEW_LINE> additional_properties_type = None <NEW_LINE> _nullable = False <NEW_LINE> @cached_property <NEW_LINE> def openapi_types(): <NEW_LINE> <INDENT> return { 'value': (str,), } <NEW_LINE> <DEDENT> @cached_property <NEW_LINE> def discriminator(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> attribute_map = {} <NEW_LINE> _composed_schemas = None <NEW_LINE> required_properties = set([ '_data_store', '_check_type', '_spec_property_naming', '_path_to_item', '_configuration', '_visited_composed_classes', ]) <NEW_LINE> @convert_js_args_to_python_args <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> _path_to_item = kwargs.pop('_path_to_item', ()) <NEW_LINE> if 'value' in kwargs: <NEW_LINE> <INDENT> value = kwargs.pop('value') <NEW_LINE> <DEDENT> elif args: <NEW_LINE> <INDENT> args = list(args) <NEW_LINE> value = args.pop(0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ApiTypeError( "value is required, but not passed in args or kwargs and doesn't have default", path_to_item=_path_to_item, valid_classes=(self.__class__,), ) <NEW_LINE> <DEDENT> _check_type = kwargs.pop('_check_type', True) <NEW_LINE> _spec_property_naming = kwargs.pop('_spec_property_naming', False) <NEW_LINE> _configuration = kwargs.pop('_configuration', None) <NEW_LINE> _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) <NEW_LINE> if args: <NEW_LINE> <INDENT> raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) <NEW_LINE> <DEDENT> self._data_store = {} <NEW_LINE> self._check_type = _check_type <NEW_LINE> self._spec_property_naming = _spec_property_naming <NEW_LINE> self._path_to_item = _path_to_item <NEW_LINE> self._configuration = _configuration <NEW_LINE> self._visited_composed_classes = _visited_composed_classes + (self.__class__,) <NEW_LINE> self.value = value <NEW_LINE> if kwargs: <NEW_LINE> <INDENT> raise ApiTypeError( "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( kwargs, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), )
NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a capitalized key describing the allowed value and an allowed value. These dicts store the allowed enum values. validations (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict that stores validations for max_length, min_length, max_items, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, inclusive_minimum, and regex. additional_properties_type (tuple): A tuple of classes accepted as additional properties values.
62598f9fd7e4931a7ef3beac
class ColorFormatter(logging.Formatter): <NEW_LINE> <INDENT> _levelMap = _levelMap <NEW_LINE> _tagMap = _tagMap <NEW_LINE> def __init__(self, fmt=None, datefmt=None): <NEW_LINE> <INDENT> if fmt is None: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif isinstance(fmt, dict): <NEW_LINE> <INDENT> for level in fmt: <NEW_LINE> <INDENT> if level in fmt.keys(): <NEW_LINE> <INDENT> _levelMap[level] = fmt[level] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Wrong format: %s' % type(fmt).__name__) <NEW_LINE> <DEDENT> super(ColorFormatter, self).__init__(None, datefmt) <NEW_LINE> self.datefmt = datefmt <NEW_LINE> <DEDENT> def format(self, record): <NEW_LINE> <INDENT> from string import Template <NEW_LINE> record.message = record.getMessage() <NEW_LINE> if self.usesTime(): <NEW_LINE> <INDENT> record.asctime = self.formatTime(record, self.datefmt) <NEW_LINE> <DEDENT> _fmt = self._levelMap[record.levelno] <NEW_LINE> _fmt = self.doTagMap(_fmt) <NEW_LINE> _tpl = Template(_fmt) <NEW_LINE> tmlArgs = dict(record.__dict__) <NEW_LINE> r = _tpl.substitute(tmlArgs) <NEW_LINE> return r <NEW_LINE> <DEDENT> def doTagMap(self, _fmt): <NEW_LINE> <INDENT> for i in self._tagMap: <NEW_LINE> <INDENT> _fmt = _fmt.replace(i, self._tagMap[i]) <NEW_LINE> <DEDENT> return _fmt
ColorFormater Class
62598f9fb7558d5895463442
class GDALRasterBase(GDALBase): <NEW_LINE> <INDENT> @property <NEW_LINE> def metadata(self): <NEW_LINE> <INDENT> if not capi.get_ds_metadata_domain_list: <NEW_LINE> <INDENT> raise ValueError('GDAL ≥ 1.11 is required for using the metadata property.') <NEW_LINE> <DEDENT> domain_list = ['DEFAULT'] <NEW_LINE> meta_list = capi.get_ds_metadata_domain_list(self._ptr) <NEW_LINE> if meta_list: <NEW_LINE> <INDENT> counter = 0 <NEW_LINE> domain = meta_list[counter] <NEW_LINE> while domain: <NEW_LINE> <INDENT> domain_list.append(domain.decode()) <NEW_LINE> counter += 1 <NEW_LINE> domain = meta_list[counter] <NEW_LINE> <DEDENT> <DEDENT> capi.free_dsl(meta_list) <NEW_LINE> result = {} <NEW_LINE> for domain in domain_list: <NEW_LINE> <INDENT> data = capi.get_ds_metadata( self._ptr, (None if domain == 'DEFAULT' else domain.encode()), ) <NEW_LINE> if not data: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> domain_meta = {} <NEW_LINE> counter = 0 <NEW_LINE> item = data[counter] <NEW_LINE> while item: <NEW_LINE> <INDENT> key, val = item.decode().split('=') <NEW_LINE> domain_meta[key] = val <NEW_LINE> counter += 1 <NEW_LINE> item = data[counter] <NEW_LINE> <DEDENT> result[domain or 'DEFAULT'] = domain_meta <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> @metadata.setter <NEW_LINE> def metadata(self, value): <NEW_LINE> <INDENT> for domain, metadata in value.items(): <NEW_LINE> <INDENT> domain = None if domain == 'DEFAULT' else domain.encode() <NEW_LINE> for meta_name, meta_value in metadata.items(): <NEW_LINE> <INDENT> capi.set_ds_metadata_item( self._ptr, meta_name.encode(), meta_value.encode() if meta_value else None, domain, )
Attributes that exist on both GDALRaster and GDALBand.
62598f9f4f6381625f1993c6
class Linker(Executor): <NEW_LINE> <INDENT> def can_handle(self, directive): <NEW_LINE> <INDENT> return directive == 'link' <NEW_LINE> <DEDENT> def handle(self, directive, data): <NEW_LINE> <INDENT> if directive != 'link': <NEW_LINE> <INDENT> raise ValueError('Linker cannot handle directive %s' % directive) <NEW_LINE> <DEDENT> return self._process_links(data) <NEW_LINE> <DEDENT> def _process_links(self, links): <NEW_LINE> <INDENT> success = True <NEW_LINE> for destination, source in links.items(): <NEW_LINE> <INDENT> success &= self._link(source, destination) <NEW_LINE> <DEDENT> if success: <NEW_LINE> <INDENT> self._log.info('All links have been set up') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._log.error('Some links were not successfully set up') <NEW_LINE> <DEDENT> return success <NEW_LINE> <DEDENT> def _is_link(self, path): <NEW_LINE> <INDENT> return os.path.islink(os.path.expanduser(path)) <NEW_LINE> <DEDENT> def _link_destination(self, path): <NEW_LINE> <INDENT> path = os.path.expanduser(path) <NEW_LINE> rel_dest = os.readlink(path) <NEW_LINE> return os.path.join(os.path.dirname(path), rel_dest) <NEW_LINE> <DEDENT> def _exists(self, path): <NEW_LINE> <INDENT> path = os.path.expanduser(path) <NEW_LINE> return os.path.exists(path) <NEW_LINE> <DEDENT> def _link(self, source, link_name): <NEW_LINE> <INDENT> success = False <NEW_LINE> source = os.path.join(self._base_directory, source) <NEW_LINE> if not self._exists(link_name) and self._is_link(link_name): <NEW_LINE> <INDENT> self._log.warning('Invalid link %s -> %s' % (link_name, self._link_destination(link_name))) <NEW_LINE> <DEDENT> elif not self._exists(link_name): <NEW_LINE> <INDENT> self._log.lowinfo('Creating link %s -> %s' % (link_name, source)) <NEW_LINE> os.symlink(source, os.path.expanduser(link_name)) <NEW_LINE> success = True <NEW_LINE> <DEDENT> elif self._exists(link_name) and not self._is_link(link_name): <NEW_LINE> <INDENT> self._log.warning( '%s already exists but is a regular file or directory' % link_name) <NEW_LINE> <DEDENT> elif self._link_destination(link_name) != source: <NEW_LINE> <INDENT> self._log.warning('Incorrect link %s -> %s' % (link_name, self._link_destination(link_name))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._log.lowinfo('Link exists %s -> %s' % (link_name, source)) <NEW_LINE> success = True <NEW_LINE> <DEDENT> return success
Symbolically links dotfiles.
62598f9f66656f66f7d5a205
class RazerChromaHDK(_RazerDeviceBrightnessSuspend): <NEW_LINE> <INDENT> USB_VID = 0x1532 <NEW_LINE> USB_PID = 0x0F09 <NEW_LINE> HAS_MATRIX = True <NEW_LINE> MATRIX_DIMS = [4, 16] <NEW_LINE> METHODS = ['get_device_type_accessory', 'set_static_effect', 'set_wave_effect', 'set_spectrum_effect', 'set_none_effect', 'set_breath_random_effect', 'set_breath_single_effect', 'set_breath_dual_effect', 'set_custom_effect', 'set_key_row'] <NEW_LINE> DEVICE_IMAGE = "https://assets2.razerzone.com/images/chromahdk2017/788b689d471fedbc0c5a175592316657-gallery-08.jpg"
Class for the Razer Chroma Hardware Development Kit (HDK)
62598f9f435de62698e9bc08
class HistogramMetricFamily(Metric): <NEW_LINE> <INDENT> def __init__(self, name, documentation, buckets=None, sum_value=None, labels=None): <NEW_LINE> <INDENT> Metric.__init__(self, name, documentation, 'histogram') <NEW_LINE> if (sum_value is None) != (buckets is None): <NEW_LINE> <INDENT> raise ValueError('buckets and sum_value must be provided together.') <NEW_LINE> <DEDENT> if labels is not None and buckets is not None: <NEW_LINE> <INDENT> raise ValueError('Can only specify at most one of buckets and labels.') <NEW_LINE> <DEDENT> if labels is None: <NEW_LINE> <INDENT> labels = [] <NEW_LINE> <DEDENT> self._labelnames = tuple(labels) <NEW_LINE> if buckets is not None: <NEW_LINE> <INDENT> self.add_metric([], buckets, sum_value) <NEW_LINE> <DEDENT> <DEDENT> def add_metric(self, labels, buckets, sum_value): <NEW_LINE> <INDENT> for bucket, value in buckets: <NEW_LINE> <INDENT> self.samples.append((self.name + '_bucket', dict(list(zip(self._labelnames, labels)) + [('le', bucket)]), value)) <NEW_LINE> <DEDENT> self.samples.append((self.name + '_count', dict(zip(self._labelnames, labels)), buckets[-1][1])) <NEW_LINE> self.samples.append((self.name + '_sum', dict(zip(self._labelnames, labels)), sum_value))
A single histogram and its samples. For use by custom collectors.
62598f9f442bda511e95c26f
class GraphicBox(object): <NEW_LINE> <INDENT> def __init__(self, image): <NEW_LINE> <INDENT> surface = image.load() <NEW_LINE> iw, self.th = surface.get_size() <NEW_LINE> self.tw = iw / 9 <NEW_LINE> names = "nw ne sw se n e s w c".split() <NEW_LINE> tiles = [ surface.subsurface((i*self.tw, 0, self.tw, self.th)) for i in range(len(names)) ] <NEW_LINE> self.tiles = dict(zip(names, tiles)) <NEW_LINE> self.tiles['c'] = self.tiles['c'].convert_alpha() <NEW_LINE> <DEDENT> def draw(self, surface, rect, fill=False): <NEW_LINE> <INDENT> ox, oy, w, h = Rect(rect) <NEW_LINE> if fill: <NEW_LINE> <INDENT> if isinstance(fill, int): <NEW_LINE> <INDENT> self.tiles['c'].set_alpha(fill) <NEW_LINE> <DEDENT> p = product(range(ox, w-ox, self.tw), range(oy, h-oy, self.th)) <NEW_LINE> [ surface.blit(self.tiles['c'], (x, y)) for x, y in p ] <NEW_LINE> <DEDENT> for x in range(self.tw+ox, w-self.tw+ox, self.tw): <NEW_LINE> <INDENT> surface.blit(self.tiles['n'], (x, oy)) <NEW_LINE> surface.blit(self.tiles['s'], (x, h-self.th+oy)) <NEW_LINE> <DEDENT> for y in range(self.th+oy, h-self.th+oy, self.th): <NEW_LINE> <INDENT> surface.blit(self.tiles['w'], (w-self.tw+ox, y)) <NEW_LINE> surface.blit(self.tiles['e'], (ox, y)) <NEW_LINE> <DEDENT> surface.blit(self.tiles['nw'], (ox, oy)) <NEW_LINE> surface.blit(self.tiles['ne'], (w-self.tw+ox, oy)) <NEW_LINE> surface.blit(self.tiles['se'], (ox, h-self.th+oy)) <NEW_LINE> surface.blit(self.tiles['sw'], (w-self.tw+ox, h-self.th+oy))
Generic class for drawing graphical boxes load it, then draw it wherever needed
62598f9f3539df3088ecc0c9
class SamDBTestCase(TestCaseInTempDir): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(SamDBTestCase, self).setUp() <NEW_LINE> self.session = system_session() <NEW_LINE> logger = logging.getLogger("selftest") <NEW_LINE> domain = "dsdb" <NEW_LINE> realm = "dsdb.samba.example.com" <NEW_LINE> host_name = "test" <NEW_LINE> server_role = "active directory domain controller" <NEW_LINE> dns_backend = "SAMBA_INTERNAL" <NEW_LINE> self.result = provision(logger, self.session, targetdir=self.tempdir, realm=realm, domain=domain, hostname=host_name, use_ntvfs=True, serverrole=server_role, dns_backend="SAMBA_INTERNAL", dom_for_fun_level=DS_DOMAIN_FUNCTION_2008_R2) <NEW_LINE> self.samdb = self.result.samdb <NEW_LINE> self.lp = self.result.lp <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> for f in ['names.tdb']: <NEW_LINE> <INDENT> os.remove(os.path.join(self.tempdir, f)) <NEW_LINE> <DEDENT> for d in ['etc', 'msg.lock', 'private', 'state']: <NEW_LINE> <INDENT> shutil.rmtree(os.path.join(self.tempdir, d)) <NEW_LINE> <DEDENT> super(SamDBTestCase, self).tearDown()
Base-class for tests with a Sam Database. This is used by the Samba SamDB-tests, but e.g. also by the OpenChange provisioning tests (which need a Sam).
62598f9fc432627299fa2ded
class RubStyle(Style): <NEW_LINE> <INDENT> default_style = 'autumn' <NEW_LINE> styles = { Whitespace: '#bbbbbb', Comment: 'italic #818181', Comment.Preproc: 'noitalic #4c8317', Comment.Special: 'italic #003560', Keyword: 'bold #003560', Keyword.Type: '#8dae10', Operator.Word: '#003560', Name.Builtin: '#8dae10', Name.Function: '#274800', Name.Class: 'underline #274800', Name.Namespace: 'underline #8dae10', Name.Variable: '#aa0000', Name.Constant: '#aa0000', Name.Entity: 'bold #800', Name.Attribute: '#8dae10', Name.Tag: 'bold #1e90ff', Name.Decorator: '#888888', String: '#336893', String.Symbol: '#003560', String.Regex: '#8dae10', Number: 'italic #8dae10', Generic.Heading: 'bold #000080', Generic.Subheading: 'bold #800080', Generic.Deleted: '#aa0000', Generic.Inserted: '#274800', Generic.Error: '#aa0000', Generic.Emph: 'italic', Generic.Strong: 'bold', Generic.Prompt: '#555555', Generic.Output: '#888888', Generic.Traceback: '#aa0000', Error: '#F00 bg:#FAA' }
A style based on the Corporate Design of the Ruhr-University Bochum.
62598f9f097d151d1a2c0e3d
class PoCSimulationResultNotFoundException(SkipableSimulatorException): <NEW_LINE> <INDENT> pass
This exception is raised if the expected PoC simulation result string was not found in the simulator's output.
62598f9fa17c0f6771d5c04e
class patient_PatientRepresent(S3Represent): <NEW_LINE> <INDENT> def lookup_rows(self, key, values, fields=[]): <NEW_LINE> <INDENT> table = self.table <NEW_LINE> ptable = current.s3db.pr_person <NEW_LINE> count = len(values) <NEW_LINE> if count == 1: <NEW_LINE> <INDENT> query = (key == values[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> query = (key.belongs(values)) <NEW_LINE> <DEDENT> left = ptable.on(table.person_id == ptable.id) <NEW_LINE> db = current.db <NEW_LINE> rows = db(query).select(patient_patient.id, pr_person.first_name, pr_person.middle_name, pr_person.last_name, limitby = (0, count), left = left) <NEW_LINE> self.queries += 1 <NEW_LINE> return rows <NEW_LINE> <DEDENT> def represent_row(self, row): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return s3_fullname(row) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return current.messages.UNKNOWN_OPT
Representation of Patient names by their full name
62598f9fa219f33f346c662e
class DepCheckProduces(Actor): <NEW_LINE> <INDENT> name = 'dep_check_produces' <NEW_LINE> consumes = () <NEW_LINE> produces = (DepCheck1, DepCheck3) <NEW_LINE> tags = (FirstPhaseTag, WorkflowApiTestWorkflowTag) <NEW_LINE> def process(self): <NEW_LINE> <INDENT> self.produce(DepCheck1(), DepCheck3())
Produces messages DepCheck1 and DepCheck3 which are going to be consumed by the DepCheckAPI1 and DepCheckAPI3 APIs.
62598f9f32920d7e50bc5e6a
class IOHandler: <NEW_LINE> <INDENT> __metaclass__ = ABCMeta <NEW_LINE> @abstractmethod <NEW_LINE> def fileno(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def is_readable(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def wait_for_readability(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def is_writable(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def prepare(self): <NEW_LINE> <INDENT> return HandlerReady() <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def wait_for_writability(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def handle_write(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def handle_read(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def handle_hup(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def handle_err(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def handle_nval(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def close(self): <NEW_LINE> <INDENT> pass
Wrapper for a socket or a file descriptor to be used in event loop or for I/O threads.
62598f9ff8510a7c17d7e082
class VSEQF_UL_QuickMarkerPresetList(bpy.types.UIList): <NEW_LINE> <INDENT> def draw_item(self, context, layout, data, item, icon, active_data, active_propname): <NEW_LINE> <INDENT> del context, data, icon, active_data, active_propname <NEW_LINE> split = layout.split(factor=.9, align=True) <NEW_LINE> split.operator('vseqf.quickmarkers_place', text=item.text).marker = item.text <NEW_LINE> split.operator('vseqf.quickmarkers_remove_preset', text='', icon='X').marker = item.text <NEW_LINE> <DEDENT> def draw_filter(self, context, layout): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def filter_items(self, context, data, property): <NEW_LINE> <INDENT> del context <NEW_LINE> markers = getattr(data, property) <NEW_LINE> helper = bpy.types.UI_UL_list <NEW_LINE> flt_neworder = helper.sort_items_by_name(markers, 'text') <NEW_LINE> return [], flt_neworder
Draws an editable list of QuickMarker presets
62598f9f0c0af96317c56196
class DPPError(Exception): <NEW_LINE> <INDENT> pass
Error thrown for DPP violations.
62598f9f3d592f4c4edbace3
class ChangeEvent(BaseObject): <NEW_LINE> <INDENT> def __init__(self, api=None, field_name=None, id=None, previous_value=None, type=None, value=None, **kwargs): <NEW_LINE> <INDENT> self.api = api <NEW_LINE> self.field_name = field_name <NEW_LINE> self.id = id <NEW_LINE> self.previous_value = previous_value <NEW_LINE> self.type = type <NEW_LINE> self.value = value <NEW_LINE> for key, value in kwargs.items(): <NEW_LINE> <INDENT> setattr(self, key, value) <NEW_LINE> <DEDENT> for key in self.to_dict(): <NEW_LINE> <INDENT> if getattr(self, key) is None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._dirty_attributes.remove(key) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> continue
###################################################################### # Do not modify, this class is autogenerated by gen_classes.py # ######################################################################
62598f9fbaa26c4b54d4f0c4
class BackupFileHandler(BaseHandler): <NEW_LINE> <INDENT> allowed_methods = ('GET', 'POST', 'PUT', 'DELETE') <NEW_LINE> model = BackupFile <NEW_LINE> def read(self, request, backupid=None): <NEW_LINE> <INDENT> if backupid: <NEW_LINE> <INDENT> return BackupFile.objects.get(id=backupid) <NEW_LINE> <DEDENT> return {} <NEW_LINE> <DEDENT> def create(self, request, backupid): <NEW_LINE> <INDENT> backupfile = BackupFile.objects.get(pk=backupid) <NEW_LINE> if "file" in request.FILES: <NEW_LINE> <INDENT> postfile = request.FILES["file"] <NEW_LINE> backupfile.file.save(backupfile.name, postfile, save=True) <NEW_LINE> return {"message": "updated backup file"} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> response = rc.BAD_REQUEST <NEW_LINE> response.write("Invalid Request! no file in request.") <NEW_LINE> return response <NEW_LINE> <DEDENT> <DEDENT> def update(self, request, backupid): <NEW_LINE> <INDENT> backupfile = BackupFile.objects.get(pk=backupid) <NEW_LINE> try: <NEW_LINE> <INDENT> utils.write_request_to_field( request, backupfile.file, "%s_%s" % ("backup", backupfile.mfile.name) ) <NEW_LINE> return {"message": "updated backup file"} <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise
The piston handler for the :class:`.BackupFile` class BackupFiles are used internally by MServe for replication. This handler allows saving, upodating and reading of a BackupFile object and the related file.
62598f9f6aa9bd52df0d4ce0
class Courier(models.Model): <NEW_LINE> <INDENT> CourierId = models.AutoField(primary_key=True) <NEW_LINE> UserId = models.ForeignKey(User, on_delete=models.CASCADE) <NEW_LINE> CourierName = models.CharField(max_length=200, unique=True)
Класс для табилцы в БД с курьерами.
62598f9fa8370b77170f01f9
class LoggerManager(Singleton): <NEW_LINE> <INDENT> def init(self, debug=False): <NEW_LINE> <INDENT> path = os.environ[LOGGING_CONFIG_ENVIRONMENT_VARIABLE] if LOGGING_CONFIG_ENVIRONMENT_VARIABLE in os.environ else None <NEW_LINE> haveenv = path and os.path.isfile(path) <NEW_LINE> if path and not haveenv: <NEW_LINE> <INDENT> print >> os.stderr, 'WARNING: %s was set but %s was not found (using default configuration files instead)' % (LOGGING_CONFIG_ENVIRONMENT_VARIABLE, path) <NEW_LINE> <DEDENT> if path and haveenv: <NEW_LINE> <INDENT> config.replace_configuration(path) <NEW_LINE> if debug: <NEW_LINE> <INDENT> print >> sys.stderr, str(os.getpid()) + ' configured logging from ' + path <NEW_LINE> <DEDENT> <DEDENT> elif os.path.isfile(LOGGING_PRIMARY_FROM_FILE): <NEW_LINE> <INDENT> config.replace_configuration(LOGGING_PRIMARY_FROM_FILE) <NEW_LINE> if debug: <NEW_LINE> <INDENT> print >> sys.stderr, str(os.getpid()) + ' configured logging from ' + LOGGING_PRIMARY_FROM_FILE <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> path = pkg_resources.resource_filename('config', LOGGING_PRIMARY_FROM_EGG) <NEW_LINE> config.replace_configuration(path) <NEW_LINE> if debug: <NEW_LINE> <INDENT> print >> sys.stderr, str(os.getpid()) + ' configured logging from ' + path <NEW_LINE> <DEDENT> <DEDENT> if os.path.isfile(LOGGING_MI_OVERRIDE): <NEW_LINE> <INDENT> config.add_configuration(LOGGING_MI_OVERRIDE) <NEW_LINE> if debug: <NEW_LINE> <INDENT> print >> sys.stderr, str(os.getpid()) + ' supplemented logging from ' + path <NEW_LINE> <DEDENT> <DEDENT> elif os.path.isfile(LOGGING_CONTAINER_OVERRIDE): <NEW_LINE> <INDENT> config.add_configuration(LOGGING_CONTAINER_OVERRIDE) <NEW_LINE> if debug: <NEW_LINE> <INDENT> print >> sys.stderr, str(os.getpid()) + ' supplemented logging from ' + path
Logger Manager. Provides an interface to configure logging at runtime.
62598f9f91f36d47f2230dab
class CreateView(LoginRequiredMixin, NextMixin, FormMessageMixin, generic.CreateView): <NEW_LINE> <INDENT> model = Comment <NEW_LINE> form_class = CommentCreateForm <NEW_LINE> form_valid_message = _("The comment has been created successfully.") <NEW_LINE> @property <NEW_LINE> def default_next_url(self): <NEW_LINE> <INDENT> return reverse('kdo-present-detail', args=[self.present.pk]) <NEW_LINE> <DEDENT> def get_form_kwargs(self): <NEW_LINE> <INDENT> kwargs = super(CreateView, self).get_form_kwargs() <NEW_LINE> kwargs['user'] = self.request.user <NEW_LINE> kwargs['present'] = self.present <NEW_LINE> return kwargs <NEW_LINE> <DEDENT> def dispatch(self, request, *args, **kwargs): <NEW_LINE> <INDENT> self.present = get_object_or_404(Present, pk=kwargs['pk'], participants__user=request.user) <NEW_LINE> return super(CreateView, self).dispatch(request, *args, **kwargs)
Add a comment to the given present.
62598f9f16aa5153ce400315
class ProgressBar(wx.Gauge): <NEW_LINE> <INDENT> def __init__(self, parent): <NEW_LINE> <INDENT> wx.Gauge.__init__(self, parent, -1, 100) <NEW_LINE> self.parent = parent <NEW_LINE> self._Layout() <NEW_LINE> self.__bind_events() <NEW_LINE> <DEDENT> def __bind_events(self): <NEW_LINE> <INDENT> sub = Publisher.subscribe <NEW_LINE> sub(self._Layout, 'ProgressBar Reposition') <NEW_LINE> <DEDENT> def _Layout(self): <NEW_LINE> <INDENT> rect = self.Parent.GetFieldRect(2) <NEW_LINE> self.SetPosition((rect.x + 2, rect.y + 2)) <NEW_LINE> self.SetSize((rect.width - 4, rect.height - 4)) <NEW_LINE> self.Show() <NEW_LINE> <DEDENT> def SetPercentage(self, value): <NEW_LINE> <INDENT> self.SetValue(int(value)) <NEW_LINE> if (value >= 99): <NEW_LINE> <INDENT> self.SetValue(0) <NEW_LINE> <DEDENT> self.Refresh() <NEW_LINE> self.Update()
Progress bar / gauge.
62598f9f8e7ae83300ee8eb5
class DirectoryNode(StorageNode): <NEW_LINE> <INDENT> @retryable_transaction() <NEW_LINE> @fsync_commit <NEW_LINE> def make_file(self, name): <NEW_LINE> <INDENT> self._load() <NEW_LINE> return self._gateway.make_file(self.id, name) <NEW_LINE> <DEDENT> @retryable_transaction() <NEW_LINE> @fsync_commit <NEW_LINE> def make_subdirectory(self, name): <NEW_LINE> <INDENT> self._load() <NEW_LINE> return self._gateway.make_subdirectory(self.id, name) <NEW_LINE> <DEDENT> @retryable_transaction() <NEW_LINE> @fsync_commit <NEW_LINE> def make_tree(self, path): <NEW_LINE> <INDENT> self._load() <NEW_LINE> return self._gateway.make_tree(self.id, path) <NEW_LINE> <DEDENT> @retryable_transaction() <NEW_LINE> @fsync_commit <NEW_LINE> def share(self, user_id, share_name, readonly=False): <NEW_LINE> <INDENT> self._load() <NEW_LINE> return self._gateway.make_share(self.id, share_name, user_id=user_id, readonly=readonly) <NEW_LINE> <DEDENT> @retryable_transaction() <NEW_LINE> @fsync_commit <NEW_LINE> def make_shareoffer(self, email, share_name, readonly=False): <NEW_LINE> <INDENT> self._load() <NEW_LINE> return self._gateway.make_share(self.id, share_name, email=email, readonly=readonly) <NEW_LINE> <DEDENT> @fsync_readonly <NEW_LINE> def get_children(self, **kwargs): <NEW_LINE> <INDENT> self._load() <NEW_LINE> if self.has_children(): <NEW_LINE> <INDENT> return list(self._gateway.get_children(self.id, **kwargs)) <NEW_LINE> <DEDENT> return [] <NEW_LINE> <DEDENT> @fsync_readonly <NEW_LINE> def get_child_by_name(self, name, with_content=False): <NEW_LINE> <INDENT> self._load() <NEW_LINE> return self._gateway.get_child_by_name(self.id, name, with_content) <NEW_LINE> <DEDENT> @retryable_transaction() <NEW_LINE> @fsync_commit <NEW_LINE> def make_file_with_content(self, file_name, hash, crc32, size, deflated_size, storage_key, mimetype=None, enforce_quota=True, is_public=False, previous_hash=None, magic_hash=None): <NEW_LINE> <INDENT> self._load() <NEW_LINE> return self._gateway.make_file_with_content( self.id, file_name, hash, crc32, size, deflated_size, storage_key, mimetype=mimetype, enforce_quota=enforce_quota, is_public=is_public, previous_hash=previous_hash, magic_hash=magic_hash)
DAO for a Directory.
62598f9fe76e3b2f99fd884d
class Calculator(): <NEW_LINE> <INDENT> def add(self, firstOperand, secondOperand): <NEW_LINE> <INDENT> return firstOperand + secondOperand <NEW_LINE> <DEDENT> def subtract(self, firstOperand, secondOperand): <NEW_LINE> <INDENT> return firstOperand - secondOperand <NEW_LINE> <DEDENT> def multiply(self, firstOperand, secondOperand): <NEW_LINE> <INDENT> return firstOperand * secondOperand <NEW_LINE> <DEDENT> def divide(self, firstOperand, secondOperand): <NEW_LINE> <INDENT> return firstOperand / secondOperand
Performs the four basic mathematical operations Methods: add(number, number) subtract(number, number) multiply(number, number) divide(number,number)
62598f9f1f037a2d8b9e3efd
class MagikUI(webapp2.RequestHandler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> index_file = os.path.dirname(__file__) + "/../templates/index.html" <NEW_LINE> self.response.out.write(file(index_file).read()) <NEW_LINE> <DEDENT> def post(self): <NEW_LINE> <INDENT> cloud_name = self.request.get('cloud') <NEW_LINE> params = {"name" : cloud_name} <NEW_LINE> if cloud_name == "s3": <NEW_LINE> <INDENT> params["AWS_ACCESS_KEY"] = self.request.get('AWS_ACCESS_KEY') <NEW_LINE> params["AWS_SECRET_KEY"] = self.request.get('AWS_SECRET_KEY') <NEW_LINE> <DEDENT> elif cloud_name == "gcs": <NEW_LINE> <INDENT> params["GCS_ACCESS_KEY"] = self.request.get('GCS_ACCESS_KEY') <NEW_LINE> params["GCS_SECRET_KEY"] = self.request.get('GCS_SECRET_KEY') <NEW_LINE> <DEDENT> elif cloud_name == "walrus": <NEW_LINE> <INDENT> params["AWS_ACCESS_KEY"] = self.request.get('WALRUS_ACCESS_KEY') <NEW_LINE> params["AWS_SECRET_KEY"] = self.request.get('WALRUS_SECRET_KEY') <NEW_LINE> <DEDENT> elif cloud_name == "azure": <NEW_LINE> <INDENT> params["AZURE_ACCOUNT_NAME"] = self.request.get('AZURE_ACCOUNT_NAME') <NEW_LINE> params["AZURE_ACCOUNT_KEY"] = self.request.get('AZURE_ACCOUNT_KEY') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.response.out.write(json.dumps({ "success" : False, "failure_reason" : "need to specify a cloud" })) <NEW_LINE> return <NEW_LINE> <DEDENT> directive = self.request.get('directive') <NEW_LINE> if directive == "upload": <NEW_LINE> <INDENT> url = "{0}/{1}".format(self.request.get("upload_bucket"), self.request.get("upload_key")) <NEW_LINE> file_to_upload = self.request.get('upload_file') <NEW_LINE> request = requests.put("http://127.0.0.1:8080/{0}".format(url), params=params, data=file_to_upload) <NEW_LINE> <DEDENT> elif directive == "download": <NEW_LINE> <INDENT> url = "{0}/{1}".format(self.request.get("download_bucket"), self.request.get("download_key")) <NEW_LINE> request = requests.get("http://127.0.0.1:8080/{0}".format(url), params=params) <NEW_LINE> <DEDENT> elif directive == "delete": <NEW_LINE> <INDENT> url = "{0}/{1}".format(self.request.get("delete_bucket"), self.request.get("delete_key")) <NEW_LINE> request = requests.delete("http://127.0.0.1:8080/{0}".format(url), params=params) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.response.out.write(json.dumps({ "success" : False, "failure_reason" : "need to specify a directive" })) <NEW_LINE> return <NEW_LINE> <DEDENT> self.response.out.write(request.text)
MagikUI provides handlers that display a web interface to the Magik API. Specifically, it exposes a route that renders a web page to let users fill in data needed to issue a request (the GET route), and another route that performs the request (the POST route).
62598f9f91af0d3eaad39c21
class TermListView(RESTDispatch): <NEW_LINE> <INDENT> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> curr_term = get_current_active_term() <NEW_LINE> terms = { 'current': curr_term.json_data(), 'next': get_term_after(curr_term).json_data(), } <NEW_LINE> return self.json_response({'terms': terms})
Retrieves a list of Terms.
62598f9f009cb60464d0133a
class AttributeAlreadyChanged(MCVirtException): <NEW_LINE> <INDENT> pass
Attribute, user is trying to change, has already changed.
62598f9f3617ad0b5ee05f67
class Cliques(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.egonets='../egonets/' <NEW_LINE> self.edge_set='./edges/' <NEW_LINE> self.training_set='../Training/' <NEW_LINE> self.testing_egonets='./test_egonets/' <NEW_LINE> self.edge_set='./edges/' <NEW_LINE> self.cliques='./cliques/' <NEW_LINE> <DEDENT> def find_cliques(self, file_index): <NEW_LINE> <INDENT> filename=self.edge_set+str(file_index)+'.egonet.edges' <NEW_LINE> out_file=self.cliques+str(file_index)+'.cliques' <NEW_LINE> os.system('~/Desktop/graph_library/MaximalCliques/justTheCliques ' + filename + ' > ' + out_file + ' &') <NEW_LINE> <DEDENT> def find_all_cliques(self): <NEW_LINE> <INDENT> for filename in os.listdir(self.testing_egonets): <NEW_LINE> <INDENT> file_index=filename.split('.egonet')[0] <NEW_LINE> self.find_cliques(file_index)
Constructs max-cliques of various sizes over all test_egonets files
62598f9f56ac1b37e6302001
class KNNEvaluator(object): <NEW_LINE> <INDENT> def __init__(self, distance, k=3): <NEW_LINE> <INDENT> self._distance = distance <NEW_LINE> self._k = k <NEW_LINE> <DEDENT> def evaluate(self, evaluation_series, reference_set, *args): <NEW_LINE> <INDENT> distances = [self._distance(evaluation_series, s) for s in reference_set] <NEW_LINE> if len(distances) < self._k: <NEW_LINE> <INDENT> return float('NaN') <NEW_LINE> <DEDENT> d = heapq.nsmallest(self._k, distances)[self._k - 1] <NEW_LINE> return d <NEW_LINE> <DEDENT> def requires_symbolic_input(self): <NEW_LINE> <INDENT> return self._distance.IS_DISCRETE
k-Nearest Neighbors evaluator. Currently uses brute force to find the kNN distnce - this is the best we can do without extra information about the distance function.
62598f9f460517430c431f66
class DeleteFunctionResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.RequestId = params.get("RequestId")
DeleteFunction response structure.
62598f9ff548e778e596b3c3
class Pitch(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'pitches' <NEW_LINE> id = db.Column(db.Integer, primary_key = True) <NEW_LINE> category = db.Column(db.String(255)) <NEW_LINE> title = db.Column(db.String(255)) <NEW_LINE> posted = db.Column(db.DateTime,default=datetime.utcnow) <NEW_LINE> likes = db.Column(db.Integer) <NEW_LINE> dislikes = db.Column(db.Integer) <NEW_LINE> vote_count = db.Column(db.Integer) <NEW_LINE> user_id = db.Column(db.Integer, db.ForeignKey("users.id")) <NEW_LINE> Review = db.relationship("Review", backref = "pitch", lazy = "dynamic") <NEW_LINE> pitch_statement = db.Column(db.String()) <NEW_LINE> def like(self): <NEW_LINE> <INDENT> self.likes = self.likes + 1 <NEW_LINE> self.vote_count = self.likes - self.dislikes <NEW_LINE> db.session.add(self) <NEW_LINE> db.session.commit() <NEW_LINE> <DEDENT> def dislike(self): <NEW_LINE> <INDENT> self.dislikes = self.dislikes + 1 <NEW_LINE> self.vote_count = self.likes - self.dislikes <NEW_LINE> db.session.add(self) <NEW_LINE> db.session.commit() <NEW_LINE> <DEDENT> def save_pitch(self): <NEW_LINE> <INDENT> db.session.add(self) <NEW_LINE> db.session.commit() <NEW_LINE> <DEDENT> def get_reviews(self): <NEW_LINE> <INDENT> pitch = Pitch.query.filter_by(id = self.id).first() <NEW_LINE> Review = Review.query.filter_by(pitch_id = pitch.id).order_by(Review.posted.desc())
Pitch class to define the pitch objects
62598f9fd53ae8145f9182a4