code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class Tips(_tiw): <NEW_LINE> <INDENT> def __init__(self, text="Tips", idx=0, parent=None): <NEW_LINE> <INDENT> super(Tips, self).__init__(text=text, idx=idx, parent=parent) | Tips formatted help text ( with bulb icon )
| 625990747047854f46340cf2 |
class Trip(models.Model): <NEW_LINE> <INDENT> driver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='driver' ) <NEW_LINE> passengers = models.ManyToManyField(User, related_name='passengers', blank=True ) <NEW_LINE> departure_date = models.DateTimeField() <NEW_LINE> origin = models.CharField(max_length=255, default='') <NEW_LINE> destination = models.CharField(max_length=255, default='') <NEW_LINE> fee = models.DecimalField(default=0, max_digits=5, decimal_places=2) <NEW_LINE> is_canceled = models.BooleanField(default=False) <NEW_LINE> is_completed = models.BooleanField(default=False) <NEW_LINE> closed = models.BooleanField(default=False) | A Trip represents a single A-to-B trip with one driver and multiple passengers | 625990744f6381625f19a147 |
class MediaTypeModel(BaseMixin, me.Document): <NEW_LINE> <INDENT> media_type_id = me.IntField(primary_key=True) <NEW_LINE> media_type = me.StringField() <NEW_LINE> meta = {'collection': 'media_types'} | Media types | 62599074a8370b77170f1d05 |
class BoxField(Field): <NEW_LINE> <INDENT> def __init__(self, xpadding=0, ypadding=0): <NEW_LINE> <INDENT> super(BoxField, self).__init__() <NEW_LINE> self.xpadding = xpadding <NEW_LINE> self.ypadding = ypadding <NEW_LINE> <DEDENT> def add_rectangle(self, rectangle): <NEW_LINE> <INDENT> if not self.rectangles: <NEW_LINE> <INDENT> self.rectangles.append(PositionedRectangle(0, 0, rectangle)) <NEW_LINE> <DEDENT> elif len(self.rectangles) == 1: <NEW_LINE> <INDENT> tl = self.rectangles[0] <NEW_LINE> self.rectangles.append(PositionedRectangle(tl.rect.x + self.xpadding, 0, rectangle)) <NEW_LINE> <DEDENT> elif len(self.rectangles) == 2: <NEW_LINE> <INDENT> tl, tr = self.rectangles <NEW_LINE> maxy = max([tl.rect.y, tr.rect.y]) <NEW_LINE> xadjust = tr.rect.x - rectangle.x <NEW_LINE> self.rectangles.append(PositionedRectangle(tr.x, maxy + self.ypadding, rectangle)) <NEW_LINE> <DEDENT> elif len(self.rectangles) == 3: <NEW_LINE> <INDENT> br = self.rectangles[-1] <NEW_LINE> yadjust = br.rect.y - rectangle.y <NEW_LINE> self.rectangles.append(PositionedRectangle(0, br.y + yadjust, rectangle)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("BoxField can only accept 4 rectangles; " "You've packed too many images!") <NEW_LINE> <DEDENT> self.x, self.y = self.calculate_bounds() | A field that packs itself into a box, ie for rounded corner use. | 62599074ad47b63b2c5a9188 |
class SIRFStatusPV: <NEW_LINE> <INDENT> BIT_DISCONN = 0b000001 <NEW_LINE> BIT_SIINTLK = 0b000010 <NEW_LINE> BIT_LLINTLK = 0b000100 <NEW_LINE> BIT_AMPLERR = 0b001000 <NEW_LINE> BIT_PHSEERR = 0b010000 <NEW_LINE> BIT_DTUNERR = 0b100000 <NEW_LINE> PV_SIRIUS_INTLK = 0 <NEW_LINE> PV_LLRF_INTLK = 1 <NEW_LINE> PV_AMPL_ERR = 2 <NEW_LINE> PV_PHSE_ERR = 3 <NEW_LINE> PV_DTUN_ERR = 4 <NEW_LINE> def compute_update(self, computed_pv, updated_pv_name, value): <NEW_LINE> <INDENT> value = 0 <NEW_LINE> disconnected = not computed_pv.pvs[SIRFStatusPV.PV_SIRIUS_INTLK].connected or not computed_pv.pvs[SIRFStatusPV.PV_LLRF_INTLK].connected or not computed_pv.pvs[SIRFStatusPV.PV_AMPL_ERR].connected or not computed_pv.pvs[SIRFStatusPV.PV_PHSE_ERR].connected or not computed_pv.pvs[SIRFStatusPV.PV_DTUN_ERR].connected <NEW_LINE> if disconnected: <NEW_LINE> <INDENT> value |= SIRFStatusPV.BIT_DISCONN <NEW_LINE> value |= SIRFStatusPV.BIT_SIINTLK <NEW_LINE> value |= SIRFStatusPV.BIT_LLINTLK <NEW_LINE> value |= SIRFStatusPV.BIT_AMPLERR <NEW_LINE> value |= SIRFStatusPV.BIT_PHSEERR <NEW_LINE> value |= SIRFStatusPV.BIT_DTUNERR <NEW_LINE> return {'value': value} <NEW_LINE> <DEDENT> sts = computed_pv.pvs[SIRFStatusPV.PV_SIRIUS_INTLK].value <NEW_LINE> if sts != 0 or sts is None: <NEW_LINE> <INDENT> value |= SIRFStatusPV.BIT_SIINTLK <NEW_LINE> <DEDENT> sts = computed_pv.pvs[SIRFStatusPV.PV_LLRF_INTLK].value <NEW_LINE> if sts != 0 or sts is None: <NEW_LINE> <INDENT> value |= SIRFStatusPV.BIT_LLINTLK <NEW_LINE> <DEDENT> severity = computed_pv.pvs[SIRFStatusPV.PV_AMPL_ERR].severity <NEW_LINE> if severity != 0: <NEW_LINE> <INDENT> value |= SIRFStatusPV.BIT_AMPLERR <NEW_LINE> <DEDENT> severity = computed_pv.pvs[SIRFStatusPV.PV_PHSE_ERR].severity <NEW_LINE> if severity != 0: <NEW_LINE> <INDENT> value |= SIRFStatusPV.BIT_PHSEERR <NEW_LINE> <DEDENT> severity = computed_pv.pvs[SIRFStatusPV.PV_DTUN_ERR].severity <NEW_LINE> if severity != 0: <NEW_LINE> <INDENT> value |= SIRFStatusPV.BIT_DTUNERR <NEW_LINE> <DEDENT> return {'value': value} | SI RF Status PV. | 6259907455399d3f05627e53 |
class ClientMock(action_mocks.ActionMock): <NEW_LINE> <INDENT> in_rdfvalue = None <NEW_LINE> out_rdfvalues = [rdfvalue.RDFString] <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(ClientMock, self).__init__() <NEW_LINE> server_stubs.ClientActionStub.classes["ReturnHello"] = self <NEW_LINE> self.__name__ = "ReturnHello" <NEW_LINE> <DEDENT> def ReturnHello(self, _): <NEW_LINE> <INDENT> return [rdfvalue.RDFString("Hello World")] | Mock of client actions. | 625990744a966d76dd5f0824 |
class StringFormatter(object): <NEW_LINE> <INDENT> def __init__(self, format_string): <NEW_LINE> <INDENT> self.format_string = format_string <NEW_LINE> <DEDENT> def _get_format_string(self): <NEW_LINE> <INDENT> return self._format_string <NEW_LINE> <DEDENT> def _set_format_string(self, value): <NEW_LINE> <INDENT> self._format_string = value <NEW_LINE> self._formatter = F(value) <NEW_LINE> <DEDENT> format_string = property(_get_format_string, _set_format_string) <NEW_LINE> del _get_format_string, _set_format_string <NEW_LINE> def format_record(self, record, handler): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._formatter.format(record=record, handler=handler) <NEW_LINE> <DEDENT> except UnicodeEncodeError: <NEW_LINE> <INDENT> fmt = self._formatter.decode('ascii', 'replace') <NEW_LINE> return fmt.format(record=record, handler=handler) <NEW_LINE> <DEDENT> except UnicodeDecodeError: <NEW_LINE> <INDENT> fmt = self._formatter.encode('ascii', 'replace') <NEW_LINE> return fmt.format(record=record, handler=handler) <NEW_LINE> <DEDENT> <DEDENT> def format_exception(self, record): <NEW_LINE> <INDENT> return record.formatted_exception <NEW_LINE> <DEDENT> def __call__(self, record, handler): <NEW_LINE> <INDENT> line = self.format_record(record, handler) <NEW_LINE> exc = self.format_exception(record) <NEW_LINE> if exc: <NEW_LINE> <INDENT> line += six.u('\n') + exc <NEW_LINE> <DEDENT> return line | Many handlers format the log entries to text format. This is done
by a callable that is passed a log record and returns an unicode
string. The default formatter for this is implemented as a class so
that it becomes possible to hook into every aspect of the formatting
process. | 6259907421bff66bcd7245a3 |
class TestPropertyEc2Subnet(BaseRuleTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(TestPropertyEc2Subnet, self).setUp() <NEW_LINE> self.collection.register(Subnet()) <NEW_LINE> self.success_templates = [ 'test/fixtures/templates/good/properties_ec2_vpc.yaml', ] <NEW_LINE> <DEDENT> def test_file_positive(self): <NEW_LINE> <INDENT> self.helper_file_positive() <NEW_LINE> <DEDENT> def test_file_negative(self): <NEW_LINE> <INDENT> self.helper_file_negative('test/fixtures/templates/bad/properties_ec2_network.yaml', 4) | Test Ec2 Subnet Resources | 625990748e7ae83300eea9cd |
class NewToken(object): <NEW_LINE> <INDENT> swagger_types = { 'friendly_name': 'str' } <NEW_LINE> attribute_map = { 'friendly_name': 'friendlyName' } <NEW_LINE> def __init__(self, friendly_name=None): <NEW_LINE> <INDENT> self._friendly_name = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.friendly_name = friendly_name <NEW_LINE> <DEDENT> @property <NEW_LINE> def friendly_name(self): <NEW_LINE> <INDENT> return self._friendly_name <NEW_LINE> <DEDENT> @friendly_name.setter <NEW_LINE> def friendly_name(self, friendly_name): <NEW_LINE> <INDENT> if friendly_name is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `friendly_name`, must not be `None`") <NEW_LINE> <DEDENT> self._friendly_name = friendly_name <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(NewToken, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, NewToken): <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 | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 6259907426068e7796d4e277 |
class HTTPClient(object): <NEW_LINE> <INDENT> def __init__(self, url, method='GET', headers=None, cookies=None): <NEW_LINE> <INDENT> self.url = url <NEW_LINE> self.session = requests.session() <NEW_LINE> self.method = method.upper() <NEW_LINE> if self.method not in METHODS: <NEW_LINE> <INDENT> raise UnSupportMethodException('不支持的method:{0},请检查传入参数!'.format(self.method)) <NEW_LINE> <DEDENT> self.set_headers(headers) <NEW_LINE> self.set_cookies(cookies) <NEW_LINE> <DEDENT> def set_headers(self, headers): <NEW_LINE> <INDENT> if headers: <NEW_LINE> <INDENT> if(not isinstance(headers,(dict))): <NEW_LINE> <INDENT> headers = eval(headers) <NEW_LINE> <DEDENT> self.session.headers.update(headers) <NEW_LINE> <DEDENT> <DEDENT> def set_cookies(self, cookies): <NEW_LINE> <INDENT> if cookies: <NEW_LINE> <INDENT> self.session.cookies.update(cookies) <NEW_LINE> <DEDENT> <DEDENT> def send(self, params=None, data=None, **kwargs): <NEW_LINE> <INDENT> times = str(int(round(time.time() * 1000))) <NEW_LINE> return_data = "" <NEW_LINE> retime ="%{=time}%" <NEW_LINE> if( data != None): <NEW_LINE> <INDENT> data = json.dumps(data) <NEW_LINE> if(retime in data ): <NEW_LINE> <INDENT> data = data.replace(retime,times) <NEW_LINE> data = json.loads(data) <NEW_LINE> <DEDENT> return_data = data <NEW_LINE> <DEDENT> if ( params != None): <NEW_LINE> <INDENT> params = json.dumps(params) <NEW_LINE> if (retime in params): <NEW_LINE> <INDENT> params = params.replace(retime, times) <NEW_LINE> params = json.loads(params) <NEW_LINE> <DEDENT> return_data = params <NEW_LINE> <DEDENT> response = self.session.request(method=self.method, url=self.url, json=params, data=data, **kwargs) <NEW_LINE> response.encoding = 'utf-8' <NEW_LINE> return response, self.url, self.session.headers, return_data | http请求的client。初始化时传入url、method等,可以添加headers和cookies,但没有auth、proxy。
>>> HTTPClient('http://www.baidu.com').send()
<Response [200]> | 6259907401c39578d7f143d2 |
class TestMaxInteger(unittest.TestCase): <NEW_LINE> <INDENT> def test(self): <NEW_LINE> <INDENT> self.assertEqual(max_integer([2,3]), 3) <NEW_LINE> <DEDENT> def testFail(self): <NEW_LINE> <INDENT> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> max_integer(['f', 3]) <NEW_LINE> <DEDENT> <DEDENT> def testString(self): <NEW_LINE> <INDENT> self.assertEqual(max_integer('ddw'), 'w') <NEW_LINE> <DEDENT> def testListString(self): <NEW_LINE> <INDENT> self.assertEqual(max_integer(['hi', 'bye']), 'hi') <NEW_LINE> <DEDENT> def testMaxAtEnd(self): <NEW_LINE> <INDENT> self.assertEqual(max_integer([3, 2, 4]), 4) <NEW_LINE> <DEDENT> def testMaxAtBeginning(self): <NEW_LINE> <INDENT> self.assertEqual(max_integer([5, 2, 3]), 5) <NEW_LINE> <DEDENT> def testNegative(self): <NEW_LINE> <INDENT> self.assertEqual(max_integer([-1, 2]), 2) <NEW_LINE> <DEDENT> def testTwoNegative(self): <NEW_LINE> <INDENT> self.assertEqual(max_integer([-1, -4]), -1) <NEW_LINE> <DEDENT> def testMaxMiddle(self): <NEW_LINE> <INDENT> self.assertEqual(max_integer([1,5,2]), 5) <NEW_LINE> <DEDENT> def testOneNum(self): <NEW_LINE> <INDENT> self.assertEqual(max_integer([1]), 1) <NEW_LINE> <DEDENT> def testEmpty(self): <NEW_LINE> <INDENT> self.assertEqual(max_integer([]), None) | First time using Unittest | 6259907455399d3f05627e54 |
class TerminalNode(ASTNode.ASTNode): <NEW_LINE> <INDENT> def __init__(self, numeric=None, variables=None, symbol=None): <NEW_LINE> <INDENT> self.numeric = numeric <NEW_LINE> self.variables = variables <NEW_LINE> self.symbol = symbol <NEW_LINE> <DEDENT> def printAST(self): <NEW_LINE> <INDENT> print(self.symbol, end='') | ASTNode inherited class that implement the terminal node which have a value for evaluation. | 62599074aad79263cf4300f3 |
class Dataset(object): <NEW_LINE> <INDENT> def __init__(self, imgSeqs=None): <NEW_LINE> <INDENT> if imgSeqs is None: <NEW_LINE> <INDENT> self._imgSeqs = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._imgSeqs = imgSeqs <NEW_LINE> <DEDENT> self._imgStacks = {} <NEW_LINE> self._labelStacks = {} <NEW_LINE> <DEDENT> @property <NEW_LINE> def imgSeqs(self): <NEW_LINE> <INDENT> return self._imgSeqs <NEW_LINE> <DEDENT> def imgSeq(self, seqName): <NEW_LINE> <INDENT> for seq in self._imgSeqs: <NEW_LINE> <INDENT> if seq.name == seqName: <NEW_LINE> <INDENT> return seq <NEW_LINE> <DEDENT> <DEDENT> return [] <NEW_LINE> <DEDENT> @imgSeqs.setter <NEW_LINE> def imgSeqs(self, value): <NEW_LINE> <INDENT> self._imgSeqs = value <NEW_LINE> self._imgStacks = {} <NEW_LINE> <DEDENT> def load(self): <NEW_LINE> <INDENT> objNames = self.lmi.getObjectNames() <NEW_LINE> imgSeqs = self.lmi.loadSequences(objNames) <NEW_LINE> raise NotImplementedError("Not implemented!") <NEW_LINE> <DEDENT> def imgStackDepthOnly(self, seqName, normZeroOne=False): <NEW_LINE> <INDENT> imgSeq = None <NEW_LINE> for seq in self._imgSeqs: <NEW_LINE> <INDENT> if seq.name == seqName: <NEW_LINE> <INDENT> imgSeq = seq <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if imgSeq is None: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> if seqName not in self._imgStacks: <NEW_LINE> <INDENT> numImgs = len(imgSeq.data) <NEW_LINE> data0 = numpy.asarray(imgSeq.data[0].dpt, 'float32') <NEW_LINE> label0 = numpy.asarray(imgSeq.data[0].gtorig, 'float32') <NEW_LINE> h, w = data0.shape <NEW_LINE> j, d = label0.shape <NEW_LINE> imgStack = numpy.zeros((numImgs, 1, h, w), dtype='float32') <NEW_LINE> labelStack = numpy.zeros((numImgs, j, d), dtype='float32') <NEW_LINE> for i in xrange(numImgs): <NEW_LINE> <INDENT> if normZeroOne: <NEW_LINE> <INDENT> imgD = numpy.asarray(imgSeq.data[i].dpt.copy(), 'float32') <NEW_LINE> imgD[imgD == 0] = imgSeq.data[i].com[2] + (imgSeq.config['cube'][2] / 2.) <NEW_LINE> imgD -= (imgSeq.data[i].com[2] - (imgSeq.config['cube'][2] / 2.)) <NEW_LINE> imgD /= imgSeq.config['cube'][2] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> imgD = numpy.asarray(imgSeq.data[i].dpt.copy(), 'float32') <NEW_LINE> imgD[imgD == 0] = imgSeq.data[i].com[2] + (imgSeq.config['cube'][2] / 2.) <NEW_LINE> imgD -= imgSeq.data[i].com[2] <NEW_LINE> imgD /= (imgSeq.config['cube'][2] / 2.) <NEW_LINE> <DEDENT> imgStack[i] = imgD <NEW_LINE> labelStack[i] = numpy.clip(numpy.asarray(imgSeq.data[i].gt3Dcrop, dtype='float32') / (imgSeq.config['cube'][2] / 2.), -1, 1) <NEW_LINE> <DEDENT> self._imgStacks[seqName] = imgStack <NEW_LINE> self._labelStacks[seqName] = labelStack <NEW_LINE> <DEDENT> return self._imgStacks[seqName], self._labelStacks[seqName] | Base class for managing data. Used to create training batches. | 62599074f9cc0f698b1c5f69 |
class PLNot(UnaryOperator[PLFormula], PLFormula): <NEW_LINE> <INDENT> @property <NEW_LINE> def operator_symbol(self) -> OpSymbol: <NEW_LINE> <INDENT> return Symbols.NOT.value <NEW_LINE> <DEDENT> def truth(self, i: PropositionalInterpretation): <NEW_LINE> <INDENT> return not self.f.truth(i) <NEW_LINE> <DEDENT> def to_nnf(self): <NEW_LINE> <INDENT> if not isinstance(self.f, AtomicFormula): <NEW_LINE> <INDENT> return self.f.negate().to_nnf() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> <DEDENT> def negate(self) -> PLFormula: <NEW_LINE> <INDENT> return self.f <NEW_LINE> <DEDENT> def _find_atomics(self) -> Set["PLAtomic"]: <NEW_LINE> <INDENT> return self.f.find_atomics() | Propositional Not. | 6259907432920d7e50bc7983 |
class UserView(CreateAPIView): <NEW_LINE> <INDENT> serializer_class = serializers.CreateUserSerializer | 用户注册:url(r"^users/$", views.UserView.as_view()) | 625990744e4d562566373d43 |
class OSUpdatesTestSummary(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'execution_status': {'key': 'executionStatus', 'type': 'str'}, 'test_status': {'key': 'testStatus', 'type': 'str'}, 'grade': {'key': 'grade', 'type': 'str'}, 'test_run_time': {'key': 'testRunTime', 'type': 'str'}, 'os_update_test_summaries': {'key': 'osUpdateTestSummaries', 'type': '[OSUpdateTestSummary]'}, } <NEW_LINE> def __init__( self, *, execution_status: Optional[Union[str, "ExecutionStatus"]] = None, test_status: Optional[Union[str, "TestStatus"]] = None, grade: Optional[Union[str, "Grade"]] = None, test_run_time: Optional[str] = None, os_update_test_summaries: Optional[List["OSUpdateTestSummary"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(OSUpdatesTestSummary, self).__init__(**kwargs) <NEW_LINE> self.execution_status = execution_status <NEW_LINE> self.test_status = test_status <NEW_LINE> self.grade = grade <NEW_LINE> self.test_run_time = test_run_time <NEW_LINE> self.os_update_test_summaries = os_update_test_summaries | The summary of some tests.
:param execution_status: The status of the last test. Possible values include: "None",
"InProgress", "Processing", "Completed", "NotExecuted", "Incomplete", "Failed", "Succeeded".
:type execution_status: str or ~test_base.models.ExecutionStatus
:param test_status: The status of last test. Possible values include: "None",
"TestExecutionInProgress", "DataProcessing", "TestFailure", "UpdateFailure",
"TestAndUpdateFailure", "InfrastructureFailure", "Completed".
:type test_status: str or ~test_base.models.TestStatus
:param grade: The grade of last test. Possible values include: "None", "NotAvailable", "Pass",
"Fail".
:type grade: str or ~test_base.models.Grade
:param test_run_time: The run time of the last test.
:type test_run_time: str
:param os_update_test_summaries: Detailed summary for each OS update.
:type os_update_test_summaries: list[~test_base.models.OSUpdateTestSummary] | 625990747b180e01f3e49d02 |
class IsotonicMethods(_AccessorMethods): <NEW_LINE> <INDENT> _module_name = 'sklearn.isotonic' <NEW_LINE> @property <NEW_LINE> def IsotonicRegression(self): <NEW_LINE> <INDENT> return self._module.IsotonicRegression <NEW_LINE> <DEDENT> def isotonic_regression(self, *args, **kwargs): <NEW_LINE> <INDENT> func = self._module.isotonic_regression <NEW_LINE> target = self._target <NEW_LINE> _y = func(target.values, *args, **kwargs) <NEW_LINE> _y = self._constructor_sliced(_y, index=target.index) <NEW_LINE> return _y <NEW_LINE> <DEDENT> def check_increasing(self, *args, **kwargs): <NEW_LINE> <INDENT> func = self._module.check_increasing <NEW_LINE> target = self._target <NEW_LINE> return func(target.index, target.values, *args, **kwargs) | Accessor to ``sklearn.isotonic``. | 6259907456b00c62f0fb420d |
class LearningAgent(Agent): <NEW_LINE> <INDENT> def __init__(self, env, learning=False, epsilon=1.0, alpha=0.5): <NEW_LINE> <INDENT> super(LearningAgent, self).__init__(env) <NEW_LINE> self.planner = RoutePlanner(self.env, self) <NEW_LINE> self.valid_actions = self.env.valid_actions <NEW_LINE> self.learning = learning <NEW_LINE> self.Q = dict() <NEW_LINE> self.epsilon = epsilon <NEW_LINE> self.alpha = alpha <NEW_LINE> self.trial = 0 <NEW_LINE> self.desired_training_trials = 300 <NEW_LINE> <DEDENT> def reset(self, destination=None, testing=False): <NEW_LINE> <INDENT> self.planner.route_to(destination) <NEW_LINE> if testing: <NEW_LINE> <INDENT> self.epsilon = self.alpha = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.epsilon = 1/(1+math.e**(-25*(-self.trial/float(self.desired_training_trials)+.5))) <NEW_LINE> self.trial += 1 <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def build_state(self): <NEW_LINE> <INDENT> waypoint = self.planner.next_waypoint() <NEW_LINE> inputs = self.env.sense(self) <NEW_LINE> deadline = self.env.get_deadline(self) <NEW_LINE> state = tuple([waypoint] + [inputs[x] for x in inputs]) <NEW_LINE> return state <NEW_LINE> <DEDENT> def get_maxQ_action(self, state): <NEW_LINE> <INDENT> maxQ = max(self.Q[state].values()) <NEW_LINE> tops = [action for action in self.Q[state] if self.Q[state][action] == maxQ] <NEW_LINE> return random.choice(tops) <NEW_LINE> <DEDENT> def createQ(self, state): <NEW_LINE> <INDENT> if self.learning and state not in self.Q: <NEW_LINE> <INDENT> self.Q[state] = {action: 0.0 for action in self.valid_actions} <NEW_LINE> <DEDENT> <DEDENT> def choose_action(self, state): <NEW_LINE> <INDENT> self.state = state <NEW_LINE> self.next_waypoint = self.planner.next_waypoint() <NEW_LINE> if not self.learning: <NEW_LINE> <INDENT> action = random.choice(self.valid_actions) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if random.random() < self.epsilon: <NEW_LINE> <INDENT> action = random.choice(self.valid_actions) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> action = self.get_maxQ_action(state) <NEW_LINE> <DEDENT> <DEDENT> return action <NEW_LINE> <DEDENT> def learn(self, state, action, reward): <NEW_LINE> <INDENT> if self.learning: <NEW_LINE> <INDENT> self.Q[state][action] = (1-self.alpha)*self.Q[state][action] + self.alpha*reward <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> state = self.build_state() <NEW_LINE> self.createQ(state) <NEW_LINE> action = self.choose_action(state) <NEW_LINE> reward = self.env.act(self, action) <NEW_LINE> self.learn(state, action, reward) <NEW_LINE> return | An agent that learns to drive in the Smartcab world.
This is the object you will be modifying. | 62599074a8370b77170f1d08 |
class CommandResolver(object): <NEW_LINE> <INDENT> def resolve( self, args, application ): <NEW_LINE> <INDENT> raise NotImplementedError() | Returns the command to execute for the given console arguments. | 62599074e1aae11d1e7cf4ac |
class SdkCommandMock(SdkCommand): <NEW_LINE> <INDENT> @property <NEW_LINE> def cmd_factory(self): <NEW_LINE> <INDENT> return self._cmd_factory <NEW_LINE> <DEDENT> def get_name(self): <NEW_LINE> <INDENT> return "test_cmd" <NEW_LINE> <DEDENT> def get_arguments(self): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> def get_help(self): <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> def exec(self): <NEW_LINE> <INDENT> pass | Very simple sdk mock command. | 625990744527f215b58eb63e |
class ComparisonTestFramework(BitcoinTestFramework): <NEW_LINE> <INDENT> def set_test_params(self): <NEW_LINE> <INDENT> self.num_nodes = 2 <NEW_LINE> self.setup_clean_chain = True <NEW_LINE> <DEDENT> def add_options(self, parser): <NEW_LINE> <INDENT> parser.add_option("--testbinary", dest="testbinary", default=os.getenv("BITCOIND", "bitcoind"), help="bitcoind binary to test") <NEW_LINE> parser.add_option("--refbinary", dest="refbinary", default=os.getenv("BITCOIND", "bitcoind"), help="bitcoind binary to use for reference nodes (if any)") <NEW_LINE> <DEDENT> def setup_network(self): <NEW_LINE> <INDENT> extra_args = [['-whitelist=127.0.0.1']] * self.num_nodes <NEW_LINE> if hasattr(self, "extra_args"): <NEW_LINE> <INDENT> extra_args = self.extra_args <NEW_LINE> <DEDENT> self.add_nodes(self.num_nodes, extra_args, binary=[self.options.testbinary] + [self.options.refbinary] * (self.num_nodes - 1)) <NEW_LINE> self.start_nodes() | Test framework for doing p2p comparison testing
Sets up some bitcoind binaries:
- 1 binary: test binary
- 2 binaries: 1 test binary, 1 ref binary
- n>2 binaries: 1 test binary, n-1 ref binaries | 625990747047854f46340cf5 |
class InternalDataError(errors.Error): <NEW_LINE> <INDENT> pass | Problem with internal checkpkg data structures. | 6259907492d797404e3897f9 |
class env_Original(Environment): <NEW_LINE> <INDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> special = self._special_set.get(key) <NEW_LINE> if special: <NEW_LINE> <INDENT> special(self, key, value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not SCons.Environment.is_valid_construction_var(key): <NEW_LINE> <INDENT> raise SCons.Errors.UserError("Illegal construction variable `%s'" % key) <NEW_LINE> <DEDENT> self._dict[key] = value | Original __setitem__() | 62599074dd821e528d6da620 |
class SelectorDIC(ModelSelector): <NEW_LINE> <INDENT> def select(self): <NEW_LINE> <INDENT> warnings.filterwarnings("ignore", category=DeprecationWarning) <NEW_LINE> n_components_range = range(self.min_n_components, self.max_n_components + 1) <NEW_LINE> highest_DIC = float('-inf') <NEW_LINE> best_model = self.base_model(self.min_n_components) <NEW_LINE> for num_compoments in n_components_range: <NEW_LINE> <INDENT> model = self.base_model(num_compoments) <NEW_LINE> try: <NEW_LINE> <INDENT> logL = model.score(self.X, self.lengths) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> DIC = logL - statistics.mean([model.score(self.hwords[word][0],self.hwords[word][1]) for word in list(self.hwords.keys()) if word != self.this_word]) <NEW_LINE> if DIC > highest_DIC: <NEW_LINE> <INDENT> highest_DIC = DIC <NEW_LINE> best_model = model <NEW_LINE> <DEDENT> <DEDENT> return best_model | select best model based on Discriminative Information Criterion
Biem, Alain. "A model selection criterion for classification: Application to hmm topology optimization."
Document Analysis and Recognition, 2003. Proceedings. Seventh International Conference on. IEEE, 2003.
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.58.6208&rep=rep1&type=pdf
DIC = log(P(X(i)) - 1/(M-1)SUM(log(P(X(all but i)) | 625990747c178a314d78e889 |
class WeeklyReportBruteAttack(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.MachineIp = None <NEW_LINE> self.Username = None <NEW_LINE> self.SrcIp = None <NEW_LINE> self.Count = None <NEW_LINE> self.AttackTime = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.MachineIp = params.get("MachineIp") <NEW_LINE> self.Username = params.get("Username") <NEW_LINE> self.SrcIp = params.get("SrcIp") <NEW_LINE> self.Count = params.get("Count") <NEW_LINE> self.AttackTime = params.get("AttackTime") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set)) | 专业周报密码破解数据。
| 625990744428ac0f6e659e6b |
class UsageError(CommandantError): <NEW_LINE> <INDENT> pass | Raised when too few command-line arguments are provided. | 6259907444b2445a339b75fc |
class Trigger_Monitor(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.pins = ['GP16', 'GP13'] <NEW_LINE> self.outputPin = Pin(self.pins[0], mode=Pin.OUT, value=1) <NEW_LINE> self.inputPin = Pin(self.pins[1], mode=Pin.IN, pull=Pin.PULL_UP) <NEW_LINE> self.triggerCount = 0 <NEW_LINE> self._triggerType_ = Pin.IRQ_RISING <NEW_LINE> self.inputIRQ = self.inputPin.irq(trigger=self._triggerType_, handler=self.pinHandler) <NEW_LINE> self.irqState = True <NEW_LINE> <DEDENT> def toggleInput(self, time_ms = 5): <NEW_LINE> <INDENT> self.outputPin.toggle() <NEW_LINE> time.sleep_ms(time_ms) <NEW_LINE> <DEDENT> def pinHandler(self, pin_o): <NEW_LINE> <INDENT> self.triggerCount += 1 <NEW_LINE> <DEDENT> def getTriggerCount(self): <NEW_LINE> <INDENT> print("Trigger Count: ", self.triggerCount) <NEW_LINE> <DEDENT> def resetTriggerCount(self): <NEW_LINE> <INDENT> self.triggerCount = 0 <NEW_LINE> <DEDENT> def disableIRQ(self): <NEW_LINE> <INDENT> self.irqState = machine.disable_irq() <NEW_LINE> <DEDENT> def reEnableIRQ(self): <NEW_LINE> <INDENT> machine.enable_irq(True) <NEW_LINE> self.irqState=True | Is there a way to change the callback? | 6259907476e4537e8c3f0ebc |
class ListSelect(SlaveView): <NEW_LINE> <INDENT> builder_file = 'list_select.glade' <NEW_LINE> def __init__(self, df_data=None): <NEW_LINE> <INDENT> self.df_data = df_data <NEW_LINE> super(ListSelect, self).__init__() <NEW_LINE> <DEDENT> def create_ui(self): <NEW_LINE> <INDENT> super(ListSelect, self).create_ui() <NEW_LINE> self.button_select_none.connect('clicked', lambda *args: self.select_none()) <NEW_LINE> self.button_select_all.connect('clicked', lambda *args: self.select_all()) <NEW_LINE> if self.df_data is not None: <NEW_LINE> <INDENT> self.set_data(self.df_data) <NEW_LINE> <DEDENT> <DEDENT> def set_data(self, df_data, select_column='select'): <NEW_LINE> <INDENT> self.select_column = select_column <NEW_LINE> self.df_data = df_data <NEW_LINE> for column in self.treeview_select.get_columns(): <NEW_LINE> <INDENT> self.treeview_select.remove_column(column) <NEW_LINE> <DEDENT> self.df_py_dtypes, self.list_store = get_list_store(df_data) <NEW_LINE> add_columns(self.treeview_select, self.df_py_dtypes, self.list_store) <NEW_LINE> select_column = self.treeview_select.get_column(self.df_py_dtypes .ix[select_column].i) <NEW_LINE> cell = select_column.get_cell_renderers()[0] <NEW_LINE> cell.connect('toggled', on_edited_dataframe_sync, None, select_column, self.df_py_dtypes, self.list_store, self.df_data) <NEW_LINE> <DEDENT> def set_all(self, value): <NEW_LINE> <INDENT> column_i = self.df_py_dtypes.ix[self.select_column].i <NEW_LINE> select_column = self.treeview_select.get_column(column_i).get_name() <NEW_LINE> self.df_data.loc[:, select_column] = value <NEW_LINE> for i in xrange(len(self.list_store)): <NEW_LINE> <INDENT> self.list_store[i][column_i] = value <NEW_LINE> <DEDENT> <DEDENT> def select_none(self): <NEW_LINE> <INDENT> self.set_all(False) <NEW_LINE> <DEDENT> def select_all(self): <NEW_LINE> <INDENT> self.set_all(True) | .. versionchanged:: 0.21
Specify :attr:`builder_file` instead of :attr:`builder_path` to support
loading ``.glade`` file from ``.zip`` files (e.g., in app packaged with
Py2Exe). | 62599074796e427e538500b6 |
class LOEA16_6: <NEW_LINE> <INDENT> play = Hit(ALL_CHARACTERS, 5) | Shard of Sulfuras | 625990742c8b7c6e89bd5125 |
class ConcatTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> call('echo \'File1\' > file1', shell=True) <NEW_LINE> call('echo \'File2\' > file2', shell=True) <NEW_LINE> <DEDENT> def test_concat(self): <NEW_LINE> <INDENT> expected_output = 'File1\n\nFile2\n\n' <NEW_LINE> call('py solution.py file1 file2', shell=True) <NEW_LINE> target_file = open('MEGATRON', 'r') <NEW_LINE> output = target_file.read() <NEW_LINE> target_file.close() <NEW_LINE> self.assertEqual(expected_output, output) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> call('rm file1 file2 MEGATRON', shell=True) | docstring for ConcatTest | 6259907597e22403b383c83f |
class PrintHandler(Handler): <NEW_LINE> <INDENT> def handle(self, data): <NEW_LINE> <INDENT> pprint.pprint(data) | Simple handler that only prints data. | 62599075627d3e7fe0e087c5 |
class AxesWidget(Widget): <NEW_LINE> <INDENT> def __init__(self, ax): <NEW_LINE> <INDENT> self.ax = ax <NEW_LINE> self.canvas = ax.figure.canvas <NEW_LINE> self.cids = [] <NEW_LINE> <DEDENT> def connect_event(self, event, callback): <NEW_LINE> <INDENT> cid = self.canvas.mpl_connect(event, callback) <NEW_LINE> self.cids.append(cid) <NEW_LINE> <DEDENT> def disconnect_events(self): <NEW_LINE> <INDENT> for c in self.cids: <NEW_LINE> <INDENT> self.canvas.mpl_disconnect(c) | Widget that is connected to a single
:class:`~matplotlib.axes.Axes`.
To guarantee that the widget remains responsive and not garbage-collected,
a reference to the object should be maintained by the user.
This is necessary because the callback registry
maintains only weak-refs to the functions, which are member
functions of the widget. If there are no references to the widget
object it may be garbage collected which will disconnect the
callbacks.
Attributes:
*ax* : :class:`~matplotlib.axes.Axes`
The parent axes for the widget
*canvas* : :class:`~matplotlib.backend_bases.FigureCanvasBase` subclass
The parent figure canvas for the widget.
*active* : bool
If False, the widget does not respond to events. | 62599075009cb60464d02e78 |
class FCB(ControlBlock): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> ControlBlock.__init__(self) <NEW_LINE> self.index = [ ] <NEW_LINE> self.linkCount = 0 <NEW_LINE> self.openCount = 0 <NEW_LINE> <DEDENT> def nBlocks(self): <NEW_LINE> <INDENT> return len(self.index) <NEW_LINE> <DEDENT> def incrOpenCount(self): <NEW_LINE> <INDENT> self.openCount += 1 <NEW_LINE> <DEDENT> def decrOpenCount(self): <NEW_LINE> <INDENT> self.openCount -= 1 <NEW_LINE> <DEDENT> def incrLinkCount(self): <NEW_LINE> <INDENT> self.linkCount += 1 <NEW_LINE> <DEDENT> def decrLinkCount(self): <NEW_LINE> <INDENT> self.linkCount -= 1 <NEW_LINE> <DEDENT> def nameInDir(self, d): <NEW_LINE> <INDENT> if self in d.content: <NEW_LINE> <INDENT> return d.names[d.content.index(self)] <NEW_LINE> <DEDENT> return None | FCB is the file control block.
Note that there is the FCB on disk and in-memory FCB.
The difference is in-memory one would have a count, but not on-disk.
The name technically is not part of the FCB but kept by directory.
it also does not know which directory it belongs to.
The constructor should be called only by the file system,
but not separately. We add extra fields to simplify programming
and tracing, but they are actually not part of actual FCBs. | 625990754c3428357761bbf3 |
class GiscedataPolissaTarifaPeriodes(osv.osv): <NEW_LINE> <INDENT> _name = 'giscedata.polissa.tarifa.periodes' <NEW_LINE> _inherit = 'giscedata.polissa.tarifa.periodes' <NEW_LINE> _columns = { 'product_gkwh_id': fields.many2one( 'product.product', 'Generation kWh', ondelete='restrict' ), } | Periodes de les Tarifes. | 62599075f9cc0f698b1c5f6a |
class _OptimizeHyperparametersEval(object): <NEW_LINE> <INDENT> def __init__(self, gp, opt_kwargs): <NEW_LINE> <INDENT> self.gp = gp <NEW_LINE> self.opt_kwargs = opt_kwargs <NEW_LINE> <DEDENT> def __call__(self, samp): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return scipy.optimize.minimize(self.gp.update_hyperparameters, samp, **self.opt_kwargs) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> warnings.warn("scipy.optimize.minimize not available, defaulting " "to fmin_slsqp.", RuntimeWarning) <NEW_LINE> return wrap_fmin_slsqp(self.gp.update_hyperparameters, samp, opt_kwargs=self.opt_kwargs) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> warnings.warn("Minimizer failed, skipping sample. Error " "is: %s: %s. State of params is: %s %s" % (sys.exc_info()[0], sys.exc_info()[1], str(self.gp.k.free_params), str(self.gp.noise_k.free_params)), RuntimeWarning) <NEW_LINE> return None | Helper class to support parallel random starts of MAP estimation of hyperparameters.
Parameters
----------
gp : :py:class:`GaussianProcess` instance
Instance to wrap to allow parallel optimization of.
opt_kwargs : dict
Dictionary of keyword arguments to be passed to
:py:func:`scipy.optimize.minimize`. | 625990758a349b6b43687b96 |
class Until(TemporalOp): <NEW_LINE> <INDENT> nargs = 2 <NEW_LINE> def tex_print(self): <NEW_LINE> <INDENT> args_tex = tuple(arg.tex_print for arg in self.args) <NEW_LINE> a, b = self.interval <NEW_LINE> if math.isinf(b): <NEW_LINE> <INDENT> return r" U ".join(args_tex) | The Until operator | 625990757b180e01f3e49d03 |
class Bound: <NEW_LINE> <INDENT> def __init__(self, pointList: [Point]): <NEW_LINE> <INDENT> self.southWest = pointList[0].copy() <NEW_LINE> self.northEast = pointList[0].copy() <NEW_LINE> for point in pointList: <NEW_LINE> <INDENT> self.southWest.x = point.x if point.x < self.southWest.x else self.southWest.x <NEW_LINE> self.southWest.y = point.y if point.y < self.southWest.y else self.southWest.y <NEW_LINE> self.northEast.x = point.x if point.x > self.northEast.x else self.northEast.x <NEW_LINE> self.northEast.y = point.y if point.y > self.northEast.y else self.northEast.y <NEW_LINE> <DEDENT> <DEDENT> def width(self) -> float: <NEW_LINE> <INDENT> return self.northEast.x - self.southWest.x <NEW_LINE> <DEDENT> def height(self) -> float: <NEW_LINE> <INDENT> return self.northEast.y - self.southWest.y <NEW_LINE> <DEDENT> def area(self) -> float: <NEW_LINE> <INDENT> return self.width() * self.height() | class Bound
Bound of points | 62599075a8370b77170f1d09 |
class TableXmlDumpPageGenerator: <NEW_LINE> <INDENT> def __init__(self, xmlfilename): <NEW_LINE> <INDENT> self.xmldump = xmlreader.XmlDump(xmlfilename) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for entry in self.xmldump.parse(): <NEW_LINE> <INDENT> if _table_start_regex.search(entry.text): <NEW_LINE> <INDENT> yield pywikibot.Page(pywikibot.Site(), entry.title) | Generator to yield all pages that seem to contain an HTML table. | 62599075a8370b77170f1d0a |
class TestLangQuirks(TestLang): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.purge() <NEW_LINE> self.quirks = True | Test language selectors with quirks. | 6259907556b00c62f0fb420f |
class InferenceEngine(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.knowledge_base = list() <NEW_LINE> self.inference_scratch_pad = list() <NEW_LINE> <DEDENT> def tell(self, cnf_sentence): <NEW_LINE> <INDENT> for item in self.knowledge_base: <NEW_LINE> <INDENT> if cmp(cnf_sentence, item) == 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if not __is_cnf__(cnf_sentence): <NEW_LINE> <INDENT> self.knowledge_base.append(conversion.__to_cnf__(cnf_sentence)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.knowledge_base.append(cnf_sentence) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def ask(self, cnf_query): <NEW_LINE> <INDENT> if __is_cnf__(s=cnf_query) is False: <NEW_LINE> <INDENT> convert = conversion.__to_cnf__(cnf_query) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> convert = cnf_query <NEW_LINE> <DEDENT> query = convert if type(convert) is list else list(convert) <NEW_LINE> negation = __not__(query) <NEW_LINE> if negation[0] == 'and': <NEW_LINE> <INDENT> for item in negation[1:]: <NEW_LINE> <INDENT> self.append_to_scratch(item) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.append_to_scratch(negation) <NEW_LINE> <DEDENT> for info in self.knowledge_base: <NEW_LINE> <INDENT> self.append_to_scratch(info) <NEW_LINE> <DEDENT> last_proposition_count = 0 <NEW_LINE> current_proposition_count = len(self.inference_scratch_pad) <NEW_LINE> conclusions = list() <NEW_LINE> while last_proposition_count != current_proposition_count: <NEW_LINE> <INDENT> last_proposition_count = current_proposition_count <NEW_LINE> for select in self.inference_scratch_pad: <NEW_LINE> <INDENT> for resolvee in self.inference_scratch_pad: <NEW_LINE> <INDENT> result = resolver.resolve(select, resolvee) <NEW_LINE> if result is False: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> elif len(result) == 0: <NEW_LINE> <INDENT> del self.inference_scratch_pad[:] <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> conclusions.append(result) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for item in conclusions: <NEW_LINE> <INDENT> self.append_to_scratch(item) <NEW_LINE> <DEDENT> del conclusions[:] <NEW_LINE> current_proposition_count = len(self.inference_scratch_pad) <NEW_LINE> <DEDENT> del self.inference_scratch_pad[:] <NEW_LINE> return False <NEW_LINE> <DEDENT> def clear(self): <NEW_LINE> <INDENT> del self.knowledge_base[:] <NEW_LINE> <DEDENT> def append_to_scratch(self, sentence): <NEW_LINE> <INDENT> for item in self.inference_scratch_pad: <NEW_LINE> <INDENT> if cmp(sentence, item) == 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.inference_scratch_pad.append(sentence) | Description of the resolution inference engine | 625990757047854f46340cf7 |
class Task(models.Model): <NEW_LINE> <INDENT> id = models.AutoField(primary_key=True) <NEW_LINE> TaskID = models.CharField(max_length=125,verbose_name='任务ID') <NEW_LINE> Taskname = models.CharField(max_length=125, verbose_name='任务名称') <NEW_LINE> Starttime = models.DateTimeField(default=timezone.now, verbose_name='开始时间') <NEW_LINE> Taksstatus = models.CharField(max_length=125, verbose_name='任务状态') <NEW_LINE> Completiontime = models.CharField(max_length=125,blank=True,null=True, verbose_name='结束时间') <NEW_LINE> Cmdb = models.ForeignKey('Cmdb', on_delete=models.CASCADE) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = 'Task' <NEW_LINE> verbose_name_plural = verbose_name <NEW_LINE> ordering = ['Starttime'] <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.Taskname | 任务信息 | 625990759c8ee82313040e26 |
class Chain(object): <NEW_LINE> <INDENT> def __init__(self, *elements, **kwargs): <NEW_LINE> <INDENT> self.source, *self.codecs, self.channel = self.elements = elements <NEW_LINE> self.levels = len(self.codecs) + 1 <NEW_LINE> self.verbosity = kwargs.pop("verbosity", 0) <NEW_LINE> self.broken_string = colortools.colored("broken", "red") <NEW_LINE> self.elementcolor = kwargs.pop("elementcolor", "blue") <NEW_LINE> self.runs = [] <NEW_LINE> if kwargs: <NEW_LINE> <INDENT> for key in kwargs: <NEW_LINE> <INDENT> print("There is no argument called '{0}'".format(key)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ",\n ".join(repr(elem) for elem in self.elements) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Channel({0},\n verbosity={1})".format(self, self.verbosity) <NEW_LINE> <DEDENT> def iter_elements(self): <NEW_LINE> <INDENT> for elem in self.elements: <NEW_LINE> <INDENT> yield colortools.colored(repr(elem), self.elementcolor) <NEW_LINE> <DEDENT> <DEDENT> def run(self): <NEW_LINE> <INDENT> outputs = [[0, 0] for i in range(self.levels)] <NEW_LINE> direction = 0 <NEW_LINE> level = 0 <NEW_LINE> output = self.source.message() <NEW_LINE> outputs[level][direction] = output <NEW_LINE> for codec in self.codecs: <NEW_LINE> <INDENT> level += 1 <NEW_LINE> output = codec.coder(output) <NEW_LINE> outputs[level][direction] = output <NEW_LINE> <DEDENT> direction = 1 <NEW_LINE> output = self.channel.run(output) <NEW_LINE> outputs[level][direction] = output <NEW_LINE> for codec in reversed(self.codecs): <NEW_LINE> <INDENT> level -= 1 <NEW_LINE> output = codec.decoder(output) <NEW_LINE> outputs[level][direction] = output <NEW_LINE> <DEDENT> self.runs.append(Run(outputs, self)) <NEW_LINE> <DEDENT> def print_run(self, n=-1, **kwargs): <NEW_LINE> <INDENT> if not self.runs: <NEW_LINE> <INDENT> self.run() <NEW_LINE> <DEDENT> run = self.runs[n] <NEW_LINE> run.print(**kwargs) | It simulates an information transmitting chain.
| 6259907599cbb53fe6832829 |
class preprocessing_interface(ABC): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def tokenization(self, parameter_dictionary): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def stemming(self, parameter_dictionary): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def lemmatization(self, parameter_dictionary): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def NER(self, parameter_dictionary): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def POS(self, parameter_dictionary): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def remove_stopwords(self, parameter_dictionary): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def remove_emails(self, parameter_dictionary): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def remove_html_tags(self, parameter_dictionary): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def remove_numbers(self, parameter_dictionary): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def remove_punctuations(self, parameter_dictionary): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def remove_unicode(self, parameter_dictionary): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def remove_hash_tags(self, parameter_dictionary): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def remove_specialcharacters(self, parameter_dictionary): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def expand_contractions(self, parameter_dictionary): <NEW_LINE> <INDENT> pass | this class is an interface for processing libraries | 6259907544b2445a339b75fd |
class Kutta4(odespy.Solver): <NEW_LINE> <INDENT> quick_description = "Explicit 4th-order Kutta method. LR Hellevik implementation" <NEW_LINE> def advance(self): <NEW_LINE> <INDENT> u, f, n, t = self.u, self.f, self.n, self.t <NEW_LINE> dt = t[n+1] - t[n] <NEW_LINE> dt3 = dt/3.0 <NEW_LINE> K1 = dt*f(u[n], t[n]) <NEW_LINE> K2 = dt*f(u[n] + K1/3.0, t[n] + dt3) <NEW_LINE> K3 = dt*f(u[n] - K1/3 + K2, t[n] + 2*dt3) <NEW_LINE> K4 = dt*f(u[n] + K1 - K2 + K3, t[n] + dt) <NEW_LINE> u_new = u[n] + (K1 + 3*K2 + 3*K3 + K4)/8.0 <NEW_LINE> return u_new | Kutta 4 method by LR Hellevik::
u[n+1] = u[n] + (K1 + 3*K2 + 3*K3 + K4)/8.0
where::
dt3 = dt/3.0
K1 = dt*f(u[n], t[n])
K2 = dt*f(u[n] + K1/3.0, t[n] + dt3)
K3 = dt*f(u[n] - K1/3 + K2, t[n] + 2*dt3)
K4 = dt*f(u[n] + K1 - K2 + K3, t[n] + dt)
| 625990758e7ae83300eea9d0 |
class JustScale(): <NEW_LINE> <INDENT> def __init__(self, tones=None): <NEW_LINE> <INDENT> self._tones = None <NEW_LINE> self._pitch_mapping = None <NEW_LINE> try: <NEW_LINE> <INDENT> self.tones = tones.intervals <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> self.tones = tones <NEW_LINE> <DEDENT> <DEDENT> def append(self, other): <NEW_LINE> <INDENT> if not isinstance(other, JustInterval): <NEW_LINE> <INDENT> msg = 'cannot append type {}. '.format(type(other)) <NEW_LINE> msg += 'Expecting type "JustInterval"' <NEW_LINE> raise ValueError(msg) <NEW_LINE> <DEDENT> self._tones.append(other) <NEW_LINE> <DEDENT> def hertz(self, fundamental): <NEW_LINE> <INDENT> return [fundamental * tone for tone in self.tones] <NEW_LINE> <DEDENT> @property <NEW_LINE> def tones(self): <NEW_LINE> <INDENT> return sorted(self._tones) <NEW_LINE> <DEDENT> @tones.setter <NEW_LINE> def tones(self, values): <NEW_LINE> <INDENT> for tone in values: <NEW_LINE> <INDENT> if not isinstance(tone, JustInterval): <NEW_LINE> <INDENT> msg = 'tones must be a list of JustIntervals. ' <NEW_LINE> msg += "Got '{}'".format(values) <NEW_LINE> raise ValueError(msg) <NEW_LINE> <DEDENT> <DEDENT> self._tones = values <NEW_LINE> <DEDENT> @property <NEW_LINE> def intervals(self): <NEW_LINE> <INDENT> return [ tone - self.tones[i-1] for i, tone in enumerate(self.tones) ][1:] <NEW_LINE> <DEDENT> @property <NEW_LINE> def complement(self): <NEW_LINE> <INDENT> tones = [tone.complement for tone in self.tones] <NEW_LINE> return JustScale(tones) <NEW_LINE> <DEDENT> @property <NEW_LINE> def prime_limit(self): <NEW_LINE> <INDENT> return max([tone.prime_limit for tone in self.tones]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def pitch_mapping(self): <NEW_LINE> <INDENT> return self.pitch_mapping <NEW_LINE> <DEDENT> @pitch_mapping.setter <NEW_LINE> def pitch_mapping(self, values): <NEW_LINE> <INDENT> if len(values) != self.tones: <NEW_LINE> <INDENT> msg = 'length mismatch. Must map one to one with intervals.' <NEW_LINE> raise ValueError(msg) <NEW_LINE> <DEDENT> for value in values: <NEW_LINE> <INDENT> if not isinstance(value, str): <NEW_LINE> <INDENT> raise ValueError('invalid mapping.') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> pitches = ', '.join([ '/'.join([str(tone.numerator), str(tone.denominator)]) for tone in self.tones ]) <NEW_LINE> return "{}([{}])".format(self.__class__.__name__, pitches) | This class implements arbitrary just intonation scales. | 62599075091ae35668706577 |
class MLChainGroup(AppGroup): <NEW_LINE> <INDENT> def __init__( self, add_default_commands=True, create_app=None, add_version_option=True, load_dotenv=True, set_debug_flag=True, **extra ): <NEW_LINE> <INDENT> params = list(extra.pop("params", None) or ()) <NEW_LINE> if add_version_option: <NEW_LINE> <INDENT> params.append(version_option) <NEW_LINE> <DEDENT> AppGroup.__init__(self, params=params, **extra) <NEW_LINE> self.create_app = create_app <NEW_LINE> self.load_dotenv = load_dotenv <NEW_LINE> self.set_debug_flag = set_debug_flag <NEW_LINE> if add_default_commands: <NEW_LINE> <INDENT> self.add_command(run_command) <NEW_LINE> self.add_command(init_command) <NEW_LINE> self.add_command(prepare_command) <NEW_LINE> <DEDENT> self._loaded_plugin_commands = False <NEW_LINE> <DEDENT> def _load_plugin_commands(self): <NEW_LINE> <INDENT> if self._loaded_plugin_commands: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> import pkg_resources <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> self._loaded_plugin_commands = True <NEW_LINE> return <NEW_LINE> <DEDENT> for ep in pkg_resources.iter_entry_points("flask.commands"): <NEW_LINE> <INDENT> self.add_command(ep.load(), ep.name) <NEW_LINE> <DEDENT> self._loaded_plugin_commands = True <NEW_LINE> <DEDENT> def get_command(self, ctx, name): <NEW_LINE> <INDENT> self._load_plugin_commands() <NEW_LINE> rv = AppGroup.get_command(self, ctx, name) <NEW_LINE> if rv is not None: <NEW_LINE> <INDENT> return rv <NEW_LINE> <DEDENT> <DEDENT> def list_commands(self, ctx): <NEW_LINE> <INDENT> self._load_plugin_commands() <NEW_LINE> rv = set(click.Group.list_commands(self, ctx)) <NEW_LINE> return sorted(rv) <NEW_LINE> <DEDENT> def main(self, *args, **kwargs): <NEW_LINE> <INDENT> return super(MLChainGroup, self).main(*args, **kwargs) | Special subclass of the :class:`AppGroup` group that supports
loading more commands from the configured Flask app. Normally a
developer does not have to interface with this class but there are
some very advanced use cases for which it makes sense to create an
instance of this.
For information as of why this is useful see :ref:`custom-scripts`.
:param add_default_commands: if this is True then the default run and
shell commands will be added.
:param add_version_option: adds the ``--version`` option.
:param create_app: an optional callback that is passed the script info and
returns the loaded app.
:param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`
files to set environment variables. Will also change the working
directory to the directory containing the first file found.
:param set_debug_flag: Set the app's debug flag based on the active
environment
.. versionchanged:: 1.0
If installed, python-dotenv will be used to load environment variables
from :file:`.env` and :file:`.flaskenv` files. | 62599075aad79263cf4300f6 |
class ProjectConfigDownload(ProjectMixIn, base.BaseDownloadCommand): <NEW_LINE> <INDENT> def get_parser(self, prog_name): <NEW_LINE> <INDENT> parser = super(ProjectConfigDownload, self).get_parser(prog_name) <NEW_LINE> parser.add_argument( 'name', help='Name of the project.' ) <NEW_LINE> return parser <NEW_LINE> <DEDENT> def take_action(self, parsed_args): <NEW_LINE> <INDENT> file_name = '{}.{}'.format(utils.normalize(parsed_args.name), parsed_args.format) <NEW_LINE> file_path = os.path.join(os.path.abspath(parsed_args.directory), file_name) <NEW_LINE> response_data = self.client.get_config(parsed_args.name) <NEW_LINE> try: <NEW_LINE> <INDENT> if not os.path.exists(parsed_args.directory): <NEW_LINE> <INDENT> os.makedirs(parsed_args.directory) <NEW_LINE> <DEDENT> with open(file_path, 'w') as stream: <NEW_LINE> <INDENT> utils.safe_dump(parsed_args.format, stream, response_data) <NEW_LINE> <DEDENT> <DEDENT> except (OSError, IOError) as e: <NEW_LINE> <INDENT> msg = ("Could not store {0} data at {1}. " "{2}".format(self.entity_name, file_path, e)) <NEW_LINE> raise error.InvalidFileException(msg) <NEW_LINE> <DEDENT> msg = "Information about the {} was stored in '{}' file.\n".format( self.entity_name, file_path) <NEW_LINE> self.app.stdout.write(msg) | Gets some configuration information about a project.
Note that this config info is not simply the contents of project.config;
it generally contains fields that may have been inherited from parent
projects. | 6259907532920d7e50bc7986 |
class ExpoPSPol2D_pdf(PDF2) : <NEW_LINE> <INDENT> def __init__ ( self , name , x , y , psy = None , nx = 2 , ny = 2 , tau = None ) : <NEW_LINE> <INDENT> PDF2.__init__ ( self , name , x , y ) <NEW_LINE> taumax = 100 <NEW_LINE> mn,mx = x.minmax() <NEW_LINE> mc = 0.5 * ( mn + mx ) <NEW_LINE> if not iszero ( mn ) : taumax = 100.0 / abs ( mn ) <NEW_LINE> if not iszero ( mc ) : taumax = min ( taumax , 100.0 / abs ( mc ) ) <NEW_LINE> if not iszero ( mx ) : taumax = min ( taumax , 100.0 / abs ( mx ) ) <NEW_LINE> self.tau = makeVar ( tau , "tau_%s" % name , "tau(%s)" % name , tau , 0 , -taumax , taumax ) <NEW_LINE> self.psy = psy <NEW_LINE> num = ( nx + 1 ) * ( ny + 1 ) - 1 <NEW_LINE> self.makePhis ( num ) <NEW_LINE> self.pdf = Ostap.Models.ExpoPS2DPol ( 'ps2D_%s' % name , 'PS2DPol(%s)' % name , self.x , self.y , self.tau , self.psy , nx , ny , self.phi_list ) | Product of exponential and phase space factor,
modulated by the positive polynom in 2D
f(x,y) = exp(tau*x) * PS(y) * Pnk(x,y)
where
- PS (y) is a phase space function for y-axis (Ostap::Math::PhaseSpaceNL)
- Pnk(x,y) is positive non-factorizable polynom
Pnk(x,y) = sum^{i=n}_{i=0}sum{j=k}_{j=0} a^2_{ij} B^n_i(x) B^k_j(y)
where:
- B^n_i - are Bernstein polynomials
Note:
- f(x,y)>=0 for whole 2D-range | 625990755fcc89381b266df8 |
class UnsupportedEvent(Exception): <NEW_LINE> <INDENT> pass | Unsupported CoT Event. | 625990755166f23b2e244d14 |
class EchoComponent(ComponentXMPP): <NEW_LINE> <INDENT> def __init__(self, jid, secret, server, port): <NEW_LINE> <INDENT> ComponentXMPP.__init__(self, jid, secret, server, port) <NEW_LINE> self.add_event_handler("message", self.message) <NEW_LINE> <DEDENT> def message(self, msg): <NEW_LINE> <INDENT> msg.reply("Thanks for sending\n%(body)s" % msg).send() | A simple SleekXMPP component that echoes messages. | 62599075bf627c535bcb2e0b |
class ValidationError(BoobyError): <NEW_LINE> <INDENT> pass | This exception should be raised when a `value` doesn't validate.
See :mod:`validators`. | 6259907591f36d47f2231b2e |
class TestEncodingCluster(object): <NEW_LINE> <INDENT> @pytest.fixture() <NEW_LINE> def r(self, request): <NEW_LINE> <INDENT> return _get_client(RedisCluster, request=request, decode_responses=True) <NEW_LINE> <DEDENT> @pytest.fixture() <NEW_LINE> def r_no_decode(self, request): <NEW_LINE> <INDENT> return _get_client( RedisCluster, request=request, decode_responses=False, ) <NEW_LINE> <DEDENT> def test_simple_encoding(self, r_no_decode): <NEW_LINE> <INDENT> unicode_string = unichr(3456) + 'abcd' + unichr(3421) <NEW_LINE> r_no_decode['unicode-string'] = unicode_string.encode('utf-8') <NEW_LINE> cached_val = r_no_decode['unicode-string'] <NEW_LINE> assert isinstance(cached_val, bytes) <NEW_LINE> assert unicode_string == cached_val.decode('utf-8') <NEW_LINE> <DEDENT> def test_simple_encoding_and_decoding(self, r): <NEW_LINE> <INDENT> unicode_string = unichr(3456) + 'abcd' + unichr(3421) <NEW_LINE> r['unicode-string'] = unicode_string <NEW_LINE> cached_val = r['unicode-string'] <NEW_LINE> assert isinstance(cached_val, unicode) <NEW_LINE> assert unicode_string == cached_val <NEW_LINE> <DEDENT> def test_memoryview_encoding(self, r_no_decode): <NEW_LINE> <INDENT> unicode_string = unichr(3456) + 'abcd' + unichr(3421) <NEW_LINE> unicode_string_view = memoryview(unicode_string.encode('utf-8')) <NEW_LINE> r_no_decode['unicode-string-memoryview'] = unicode_string_view <NEW_LINE> cached_val = r_no_decode['unicode-string-memoryview'] <NEW_LINE> assert isinstance(cached_val, bytes) <NEW_LINE> assert unicode_string == cached_val.decode('utf-8') <NEW_LINE> <DEDENT> def test_memoryview_encoding_and_decoding(self, r): <NEW_LINE> <INDENT> unicode_string = unichr(3456) + 'abcd' + unichr(3421) <NEW_LINE> unicode_string_view = memoryview(unicode_string.encode('utf-8')) <NEW_LINE> r['unicode-string-memoryview'] = unicode_string_view <NEW_LINE> cached_val = r['unicode-string-memoryview'] <NEW_LINE> assert isinstance(cached_val, unicode) <NEW_LINE> assert unicode_string == cached_val <NEW_LINE> <DEDENT> def test_list_encoding(self, r): <NEW_LINE> <INDENT> unicode_string = unichr(3456) + 'abcd' + unichr(3421) <NEW_LINE> result = [unicode_string, unicode_string, unicode_string] <NEW_LINE> r.rpush('a', *result) <NEW_LINE> assert r.lrange('a', 0, -1) == result | We must import the entire class due to the seperate fixture that uses RedisCluster as client
class instead of the normal Redis instance.
FIXME: If possible, monkeypatching TestEncoding class would be preferred but kinda impossible in reality | 625990755fdd1c0f98e5f8bc |
class BaseData( object ): <NEW_LINE> <INDENT> def __init__(self, name,type="BaseData"): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.type = type <NEW_LINE> <DEDENT> def show( self ): <NEW_LINE> <INDENT> itsme = "\n%s \n\t name = %s" % (self.type, self.name) <NEW_LINE> for item in dir(self): <NEW_LINE> <INDENT> if item.find('__')>=0 : continue <NEW_LINE> attr = getattr(self,item) <NEW_LINE> if attr is not None: <NEW_LINE> <INDENT> if type(attr)==str: <NEW_LINE> <INDENT> print(item, "(str) = ", attr) <NEW_LINE> <DEDENT> elif type(attr)==np.ndarray: <NEW_LINE> <INDENT> print(item, ": ndarray of dimension(s) ", attr.shape) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(item, " = ", type(attr)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def show2( self ): <NEW_LINE> <INDENT> itsme = "\n%s from %s :" % (self.type, self.name) <NEW_LINE> myplottables = self.get_plottables() <NEW_LINE> for key, array in myplottables.items(): <NEW_LINE> <INDENT> itsme += "\n\t %s: \t %s " % (key, array.shape) <NEW_LINE> <DEDENT> print(itsme) <NEW_LINE> return <NEW_LINE> <DEDENT> def get_plottables_base(self): <NEW_LINE> <INDENT> plottables = {} <NEW_LINE> for item in dir(self): <NEW_LINE> <INDENT> if item.find('__')>=0 : continue <NEW_LINE> attr = getattr(self,item) <NEW_LINE> if attr is not None: <NEW_LINE> <INDENT> if type(attr)==np.ndarray: <NEW_LINE> <INDENT> plottables[item] = attr <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return plottables <NEW_LINE> <DEDENT> def get_plottables(self): <NEW_LINE> <INDENT> return self.get_plottables_base() | Base class for container objects storing event data
in memory (as numpy arrays mainly). Useful for passing
the data to e.g. ipython for further investigation | 6259907501c39578d7f143d4 |
class Generic_dbutils(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tname(self, table): <NEW_LINE> <INDENT> if table != 'biosequence': <NEW_LINE> <INDENT> return table <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'bioentry' <NEW_LINE> <DEDENT> <DEDENT> def last_id(self, cursor, table): <NEW_LINE> <INDENT> table = self.tname(table) <NEW_LINE> sql = r"select max(%s_id) from %s" % (table, table) <NEW_LINE> cursor.execute(sql) <NEW_LINE> rv = cursor.fetchone() <NEW_LINE> return rv[0] <NEW_LINE> <DEDENT> def execute(self, cursor, sql, args=None): <NEW_LINE> <INDENT> cursor.execute(sql, args or ()) <NEW_LINE> <DEDENT> def autocommit(self, conn, y=1): <NEW_LINE> <INDENT> pass | Default database utilities. | 6259907599fddb7c1ca63a74 |
class TaskAborted(Exception): <NEW_LINE> <INDENT> pass | The task has been aborted.
This is similiar to JobAborted, but derives from Exception instead of
BaseException.
The TaskAborted exception is used to communicate to Celery to 'fail' the
job. The JobAborted exception cannot be used; since its base is
BaseException, it will cause the Celery worker to exit. So when
JobAborted is raised, it is converted to a TaskAborted exception and
then raised for Celery to handle. | 625990758a349b6b43687b98 |
class RunTest: <NEW_LINE> <INDENT> def __init__(self, server=None): <NEW_LINE> <INDENT> self.speedTest = speedtest.Speedtest() <NEW_LINE> if server: <NEW_LINE> <INDENT> self.server = server <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.server = "" <NEW_LINE> <DEDENT> <DEDENT> def runPing(self): <NEW_LINE> <INDENT> if self.server: <NEW_LINE> <INDENT> if not looksLikeInt(self.server): <NEW_LINE> <INDENT> self.speedTest.get_best_server(self.speedTest.set_mini_server(self.server)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.speedTest.get_servers([self.server]) <NEW_LINE> self.speedTest.get_best_server() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.speedTest.get_best_server() <NEW_LINE> <DEDENT> <DEDENT> def runDownload(self): <NEW_LINE> <INDENT> self.speedTest.download() <NEW_LINE> <DEDENT> def runUpload(self): <NEW_LINE> <INDENT> self.speedTest.upload() <NEW_LINE> <DEDENT> def getResults(self): <NEW_LINE> <INDENT> return self.speedTest.results.dict() | By encapsulating SpeedTest into a class, it makes more obvious to run only ping tests | 625990753317a56b869bf1e5 |
class PermissionComparisonNode(ResolverNode): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def handle_token(cls, parser, token): <NEW_LINE> <INDENT> bits = token.contents.split() <NEW_LINE> if 5 < len(bits) < 3: <NEW_LINE> <INDENT> raise template.TemplateSyntaxError("'%s' tag takes three, " "four or five arguments" % bits[0]) <NEW_LINE> <DEDENT> end_tag = 'endifhasperm' <NEW_LINE> nodelist_true = parser.parse(('else', end_tag)) <NEW_LINE> token = parser.next_token() <NEW_LINE> if token.contents == 'else': <NEW_LINE> <INDENT> nodelist_false = parser.parse((end_tag,)) <NEW_LINE> parser.delete_first_token() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> nodelist_false = template.NodeList() <NEW_LINE> <DEDENT> if len(bits) == 3: <NEW_LINE> <INDENT> objs = (None, None) <NEW_LINE> <DEDENT> elif len(bits) == 4: <NEW_LINE> <INDENT> objs = (bits[3], None) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> objs = (bits[3], bits[4]) <NEW_LINE> <DEDENT> return cls(bits[2], bits[1], nodelist_true, nodelist_false, *objs) <NEW_LINE> <DEDENT> def __init__(self, user, perm, nodelist_true, nodelist_false, *objs): <NEW_LINE> <INDENT> self.user = user <NEW_LINE> self.objs = objs <NEW_LINE> self.perm = perm <NEW_LINE> self.nodelist_true = nodelist_true <NEW_LINE> self.nodelist_false = nodelist_false <NEW_LINE> <DEDENT> def render(self, context): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user = self.resolve(self.user, context) <NEW_LINE> perm = self.resolve(self.perm, context) <NEW_LINE> if self.objs: <NEW_LINE> <INDENT> objs = [] <NEW_LINE> for obj in self.objs: <NEW_LINE> <INDENT> if obj is not None: <NEW_LINE> <INDENT> objs.append(self.resolve(obj, context)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> objs = None <NEW_LINE> <DEDENT> check = get_check(user, perm) <NEW_LINE> if check is not None: <NEW_LINE> <INDENT> if check(*objs): <NEW_LINE> <INDENT> return self.nodelist_true.render(context) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except (ImproperlyConfigured, ImportError): <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> except template.VariableDoesNotExist: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> except (TypeError, AttributeError): <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> return self.nodelist_false.render(context) | Implements a node to provide an "if user/group has permission on object" | 625990757047854f46340cf9 |
class Category(models.Model): <NEW_LINE> <INDENT> name = models.CharField(_('category name'), max_length=20) <NEW_LINE> created_time = models.DateTimeField(_('create time'), auto_now_add=True) <NEW_LINE> last_modified_time = models.DateTimeField(_('last modified time'), auto_now=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.name | 储存文章的分类信息 | 62599075dd821e528d6da622 |
class Field(GDALBase): <NEW_LINE> <INDENT> def __init__(self, feat, index): <NEW_LINE> <INDENT> self._feat = feat <NEW_LINE> self._index = index <NEW_LINE> fld_ptr = capi.get_feat_field_defn(feat.ptr, index) <NEW_LINE> if not fld_ptr: <NEW_LINE> <INDENT> raise OGRException('Cannot create OGR Field, invalid pointer given.') <NEW_LINE> <DEDENT> self.ptr = fld_ptr <NEW_LINE> self.__class__ = OGRFieldTypes[self.type] <NEW_LINE> if isinstance(self, OFTReal) and self.precision == 0: <NEW_LINE> <INDENT> self.__class__ = OFTInteger <NEW_LINE> self._double = True <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.value).strip() <NEW_LINE> <DEDENT> def as_double(self): <NEW_LINE> <INDENT> return capi.get_field_as_double(self._feat.ptr, self._index) <NEW_LINE> <DEDENT> def as_int(self): <NEW_LINE> <INDENT> return capi.get_field_as_integer(self._feat.ptr, self._index) <NEW_LINE> <DEDENT> def as_string(self): <NEW_LINE> <INDENT> string = capi.get_field_as_string(self._feat.ptr, self._index) <NEW_LINE> return force_text(string, encoding=self._feat.encoding, strings_only=True) <NEW_LINE> <DEDENT> def as_datetime(self): <NEW_LINE> <INDENT> yy, mm, dd, hh, mn, ss, tz = [c_int() for i in range(7)] <NEW_LINE> status = capi.get_field_as_datetime( self._feat.ptr, self._index, byref(yy), byref(mm), byref(dd), byref(hh), byref(mn), byref(ss), byref(tz)) <NEW_LINE> if status: <NEW_LINE> <INDENT> return (yy, mm, dd, hh, mn, ss, tz) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise OGRException('Unable to retrieve date & time information from the field.') <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> name = capi.get_field_name(self.ptr) <NEW_LINE> return force_text(name, encoding=self._feat.encoding, strings_only=True) <NEW_LINE> <DEDENT> @property <NEW_LINE> def precision(self): <NEW_LINE> <INDENT> return capi.get_field_precision(self.ptr) <NEW_LINE> <DEDENT> @property <NEW_LINE> def type(self): <NEW_LINE> <INDENT> return capi.get_field_type(self.ptr) <NEW_LINE> <DEDENT> @property <NEW_LINE> def type_name(self): <NEW_LINE> <INDENT> return capi.get_field_type_name(self.type) <NEW_LINE> <DEDENT> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> return self.as_string() <NEW_LINE> <DEDENT> @property <NEW_LINE> def width(self): <NEW_LINE> <INDENT> return capi.get_field_width(self.ptr) | This class wraps an OGR Field, and needs to be instantiated
from a Feature object. | 62599075be8e80087fbc09d2 |
class Deflector: <NEW_LINE> <INDENT> def __init__(self, tem): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._tem = tem <NEW_LINE> self._getter = None <NEW_LINE> self._setter = None <NEW_LINE> self.key = 'def' <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> x, y = self.get() <NEW_LINE> return f'{self.name}(x={x}, y={y})' <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self) -> str: <NEW_LINE> <INDENT> return self.__class__.__name__ <NEW_LINE> <DEDENT> def set(self, x: int, y: int): <NEW_LINE> <INDENT> self._setter(x, y) <NEW_LINE> <DEDENT> def get(self) -> Tuple[int, int]: <NEW_LINE> <INDENT> return DeflectorTuple(*self._getter()) <NEW_LINE> <DEDENT> @property <NEW_LINE> def x(self) -> int: <NEW_LINE> <INDENT> x, y = self.get() <NEW_LINE> return x <NEW_LINE> <DEDENT> @x.setter <NEW_LINE> def x(self, value: int): <NEW_LINE> <INDENT> self.set(value, self.y) <NEW_LINE> <DEDENT> @property <NEW_LINE> def y(self) -> int: <NEW_LINE> <INDENT> x, y = self.get() <NEW_LINE> return y <NEW_LINE> <DEDENT> @y.setter <NEW_LINE> def y(self, value: int): <NEW_LINE> <INDENT> self.set(self.x, value) <NEW_LINE> <DEDENT> @property <NEW_LINE> def xy(self) -> Tuple[int, int]: <NEW_LINE> <INDENT> return self.get() <NEW_LINE> <DEDENT> @xy.setter <NEW_LINE> def xy(self, values: Tuple[int, int]): <NEW_LINE> <INDENT> x, y = values <NEW_LINE> self.set(x=x, y=y) <NEW_LINE> <DEDENT> def neutral(self): <NEW_LINE> <INDENT> self._tem.setNeutral(self.key) | Generic microscope deflector object defined by X/Y values Must be
subclassed to set the self._getter, self._setter functions. | 625990752c8b7c6e89bd5128 |
class BaseQuery(orm.Query): <NEW_LINE> <INDENT> def get_or_404(self, ident, description=None): <NEW_LINE> <INDENT> rv = self.get(ident) <NEW_LINE> if rv is None: <NEW_LINE> <INDENT> abort(404, description=None) <NEW_LINE> <DEDENT> return rv <NEW_LINE> <DEDENT> def first_or_404(self, description=None): <NEW_LINE> <INDENT> rv = self.first() <NEW_LINE> if rv is None: <NEW_LINE> <INDENT> abort(404, description=None) <NEW_LINE> <DEDENT> return rv <NEW_LINE> <DEDENT> def paginate(self, page, per_page=20, error_out=True): <NEW_LINE> <INDENT> if error_out and page < 1: <NEW_LINE> <INDENT> abort(404) <NEW_LINE> <DEDENT> items = self.limit(per_page).offset((page - 1) * per_page).all() <NEW_LINE> if not items and page != 1 and error_out: <NEW_LINE> <INDENT> abort(404) <NEW_LINE> <DEDENT> if page == 1 and len(items) < per_page: <NEW_LINE> <INDENT> total = len(items) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> total = self.order_by(None).count() <NEW_LINE> <DEDENT> return Pagination(self, page, per_page, total, items) | The default query object used for models, and exposed as
:attr:`~SQLAlchemy.Query`. This can be subclassed and
replaced for individual models by setting the :attr:`~Model.query_class`
attribute. This is a subclass of a standard SQLAlchemy
:class:`~sqlalchemy.orm.query.Query` class and has all the methods of a
standard query as well. | 62599075379a373c97d9a962 |
class VariableRecoveryFastState(VariableRecoveryStateBase): <NEW_LINE> <INDENT> def __init__(self, block_addr, analysis, arch, func, stack_region=None, register_region=None, processor_state=None): <NEW_LINE> <INDENT> super().__init__(block_addr, analysis, arch, func, stack_region=stack_region, register_region=register_region) <NEW_LINE> self.processor_state = ProcessorState(self.arch) if processor_state is None else processor_state <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<VRAbstractState: %d register variables, %d stack variables>" % (len(self.register_region), len(self.stack_region)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if type(other) is not VariableRecoveryFastState: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.stack_region == other.stack_region and self.register_region == other.register_region <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> state = VariableRecoveryFastState( self.block_addr, self._analysis, self.arch, self.function, stack_region=self.stack_region.copy(), register_region=self.register_region.copy(), processor_state=self.processor_state.copy(), ) <NEW_LINE> return state <NEW_LINE> <DEDENT> def merge(self, other, successor=None): <NEW_LINE> <INDENT> replacements = {} <NEW_LINE> if successor in self.dominance_frontiers: <NEW_LINE> <INDENT> replacements = self._make_phi_variables(successor, self, other) <NEW_LINE> <DEDENT> merged_stack_region = self.stack_region.copy().replace(replacements).merge(other.stack_region, replacements=replacements) <NEW_LINE> merged_register_region = self.register_region.copy().replace(replacements).merge(other.register_region, replacements=replacements) <NEW_LINE> state = VariableRecoveryFastState( successor, self._analysis, self.arch, self.function, stack_region=merged_stack_region, register_region=merged_register_region, processor_state=self.processor_state.copy().merge(other.processor_state), ) <NEW_LINE> return state <NEW_LINE> <DEDENT> def _normalize_register_offset(self, offset): <NEW_LINE> <INDENT> return offset <NEW_LINE> <DEDENT> def _to_signed(self, n): <NEW_LINE> <INDENT> if n >= 2 ** (self.arch.bits - 1): <NEW_LINE> <INDENT> return n - 2 ** self.arch.bits <NEW_LINE> <DEDENT> return n | The abstract state of variable recovery analysis.
:ivar KeyedRegion stack_region: The stack store.
:ivar KeyedRegion register_region: The register store. | 62599075cc0a2c111447c771 |
class Layer(object): <NEW_LINE> <INDENT> def __init__(self, num_neurons, num_inputs, activation, derivative): <NEW_LINE> <INDENT> self.neurons = [Neuron(num_inputs, activation, derivative) for i in range(0, num_neurons, 1)] <NEW_LINE> <DEDENT> def process(self, inputs): <NEW_LINE> <INDENT> return [neuron.process(inputs) for neuron in self.neurons] | A layer is a layer of neurons in a neural network (sometimes called Synapses)
@property (Array<Neuron>) neurons - The neurons in the layer | 62599075aad79263cf4300f8 |
class Controller(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.add_flag = self.del_flag = self.open_flag = False <NEW_LINE> self.browser = web.Browser("websites_saved.json") <NEW_LINE> self.browser.load_links() <NEW_LINE> self.GUI = G.MainGUI(self) <NEW_LINE> self.GUI.window.mainloop() <NEW_LINE> <DEDENT> def display_Add_GUI(self): <NEW_LINE> <INDENT> self.add_flag = True <NEW_LINE> self.GUI.destroy_main_widgets() <NEW_LINE> self.GUI.add_link_GUI() <NEW_LINE> <DEDENT> def finalize_add(self): <NEW_LINE> <INDENT> topic_input = self.GUI.topic_txt.get("1.0", "end-1c") <NEW_LINE> link_input = self.GUI.link_txt.get("1.0", "end-1c") <NEW_LINE> value = self.browser.add_new_link(topic_input, link_input) <NEW_LINE> self.GUI.destroy_main_add_widgets() <NEW_LINE> if value: <NEW_LINE> <INDENT> self.GUI.display_message(True, "add") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.GUI.display_message(False, "add") <NEW_LINE> <DEDENT> self.add_flag = False <NEW_LINE> <DEDENT> def display_Del_GUI(self): <NEW_LINE> <INDENT> self.del_flag = True <NEW_LINE> self.GUI.destroy_main_widgets() <NEW_LINE> self.GUI.del_link_GUI() <NEW_LINE> <DEDENT> def finalize_del(self): <NEW_LINE> <INDENT> link = self.GUI.link_txt.get("1.0", "end-1c") <NEW_LINE> value = self.browser.remove_link(link) <NEW_LINE> self.GUI.destroy_main_del_widgets() <NEW_LINE> if value: <NEW_LINE> <INDENT> self.GUI.display_message(True, "del") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.GUI.display_message(False, "del") <NEW_LINE> <DEDENT> self.del_flag = False <NEW_LINE> <DEDENT> def open_Browser_GUI(self): <NEW_LINE> <INDENT> self.open_flag = True <NEW_LINE> self.GUI.destroy_main_widgets() <NEW_LINE> topics = set(self.browser.get_topics()) <NEW_LINE> topics.add('Select') <NEW_LINE> self.GUI.open_brow_GUI(topics) <NEW_LINE> <DEDENT> def finalize_opening(self, *args): <NEW_LINE> <INDENT> self.GUI.destroy_main_open_widgets() <NEW_LINE> topic = self.GUI.tkvar.get() <NEW_LINE> status = self.browser.open_browser_GUI(topic) <NEW_LINE> if status: <NEW_LINE> <INDENT> self.GUI.display_message(True, "Open") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.GUI.display_message(False, "Open") <NEW_LINE> <DEDENT> self.open_flag = False <NEW_LINE> <DEDENT> def close_program(self): <NEW_LINE> <INDENT> exit(0) <NEW_LINE> <DEDENT> def go_back_main_menu(self): <NEW_LINE> <INDENT> if self.add_flag: <NEW_LINE> <INDENT> self.GUI.destroy_add_widgets() <NEW_LINE> <DEDENT> elif self.del_flag: <NEW_LINE> <INDENT> self.GUI.destroy_del_widgets() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.GUI.destroy_open_widgets() <NEW_LINE> <DEDENT> self.GUI.display_menu() | Manage: GUI vs Back-End code | 625990755166f23b2e244d16 |
class ChoiceAndCharInputWidget(ExtendedMultiWidget): <NEW_LINE> <INDENT> def __init__(self, choices=None, attrs=None, widgets=None, widget_css_class='choice-and-char-widget', **kwargs): <NEW_LINE> <INDENT> if not attrs: <NEW_LINE> <INDENT> attrs = {} <NEW_LINE> <DEDENT> if not widgets: <NEW_LINE> <INDENT> widgets = ( Select(choices=choices), TextInput() ) <NEW_LINE> <DEDENT> super(ChoiceAndCharInputWidget, self).__init__( widgets=widgets, attrs=attrs, widget_css_class=widget_css_class, **kwargs ) <NEW_LINE> <DEDENT> def decompress(self, value): <NEW_LINE> <INDENT> if value: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> return [None, None] | Renders choice field and char field next to each other. | 625990758e7ae83300eea9d3 |
class LogoutThenLoginView(LogoutView): <NEW_LINE> <INDENT> next_page = settings.LOGIN_URL <NEW_LINE> template_name = 'registration/logged_out.html' | Thoát xong nhảy tới trang login. | 625990755fc7496912d48f0a |
class PersonTag(Row): <NEW_LINE> <INDENT> table_name = 'person_tag' <NEW_LINE> primary_key = 'person_tag_id' <NEW_LINE> fields = { 'person_tag_id': Parameter(int, "Person setting identifier"), 'person_id': Person.fields['person_id'], 'email': Person.fields['email'], 'tag_type_id': TagType.fields['tag_type_id'], 'tagname': TagType.fields['tagname'], 'description': TagType.fields['description'], 'category': TagType.fields['category'], 'value': Parameter(str, "Person setting value"), } | Representation of a row in the person_tag.
To use, instantiate with a dict of values. | 625990753539df3088ecdbd8 |
class WatchdogWorkerProcess(WorkerProcess): <NEW_LINE> <INDENT> def _start_file_watcher(self, project_dir): <NEW_LINE> <INDENT> restart_callback = WatchdogRestarter(self._restart_event) <NEW_LINE> watcher = WatchdogFileWatcher() <NEW_LINE> watcher.watch_for_file_changes( project_dir, restart_callback) | Worker that runs the chalice dev server. | 62599075627d3e7fe0e087c9 |
@total_ordering <NEW_LINE> class RateLimitItem(metaclass=RateLimitItemMeta): <NEW_LINE> <INDENT> __slots__ = ["namespace", "amount", "multiples", "granularity"] <NEW_LINE> GRANULARITY: Granularity <NEW_LINE> def __init__( self, amount: int, multiples: Optional[int] = 1, namespace: str = "LIMITER" ): <NEW_LINE> <INDENT> self.namespace = namespace <NEW_LINE> self.amount = int(amount) <NEW_LINE> self.multiples = int(multiples or 1) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def check_granularity_string(cls, granularity_string: str) -> bool: <NEW_LINE> <INDENT> return granularity_string.lower() in cls.GRANULARITY.name <NEW_LINE> <DEDENT> def get_expiry(self) -> int: <NEW_LINE> <INDENT> return self.GRANULARITY.seconds * self.multiples <NEW_LINE> <DEDENT> def key_for(self, *identifiers) -> str: <NEW_LINE> <INDENT> remainder = "/".join( [safe_string(k) for k in identifiers] + [ safe_string(self.amount), safe_string(self.multiples), self.GRANULARITY.name, ] ) <NEW_LINE> return "%s/%s" % (self.namespace, remainder) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.amount == other.amount and self.GRANULARITY == other.GRANULARITY <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "%d per %d %s" % (self.amount, self.multiples, self.GRANULARITY.name) <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> return self.GRANULARITY.seconds < other.GRANULARITY.seconds | defines a Rate limited resource which contains the characteristic
namespace, amount and granularity multiples of the rate limiting window.
:param amount: the rate limit amount
:param multiples: multiple of the 'per' :attr:`GRANULARITY`
(e.g. 'n' per 'm' seconds)
:param namespace: category for the specific rate limit | 6259907501c39578d7f143d5 |
class GaussRV(RV_with_mean_and_cov): <NEW_LINE> <INDENT> def _sample(self, N): <NEW_LINE> <INDENT> R = self.C.Right <NEW_LINE> D = rnd.randn(N, len(R)) @ R <NEW_LINE> return D | Gaussian (Normal) multivariate random variable. | 6259907599fddb7c1ca63a75 |
class TemplateArgsTest(InvenioTestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setup_app(cls, app): <NEW_LINE> <INDENT> from invenio.ext.template.context_processor import template_args <NEW_LINE> from invenio.modules.collections.views.collections import index <NEW_LINE> @template_args(index) <NEW_LINE> def foo(): <NEW_LINE> <INDENT> return {'foo': 'foo', 'baz': 'baz'} <NEW_LINE> <DEDENT> @template_args('collections.index', app=app) <NEW_LINE> def bar(): <NEW_LINE> <INDENT> return {'bar': 'bar', 'baz': 'BAZ'} <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def config(self): <NEW_LINE> <INDENT> from invenio.base.config import EXTENSIONS <NEW_LINE> cfg = super(TemplateArgsTest, self).config <NEW_LINE> cfg['EXTENSIONS'] = EXTENSIONS + [ 'invenio.testsuite.test_ext_template.TemplateArgsTest'] <NEW_LINE> return cfg <NEW_LINE> <DEDENT> def test_template_args_loading(self): <NEW_LINE> <INDENT> self.client.get(url_for('collections.index')) <NEW_LINE> self.assertEqual(self.get_context_variable('foo'), 'foo') <NEW_LINE> self.assertEqual(self.get_context_variable('bar'), 'bar') <NEW_LINE> self.assertEqual(self.get_context_variable('baz'), 'BAZ') | Test ``template_args`` decorator. | 6259907597e22403b383c844 |
class __API(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> if 'LIBCASM' in os.environ: <NEW_LINE> <INDENT> libname = os.environ['LIBCASM'] <NEW_LINE> <DEDENT> elif 'CASM_PREFIX' in os.environ: <NEW_LINE> <INDENT> libname = glob.glob(join(os.environ['CASM_PREFIX'], 'lib', 'libcasm.*'))[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> libname = glob.glob(join('/usr', 'local', 'lib', 'libcasm.*'))[0] <NEW_LINE> <DEDENT> self.lib_casm = ctypes.CDLL(libname, mode=ctypes.RTLD_GLOBAL) <NEW_LINE> if 'LIBCCASM' in os.environ: <NEW_LINE> <INDENT> libname = os.environ['LIBCCASM'] <NEW_LINE> <DEDENT> elif 'CASM_PREFIX' in os.environ: <NEW_LINE> <INDENT> libname = glob.glob(join(os.environ['CASM_PREFIX'], 'lib', 'libccasm.*'))[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> libname = glob.glob(join('/usr', 'local', 'lib', 'libccasm.*'))[0] <NEW_LINE> <DEDENT> self.lib_ccasm = ctypes.CDLL(libname, mode=ctypes.RTLD_GLOBAL) <NEW_LINE> self.lib_ccasm.casm_STDOUT.restype = ctypes.c_void_p <NEW_LINE> self.lib_ccasm.casm_STDERR.restype = ctypes.c_void_p <NEW_LINE> self.lib_ccasm.casm_nullstream.restype = ctypes.c_void_p <NEW_LINE> self.lib_ccasm.casm_ostringstream_new.restype = ctypes.c_void_p <NEW_LINE> self.lib_ccasm.casm_ostringstream_delete.argtypes = [ctypes.c_void_p] <NEW_LINE> self.lib_ccasm.casm_ostringstream_delete.restype = None <NEW_LINE> self.lib_ccasm.casm_ostringstream_size.argtypes = [ctypes.c_void_p] <NEW_LINE> self.lib_ccasm.casm_ostringstream_size.restype = ctypes.c_ulong <NEW_LINE> self.lib_ccasm.casm_ostringstream_strcpy.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_char)] <NEW_LINE> self.lib_ccasm.casm_ostringstream_strcpy.restype = ctypes.POINTER(ctypes.c_char) <NEW_LINE> self.lib_ccasm.casm_primclex_new.argtypes = [ctypes.c_char_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] <NEW_LINE> self.lib_ccasm.casm_primclex_new.restype = ctypes.c_void_p <NEW_LINE> self.lib_ccasm.casm_primclex_delete.argtypes = [ctypes.c_void_p] <NEW_LINE> self.lib_ccasm.casm_primclex_delete.restype = None <NEW_LINE> self.lib_ccasm.casm_primclex_refresh.argtypes = [ctypes.c_void_p, ctypes.c_bool, ctypes.c_bool, ctypes.c_bool, ctypes.c_bool, ctypes.c_bool] <NEW_LINE> self.lib_ccasm.casm_primclex_refresh.restype = None <NEW_LINE> self.lib_ccasm.casm_capi.argtypes = [ctypes.c_char_p, ctypes.c_void_p, ctypes.c_char_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] <NEW_LINE> self.lib_ccasm.casm_capi.restype = ctypes.c_int | Hidden class of which there will be only one instance
Attributes
----------
lib_casm: ctypes.CDLL
Handle to libcasm.*
lib_ccasm: ctypes.CDLL
Handle to libccasm.* | 62599075d268445f2663a7fe |
@method_decorator(csp_exempt, name="dispatch") <NEW_LINE> class CreateFlatPage(LoginRequiredMixin, PermissionRequiredMixin, CreateView): <NEW_LINE> <INDENT> permission_required = "flatpage.add_flatpage" <NEW_LINE> model = flatpages.models.FlatPage <NEW_LINE> form_class = forms.FlatPage <NEW_LINE> def get_success_url(self): <NEW_LINE> <INDENT> return urls.reverse("manage-flatpages") | Create flat page. | 625990758a349b6b43687b9a |
class updateDataVersion_result: <NEW_LINE> <INDENT> thrift_spec = ( (0, TType.I32, 'success', None, None, ), ) <NEW_LINE> def __init__(self, success=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.I32: <NEW_LINE> <INDENT> self.success = iprot.readI32(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('updateDataVersion_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.I32, 0) <NEW_LINE> oprot.writeI32(self.success) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- success | 625990753317a56b869bf1e6 |
class PhysicalCoordinate(Coord): <NEW_LINE> <INDENT> def __init__(self, model_view): <NEW_LINE> <INDENT> super().__init__(model_view) <NEW_LINE> self.cval = None <NEW_LINE> self.dmtype = "PhysicalCoordinate" <NEW_LINE> for ele in model_view.xpath('.//INSTANCE[@dmrole="coords:PhysicalCoordinate.cval"]'): <NEW_LINE> <INDENT> self.cval = Quantity(ele) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return f"[{self.dmtype}: {self.cval} {self.coordSys}]" | classdocs | 625990753346ee7daa338301 |
class MachineTranslationTest(TestCase): <NEW_LINE> <INDENT> def test_support(self): <NEW_LINE> <INDENT> machine_translation = DummyTranslation() <NEW_LINE> self.assertTrue(machine_translation.is_supported('cs')) <NEW_LINE> self.assertFalse(machine_translation.is_supported('de')) <NEW_LINE> <DEDENT> def test_translate(self): <NEW_LINE> <INDENT> machine_translation = DummyTranslation() <NEW_LINE> self.assertEqual( machine_translation.translate('cs', 'Hello', None, None), [] ) <NEW_LINE> self.assertEqual( len( machine_translation.translate( 'cs', 'Hello, world!', None, None ) ), 2 ) <NEW_LINE> <DEDENT> def assertTranslate(self, machine, lang='cs', word='world'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> translation = machine.translate(lang, word, None, None) <NEW_LINE> self.assertIsInstance(translation, list) <NEW_LINE> <DEDENT> except MachineTranslationError as exc: <NEW_LINE> <INDENT> self.skipTest(str(exc)) <NEW_LINE> <DEDENT> <DEDENT> def test_glosbe(self): <NEW_LINE> <INDENT> machine = GlosbeTranslation() <NEW_LINE> self.assertTranslate(machine) <NEW_LINE> <DEDENT> def test_mymemory(self): <NEW_LINE> <INDENT> machine = MyMemoryTranslation() <NEW_LINE> self.assertTranslate(machine) <NEW_LINE> <DEDENT> def test_opentran(self): <NEW_LINE> <INDENT> machine = OpenTranTranslation() <NEW_LINE> self.assertTranslate(machine) <NEW_LINE> <DEDENT> def test_apertium(self): <NEW_LINE> <INDENT> machine = ApertiumTranslation() <NEW_LINE> self.assertTranslate(machine, 'es') <NEW_LINE> <DEDENT> @skipUnless(microsoft_translation_supported(), 'missing credentials') <NEW_LINE> def test_microsoft(self): <NEW_LINE> <INDENT> machine = MicrosoftTranslation() <NEW_LINE> self.assertTranslate(machine) <NEW_LINE> <DEDENT> def test_google(self): <NEW_LINE> <INDENT> machine = GoogleWebTranslation() <NEW_LINE> self.assertTranslate(machine) <NEW_LINE> <DEDENT> def test_amagama(self): <NEW_LINE> <INDENT> machine = AmagamaTranslation() <NEW_LINE> self.assertTranslate(machine) | Testing of machine translation core. | 62599075be7bc26dc9252af6 |
class Connector(AbstractConnector): <NEW_LINE> <INDENT> def __init__(self, index, statuses, resultsQueue, freeWorker, cfg, warebox, enc_dir, lockfile_fd): <NEW_LINE> <INDENT> AbstractConnector.__init__(self, index, statuses, resultsQueue, freeWorker) <NEW_LINE> self.cfg = cfg <NEW_LINE> self.warebox = warebox <NEW_LINE> self.enc_dir = enc_dir <NEW_LINE> self.lockfile_fd = lockfile_fd <NEW_LINE> <DEDENT> def start_WorkerWatcher(self): <NEW_LINE> <INDENT> self.worker = self.WorkerWatcher(self.index, self.queue, self, self.cfg, self.warebox, self.enc_dir, self.lockfile_fd) <NEW_LINE> self.worker.start() <NEW_LINE> <DEDENT> def _on_init(self): <NEW_LINE> <INDENT> self.WorkerWatcher = WorkerWatcher | CryptoConnector extend the prototypes.Connector.Connector | 62599075435de62698e9d74a |
class V1beta3_ServiceSpec(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.swaggerTypes = { 'createExternalLoadBalancer': 'bool', 'portalIP': 'str', 'ports': 'list[V1beta3_ServicePort]', 'publicIPs': 'list[str]', 'selector': 'dict', 'sessionAffinity': 'str' } <NEW_LINE> self.attributeMap = { 'createExternalLoadBalancer': 'createExternalLoadBalancer', 'portalIP': 'portalIP', 'ports': 'ports', 'publicIPs': 'publicIPs', 'selector': 'selector', 'sessionAffinity': 'sessionAffinity' } <NEW_LINE> self.createExternalLoadBalancer = None <NEW_LINE> self.portalIP = None <NEW_LINE> self.ports = None <NEW_LINE> self.publicIPs = None <NEW_LINE> self.selector = None <NEW_LINE> self.sessionAffinity = None | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 6259907566673b3332c31d40 |
class MoveTo(Action): <NEW_LINE> <INDENT> def __init__(self, bot, pos): <NEW_LINE> <INDENT> super(MoveTo, self).__init__(bot) <NEW_LINE> self.pos = pos <NEW_LINE> <DEDENT> def do(self): <NEW_LINE> <INDENT> delta = self.pos - self.bot.pos <NEW_LINE> if delta.length() < 1: <NEW_LINE> <INDENT> self.bot.move(delta) <NEW_LINE> return None <NEW_LINE> <DEDENT> delta.normalize() <NEW_LINE> self.bot.move(delta) <NEW_LINE> return self | I would move to a coordinate, but John has been concentrating on mining | 62599075d486a94d0ba2d8fb |
class WideResNet16(WideResNet): <NEW_LINE> <INDENT> blocks_per_group = ( (16 - 4) // 6, (16 - 4) // 6, (16 - 4) // 6, ) | 16-layer wide residual network with v1 structure. | 6259907556ac1b37e6303983 |
class IdaCMD(DisasCMD): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def identify(path): <NEW_LINE> <INDENT> return os.path.split(path)[-1].split('.')[0].lower().startswith("ida") <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def name(): <NEW_LINE> <INDENT> return "IDA" <NEW_LINE> <DEDENT> def createDatabase(self, binary_file, is_windows): <NEW_LINE> <INDENT> type = "elf" if not is_windows else "coff" <NEW_LINE> suffix = ".i64" if self._path.endswith("64") else ".idb" <NEW_LINE> database_file = binary_file + suffix <NEW_LINE> os.system("%s -A -B -T%s -o%s %s" % (self._path, type, database_file, binary_file)) <NEW_LINE> return database_file <NEW_LINE> <DEDENT> def executeScript(self, database, script): <NEW_LINE> <INDENT> os.system("%s -A -S%s %s" % (self._path, script, database)) | DisasCMD implementation for the IDA disassembler. | 62599075379a373c97d9a964 |
class McCallModel: <NEW_LINE> <INDENT> def __init__(self, α=0.2, β=0.98, γ=0.7, c=6.0, σ=2.0, w_vec=None, p_vec=None): <NEW_LINE> <INDENT> self.α, self.β, self.γ, self.c = α, β, γ, c <NEW_LINE> self.σ = σ <NEW_LINE> if w_vec is None: <NEW_LINE> <INDENT> n = 60 <NEW_LINE> self.w_vec = np.linspace(10, 20, n) <NEW_LINE> a, b = 600, 400 <NEW_LINE> dist = BetaBinomial(n-1, a, b) <NEW_LINE> self.p_vec = dist.pdf() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.w_vec = w_vec <NEW_LINE> self.p_vec = p_vec | Stores the parameters and functions associated with a given model. | 62599075a05bb46b3848bdcc |
class DAO(object): <NEW_LINE> <INDENT> def data_dyad(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def data_monad(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def iter(self): <NEW_LINE> <INDENT> raise NotImplementedError() | I'm not actually sure how abstractions/interfaces are implemented in Python. But here you go.
It's supposed to describe the interface of how input--output pairs are retrieved. | 62599075091ae3566870657b |
class BaseModel: <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> if len(kwargs) > 0: <NEW_LINE> <INDENT> for key, value in kwargs.items(): <NEW_LINE> <INDENT> if key == "updated_at": <NEW_LINE> <INDENT> value = datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%f") <NEW_LINE> <DEDENT> elif key == "created_at": <NEW_LINE> <INDENT> value = datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%f") <NEW_LINE> <DEDENT> elif key == "__class__": <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> setattr(self, key, value) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.id = str(uuid.uuid4()) <NEW_LINE> self.created_at = datetime.now() <NEW_LINE> self.updated_at = datetime.now() <NEW_LINE> models.storage.new(self) <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> class_name = type(self).__name__ <NEW_LINE> mssg = "[{0}] ({1}) {2}".format(class_name, self.id, self.__dict__) <NEW_LINE> return (mssg) <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> self.updated_at = datetime.now() <NEW_LINE> models.storage.save() <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> tdic = {} <NEW_LINE> tdic["__class__"] = type(self).__name__ <NEW_LINE> for var, value in self.__dict__.items(): <NEW_LINE> <INDENT> if isinstance(value, datetime): <NEW_LINE> <INDENT> tdic[var] = value.isoformat() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tdic[var] = value <NEW_LINE> <DEDENT> <DEDENT> return (tdic) | class for all other classes to inherit from | 625990755fc7496912d48f0b |
class Twitter: <NEW_LINE> <INDENT> HASH_TAG = "#BCDev" <NEW_LINE> TWITTER_STATUS_LENGTH = 140 <NEW_LINE> DEFAULT_TWITTER_URL_LENGTH = 23 <NEW_LINE> ELLIPSIS = u"\u2026" <NEW_LINE> def __init__(self, twitter_credentials, twitter_config_store): <NEW_LINE> <INDENT> auth = tweepy.OAuthHandler(twitter_credentials['consumer_key'], twitter_credentials['consumer_secret']) <NEW_LINE> auth.set_access_token(twitter_credentials['access_token'], twitter_credentials['access_token_secret']) <NEW_LINE> self._api = tweepy.API(auth) <NEW_LINE> self._twitter_config_store = twitter_config_store <NEW_LINE> self._twitter_config = dict() <NEW_LINE> <DEDENT> def tweet_new_issue(self, url, title): <NEW_LINE> <INDENT> status = self._create_status(url, title, "New issue:") <NEW_LINE> self._api.update_status(status) <NEW_LINE> logger.info("Tweeted " + status) <NEW_LINE> <DEDENT> def _create_status(self, url, title, prefix): <NEW_LINE> <INDENT> stripped_prefix = prefix.strip() <NEW_LINE> stripped_title = title.strip() <NEW_LINE> description = "{0} {1}".format(stripped_prefix, stripped_title) <NEW_LINE> formatting_spaces = 2 <NEW_LINE> url_length = self.get_url_length(url) <NEW_LINE> tweet_length = len(description) + url_length + len(Twitter.HASH_TAG) + formatting_spaces <NEW_LINE> if tweet_length > Twitter.TWITTER_STATUS_LENGTH: <NEW_LINE> <INDENT> over_length = tweet_length - Twitter.TWITTER_STATUS_LENGTH <NEW_LINE> description = "{0}{1}".format(description[0:len(description) - over_length - len(Twitter.ELLIPSIS)], Twitter.ELLIPSIS) <NEW_LINE> <DEDENT> status = "{0} {1} {2}".format(description, url, Twitter.HASH_TAG) <NEW_LINE> return status <NEW_LINE> <DEDENT> def get_url_length(self, url): <NEW_LINE> <INDENT> url_length = Twitter.DEFAULT_TWITTER_URL_LENGTH <NEW_LINE> str_url = str(url).lower() <NEW_LINE> if str_url.startswith('http://'): <NEW_LINE> <INDENT> url_length = self.get_short_url_length() <NEW_LINE> <DEDENT> elif str_url.startswith('https://'): <NEW_LINE> <INDENT> url_length = self.get_short_url_length_https() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.warning("Could not determine protocol for url " + url) <NEW_LINE> <DEDENT> return url_length <NEW_LINE> <DEDENT> def get_short_url_length(self): <NEW_LINE> <INDENT> return self._get_url_length_from_config('short_url_length') <NEW_LINE> <DEDENT> def get_short_url_length_https(self): <NEW_LINE> <INDENT> return self._get_url_length_from_config('short_url_length_https') <NEW_LINE> <DEDENT> def _get_url_length_from_config(self, key_value): <NEW_LINE> <INDENT> self._load_twitter_config() <NEW_LINE> url_length = Twitter.DEFAULT_TWITTER_URL_LENGTH <NEW_LINE> try: <NEW_LINE> <INDENT> url_length = self._twitter_config[key_value] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> logger.exception("Could not obtain {0}, using default value".format(key_value)) <NEW_LINE> <DEDENT> return url_length <NEW_LINE> <DEDENT> def _load_twitter_config(self): <NEW_LINE> <INDENT> if len(self._twitter_config) == 0: <NEW_LINE> <INDENT> self._twitter_config = self._twitter_config_store.get() <NEW_LINE> <DEDENT> <DEDENT> def reset_twitter_config(self): <NEW_LINE> <INDENT> self._twitter_config_store.save(self._api.configuration()) | Class for interacting with the Tweepy API and formatting twitter statuses. | 62599075adb09d7d5dc0bead |
class Circle: <NEW_LINE> <INDENT> def __init__(self, radius): <NEW_LINE> <INDENT> self.radius = radius <NEW_LINE> <DEDENT> @property <NEW_LINE> def diameter(self): <NEW_LINE> <INDENT> return self.radius * 2 <NEW_LINE> <DEDENT> @diameter.setter <NEW_LINE> def diameter(self, value): <NEW_LINE> <INDENT> self.radius = value/2 <NEW_LINE> <DEDENT> @property <NEW_LINE> def area(self): <NEW_LINE> <INDENT> return math.pi * self.radius ** 2 <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_diameter(cls, diameter): <NEW_LINE> <INDENT> radius = diameter/2 <NEW_LINE> return cls(radius) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return f"Circle({self.radius})" <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f"Circle with radius: {float(self.radius)}" <NEW_LINE> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> return Circle(self.radius + other.radius) <NEW_LINE> <DEDENT> def __mul__(self, other): <NEW_LINE> <INDENT> return Circle(self.radius * other) <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> return self.radius < other.radius <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.radius == other.radius <NEW_LINE> <DEDENT> def __gt__(self, other): <NEW_LINE> <INDENT> self.radius > other.radius <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return self.radius != other.radius <NEW_LINE> <DEDENT> def __rmul__(self, other): <NEW_LINE> <INDENT> return Circle(other * self.radius) <NEW_LINE> <DEDENT> def __iadd__(self, other): <NEW_LINE> <INDENT> return Circle(self.radius + other.radius) <NEW_LINE> <DEDENT> def __imul__(self, other): <NEW_LINE> <INDENT> return Circle(self.radius * other) | create a circle class that represents a simple circle | 6259907501c39578d7f143d6 |
class PluginTemplateEngine(): <NEW_LINE> <INDENT> def __init__(self, config: dict, dotbot: dict) -> None: <NEW_LINE> <INDENT> self.config = config <NEW_LINE> self.dotbot = dotbot <NEW_LINE> self.logger_level = '' <NEW_LINE> self.bot = None <NEW_LINE> self.logger = None <NEW_LINE> <DEDENT> def init(self, bot: ChatbotEngine): <NEW_LINE> <INDENT> self.bot = bot <NEW_LINE> self.logger = DotFlow2LoggerAdapter(logging.getLogger('df2_ext.template_e'), self, self.bot, 'Jinja2') <NEW_LINE> <DEDENT> def add_functions(self, template: Template): <NEW_LINE> <INDENT> for f_name in self.bot.functions_map: <NEW_LINE> <INDENT> template.globals[f_name] = getattr(self.bot.df2, f_name) <NEW_LINE> <DEDENT> <DEDENT> def render(self, template: str) -> str: <NEW_LINE> <INDENT> self.logger.debug('Rendering template: "' + template + '"') <NEW_LINE> df2_vars = self.bot.session.get_var(self.bot.user_id) <NEW_LINE> template = Template(template) <NEW_LINE> self.add_functions(template) <NEW_LINE> response = template.render(df2_vars) <NEW_LINE> self.logger.debug('Template response: "' + response + '"') <NEW_LINE> return response | . | 62599075f9cc0f698b1c5f6d |
class market_environment(object): <NEW_LINE> <INDENT> def __init__(self, name, pricing_date): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.pricing_date = pricing_date <NEW_LINE> self.constants = {} <NEW_LINE> self.lists = {} <NEW_LINE> self.curves = {} <NEW_LINE> <DEDENT> def add_constant(self, key, constant): <NEW_LINE> <INDENT> self.constants[key] = constant <NEW_LINE> <DEDENT> def get_constant(self, key): <NEW_LINE> <INDENT> return self.constants[key] <NEW_LINE> <DEDENT> def add_list(self, key, list_object): <NEW_LINE> <INDENT> self.lists[key] = list_object <NEW_LINE> <DEDENT> def get_list(self, key): <NEW_LINE> <INDENT> return self.lists[key] <NEW_LINE> <DEDENT> def add_curve(self, key, curve): <NEW_LINE> <INDENT> self.curves[key] = curve <NEW_LINE> <DEDENT> def get_curve(self, key): <NEW_LINE> <INDENT> return self.curves[key] <NEW_LINE> <DEDENT> def add_environment(self, env): <NEW_LINE> <INDENT> for key in env.constants: <NEW_LINE> <INDENT> self.constants[key] = env.constants[key] <NEW_LINE> <DEDENT> for key in env.lists: <NEW_LINE> <INDENT> self.lists[key] = env.lists[key] <NEW_LINE> <DEDENT> for key in env.curves: <NEW_LINE> <INDENT> self.curves[key] = env.curves[key] | Class to model a market environment relevant for valuation.
Attributes
==========
name : string
name of the market environment
pricing_date : datetime object
date of the market environment
Methods
=======
add_constant :
adds a constant (e.g. model parameter)
get_constant:
gets a constant
add_list :
adds a list (e.g. underlying)
get_list :
gets a list
add_curve :
adds a market curve (e.g. yield curve)
get_curve :
gets a market curve
add_environment :
adds and overwrites whole market environment
with constans, lists, and curves | 62599075baa26c4b54d50bf2 |
class _PlottingContext(_RCAesthetics): <NEW_LINE> <INDENT> _keys = _context_keys <NEW_LINE> _set = staticmethod(_set_context) | Light wrapper on a dict to set context temporarily. | 6259907563b5f9789fe86aa8 |
class TrackValidation: <NEW_LINE> <INDENT> def __init__(self, trackname): <NEW_LINE> <INDENT> self.track_name = trackname <NEW_LINE> self.pct_overhead_ops = 0.0 <NEW_LINE> self.pct_overhead_ops_acceptable = False <NEW_LINE> self.pct_ops_failed = 0.0 <NEW_LINE> self.pct_failed_ops_acceptable = False <NEW_LINE> self.op_response_time_targets_met = True <NEW_LINE> <DEDENT> def is_acceptable(self): <NEW_LINE> <INDENT> return self.pct_overhead_ops_acceptable and self.pct_failed_ops_acceptable and self.op_response_time_targets_met | Class for deciding whether a track summary from a run should be
considered valid based on the overheads and response times recorded | 6259907599cbb53fe683282e |
class Undo: <NEW_LINE> <INDENT> def __init__(self, folderToStore): <NEW_LINE> <INDENT> self.whatToUndo = [] <NEW_LINE> self.separator = ',' <NEW_LINE> self.folderToStore = folderToStore <NEW_LINE> self.fileOps = FileOperations() <NEW_LINE> <DEDENT> def add(self, oldPath, oldFilename, newPath, newFilename): <NEW_LINE> <INDENT> data = oldPath + self.separator + oldFilename + self.separator + newPath + self.separator + newFilename <NEW_LINE> self.whatToUndo.append(data) <NEW_LINE> <DEDENT> def generateUndoFile(self): <NEW_LINE> <INDENT> self.undoFilenameWithPath = self.folderToStore + "ToUndoTheFilesMoved_" + str(datetime.datetime.now()) + ".undo" <NEW_LINE> self.fileOps.writeLinesToFile(self.undoFilenameWithPath, self.whatToUndo) <NEW_LINE> <DEDENT> def performUndo(self, undoFilenameWithPath): <NEW_LINE> <INDENT> numberOfUndos = 0 <NEW_LINE> lines = self.fileOps.readFromFile(undoFilenameWithPath) <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> line = line.split(self.separator) <NEW_LINE> i = 0 <NEW_LINE> oldPath = line[i]; i = i + 1 <NEW_LINE> oldFilename = line[i]; i = i + 1 <NEW_LINE> currentPath = line[i]; i = i + 1 <NEW_LINE> currentFilename = line[i]; i = i + 1 <NEW_LINE> self.fileOps.moveFile(currentPath, currentFilename, oldPath, oldFilename) <NEW_LINE> numberOfUndos = numberOfUndos + 1 <NEW_LINE> <DEDENT> self.fileOps.deleteFile(undoFilenameWithPath) <NEW_LINE> print('Finished '+ str(numberOfUndos) +' undo operations. Deleted file: ', undoFilenameWithPath) <NEW_LINE> sg.popup("Completed undo operations", keep_on_top=True) | This class allows the creation of an undo file and allows using an existing undo file to undo the file operations that were performed earlier | 625990757047854f46340cfd |
class TokenManager(object): <NEW_LINE> <INDENT> def __init__(self, username=None, password=None, client_id=None, client_secret=None, app_url=defaults.APP_URL): <NEW_LINE> <INDENT> self.username = username <NEW_LINE> self.password = password <NEW_LINE> self.client_id = client_id <NEW_LINE> self.client_secret = client_secret <NEW_LINE> self.app_url = app_url <NEW_LINE> self.access_token = None <NEW_LINE> self.expires_at = 0 <NEW_LINE> <DEDENT> def is_access_token_expired(self): <NEW_LINE> <INDENT> return self.access_token == None or self.expires_at < time.time() <NEW_LINE> <DEDENT> def get_access_token(self): <NEW_LINE> <INDENT> if self.is_access_token_expired(): <NEW_LINE> <INDENT> if is_debug_enabled(): <NEW_LINE> <INDENT> debug('requesting new access_token') <NEW_LINE> <DEDENT> token = get_access_token(username=self.username, password=self.password, client_id=self.client_id, client_secret=self.client_secret, app_url=self.app_url) <NEW_LINE> self.expires_at = time.time() + token['expires_in']/2 <NEW_LINE> self.access_token = token['access_token'] <NEW_LINE> <DEDENT> return self.access_token <NEW_LINE> <DEDENT> def get_access_token_headers(self): <NEW_LINE> <INDENT> return { 'Authorization': 'Bearer %s' % self.get_access_token(), 'Content-Type': 'application/json', 'Accept': 'application/json' } | jut authentication token manager which handles the refreshing of auth
tokens as well as caching of valid authentication tokens | 625990754527f215b58eb642 |
class h3(html_tag): <NEW_LINE> <INDENT> pass | Represents the third-highest ranking heading. | 6259907592d797404e3897fd |
class LRFinder(Callback): <NEW_LINE> <INDENT> def __init__(self, min_lr=1e-5, max_lr=1e-2, steps_per_epoch=None, epochs=None, beta=0.9): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.min_lr = min_lr <NEW_LINE> self.max_lr = max_lr <NEW_LINE> self.total_iterations = steps_per_epoch * epochs <NEW_LINE> self.iteration = 0 <NEW_LINE> self.history = {} <NEW_LINE> self.beta = beta <NEW_LINE> <DEDENT> def clr(self): <NEW_LINE> <INDENT> x = np.log(1 + self.iteration / self.total_iterations) <NEW_LINE> return self.min_lr + (self.max_lr-self.min_lr) * x <NEW_LINE> <DEDENT> def on_train_begin(self, logs=None): <NEW_LINE> <INDENT> logs = logs or {} <NEW_LINE> K.set_value(self.model.optimizer.lr, self.min_lr) <NEW_LINE> <DEDENT> def on_batch_end(self, epoch, logs=None): <NEW_LINE> <INDENT> logs = logs or {} <NEW_LINE> self.iteration += 1 <NEW_LINE> self.history.setdefault('lr', []).append(K.get_value(self.model.optimizer.lr)) <NEW_LINE> self.history.setdefault('iterations', []).append(self.iteration) <NEW_LINE> for k, v in logs.items(): <NEW_LINE> <INDENT> self.history.setdefault(k, []).append(v) <NEW_LINE> <DEDENT> K.set_value(self.model.optimizer.lr, self.clr()) <NEW_LINE> <DEDENT> def smooth_fn(self, y): <NEW_LINE> <INDENT> n = len(self.history['iterations']) <NEW_LINE> beta_c = 1 - self.beta <NEW_LINE> ewa = np.zeros(n) <NEW_LINE> ewa_corrected = np.zeros(n) <NEW_LINE> ewa_corrected[0] = ewa[0] = y[0] <NEW_LINE> for i in range (1,n): <NEW_LINE> <INDENT> ewa[i] = self.beta*ewa[i-1] + beta_c*y[i] <NEW_LINE> ewa_corrected[i] = ewa[i] / (1 - self.beta**n) <NEW_LINE> <DEDENT> return ewa_corrected <NEW_LINE> <DEDENT> def plot_lr(self): <NEW_LINE> <INDENT> plt.figure(figsize=(10,6)) <NEW_LINE> plt.plot(self.history['iterations'], self.history['lr']) <NEW_LINE> plt.yscale('log') <NEW_LINE> plt.xlabel('Iteration') <NEW_LINE> plt.ylabel('LR') <NEW_LINE> plt.title("Learning rate") <NEW_LINE> <DEDENT> def plot_loss(self): <NEW_LINE> <INDENT> plt.figure(figsize=(10,6)) <NEW_LINE> smoothed_loss = self.smooth_fn(self.history['loss']) <NEW_LINE> plt.plot(self.history['lr'][1::10], smoothed_loss[1::10]) <NEW_LINE> plt.xscale('log') <NEW_LINE> plt.xlabel('LR (log scale)') <NEW_LINE> plt.ylabel('Loss') <NEW_LINE> plt.title("Loss vs Learning Rate") | The Learning Rate range test: a callback for finding the optimal learning rate range
This function will
# Usage
```
lr_finder = LRFinder(min_lr=1e-5,
max_lr=1e-2,
steps_per_epoch=np.ceil(data_size/batch_size),
epochs=3
beta=0.9)
model.fit(X_train, Y_train, callbacks=[lr_finder])
lr_finder.plot_loss()
```
# Arguments
min_lr: The lower bound of the learning rate
max_lr: The upper bound of the learning rate
steps_per_epoch: Number of iterations/mini-batches -- calculated as `np.ceil(data_size/batch_size)`.
epochs: Number of epochs to run experiment. Usually between 2 and 4 epochs is sufficient.
beta: the smoothing parameter. 0.99 ~ weighted over 100 previous values,
0.9 - 10 values.
# Acknowledgements
Author : Meena Mani (added a weighted average to plot loss)
Stater code/blog: jeremyjordan.me/nn-learning-rate
Original paper: https://arxiv.org/abs/1506.01186 | 62599075a05bb46b3848bdcd |
class Meta: <NEW_LINE> <INDENT> verbose_name_plural = _(messages.PLURAL_SYS_CONN_RESULTS_MSG) | Metadata for model. | 625990754a966d76dd5f082e |
class XP2003x64TimerVType(obj.ProfileModification): <NEW_LINE> <INDENT> conditions = {'os': lambda x: x == 'windows', 'memory_model': lambda x: x == '64bit', 'major': lambda x: x < 6} <NEW_LINE> def modification(self, profile): <NEW_LINE> <INDENT> profile.vtypes.update({ 'tagTIMER' : [ None, { 'head' : [ 0x00, ['_HEAD']], 'ListEntry' : [ 0x18, ['_LIST_ENTRY']], 'spwnd' : [ 0x28, ['pointer', ['tagWND']]], 'pti' : [ 0x20, ['pointer', ['tagTHREADINFO']]], 'nID' : [ 0x30, ['unsigned short']], 'cmsCountdown' : [ 0x38, ['unsigned int']], 'cmsRate' : [ 0x3C, ['unsigned int']], 'flags' : [ 0x40, ['Flags', {'bitmap': consts.TIMER_FLAGS}]], 'pfn' : [ 0x48, ['pointer', ['void']]], }]}) | Apply the tagTIMER for XP and 2003 x64 | 625990755166f23b2e244d1a |
class IUshahidiMapView(Interface): <NEW_LINE> <INDENT> pass | Marker Interface for Ushahidi Map View | 6259907597e22403b383c847 |
class NumericValidator(RequiredValidator): <NEW_LINE> <INDENT> def validate(self, value): <NEW_LINE> <INDENT> if value is not None: <NEW_LINE> <INDENT> if not isinstance(value, Number): <NEW_LINE> <INDENT> raise ValidationError("{value} ({type}) is not numeric".format( value=value, type=type(value))) <NEW_LINE> <DEDENT> <DEDENT> super(NumericValidator, self).validate(value) | Tests that the provided value is a python numeric type. | 62599075009cb60464d02e80 |
class SimpleProductSearchHandler(MultipleObjectMixin): <NEW_LINE> <INDENT> paginate_by = settings.OSCAR_PRODUCTS_PER_PAGE <NEW_LINE> def __init__(self, request_data, full_path, categories=None): <NEW_LINE> <INDENT> self.categories = categories <NEW_LINE> self.kwargs = {'page': request_data.get('page', 1)} <NEW_LINE> self.object_list = self.get_queryset() <NEW_LINE> <DEDENT> def get_queryset(self): <NEW_LINE> <INDENT> qs = Product.browsable.base_queryset() <NEW_LINE> if self.categories: <NEW_LINE> <INDENT> qs = qs.filter(categories__in=self.categories).distinct() <NEW_LINE> <DEDENT> return qs <NEW_LINE> <DEDENT> def get_search_context_data(self, context_object_name, request=None): <NEW_LINE> <INDENT> self.context_object_name = context_object_name <NEW_LINE> if request: <NEW_LINE> <INDENT> if request.GET.get('new', None) == 'on': <NEW_LINE> <INDENT> self.object_list = self.object_list.order_by('-date_created') <NEW_LINE> <DEDENT> if request.GET.get('promotion', None) == 'on': <NEW_LINE> <INDENT> self.object_list = self.object_list.filter(is_discountable=True) <NEW_LINE> <DEDENT> <DEDENT> context = self.get_context_data(object_list=self.object_list) <NEW_LINE> context[context_object_name] = context['page_obj'].object_list <NEW_LINE> return context | A basic implementation of the full-featured SearchHandler that has no
faceting support, but doesn't require a Haystack backend. It only
supports category browsing.
Note that is meant as a replacement search handler and not as a view
mixin; the mixin just does most of what we need it to do. | 62599075adb09d7d5dc0beaf |
class BoundaryTree: <NEW_LINE> <INDENT> def __init__(self, position, label, children=None, parent=None): <NEW_LINE> <INDENT> self.position = position <NEW_LINE> self.label = label <NEW_LINE> if children is None: <NEW_LINE> <INDENT> self.children = [] <NEW_LINE> self.childnum = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.children = children <NEW_LINE> self.childnum = len(children) <NEW_LINE> <DEDENT> self.parent = parent <NEW_LINE> <DEDENT> def __str__(self, level=0): <NEW_LINE> <INDENT> ret = '| '*level + '{}: {}\n'.format(self.position, self.label) <NEW_LINE> if self.children is not None: <NEW_LINE> <INDENT> for child in self.children: <NEW_LINE> <INDENT> ret += child.__str__(level+1) <NEW_LINE> <DEDENT> <DEDENT> return ret <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> posclose = np.allclose(self.position, other.position) <NEW_LINE> labclose = np.isclose(self.label, other.label) <NEW_LINE> return posclose and labclose <NEW_LINE> <DEDENT> def addchild(self, position, label): <NEW_LINE> <INDENT> newnode = BoundaryTree(position, label, parent=self) <NEW_LINE> self.children.append(newnode) <NEW_LINE> self.childnum += 1 <NEW_LINE> <DEDENT> def query(self, inp, maxchild=5, metric_pos=norm): <NEW_LINE> <INDENT> A = self.children[:] <NEW_LINE> if self.childnum < maxchild: <NEW_LINE> <INDENT> A.append(self) <NEW_LINE> <DEDENT> node_positions = np.array([node.position for node in A]) <NEW_LINE> distances = metric_pos(node_positions, inp) <NEW_LINE> min_ind = np.argmin(distances) <NEW_LINE> min_node = A[min_ind] <NEW_LINE> if min_node is self: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return min_node.query(inp, maxchild=maxchild, metric_pos=metric_pos) <NEW_LINE> <DEDENT> <DEDENT> def oldquery(self, inp, maxchild=5, metric_pos=norm): <NEW_LINE> <INDENT> A = self.children[:] <NEW_LINE> if self.childnum < maxchild: <NEW_LINE> <INDENT> A.append(self) <NEW_LINE> <DEDENT> mindist = np.inf <NEW_LINE> minnode = None <NEW_LINE> for node in A: <NEW_LINE> <INDENT> nodedist = metric_pos(inp, node.position) <NEW_LINE> if nodedist < mindist: <NEW_LINE> <INDENT> mindist = nodedist <NEW_LINE> minnode = node <NEW_LINE> <DEDENT> <DEDENT> if minnode == self: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return minnode.query(inp, maxchild=maxchild, metric_pos=metric_pos) <NEW_LINE> <DEDENT> <DEDENT> def train(self, y, label, labthresh=0.1, maxchild=5, metric_lab=cat_noteq, metric_pos=norm): <NEW_LINE> <INDENT> vmin = self.query(y, maxchild=maxchild, metric_pos=metric_pos) <NEW_LINE> if metric_lab(label, vmin.label) > labthresh: <NEW_LINE> <INDENT> vmin.addchild(y, label) <NEW_LINE> <DEDENT> return self | Boundary Tree.
Parameters
----------
position : np.array
Position vector of a point.
label : np.array or float
Label of a point.
children : List of BoundaryTrees, optional
List of child nodes (default []).
parent : BoundaryTree, optional
Parent node (default None). | 62599075167d2b6e312b8233 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.