function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
list
def remove(self): sys.stdout = self.stdout
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def __del__(self): self.remove()
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def write(self, x): self.stdout.write(x) traceback.print_stack()
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def flush(self): self.stdout.flush()
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def pretty(data, indent=''): """Format nested dict/list/tuple structures into a more human-readable string This function is a bit better than pprint for displaying OrderedDicts. """ ret = "" ind2 = indent + " " if isinstance(data, dict): ret = indent+"{\n" for k, v in data.items(): ret += ind2 + repr(k) + ": " + pretty(v, ind2).strip() + "\n" ret += indent+"}\n" elif isinstance(data, list) or isinstance(data, tuple): s = repr(data) if len(s) < 40: ret += indent + s else: if isinstance(data, list): d = '[]' else: d = '()' ret = indent+d[0]+"\n" for i, v in enumerate(data): ret += ind2 + str(i) + ": " + pretty(v, ind2).strip() + "\n" ret += indent+d[1]+"\n" else: ret += indent + repr(data) return ret
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def __init__(self, interval=10.0): self.interval = interval self.lock = Mutex() self._stop = False self.start()
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def start(self, interval=None): if interval is not None: self.interval = interval self._stop = False self.thread = threading.Thread(target=self.run) self.thread.daemon = True self.thread.start()
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def __init__(self, stream): self.stream = getattr(sys, stream) self.err = stream == 'stderr' setattr(sys, stream, self)
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def flush(self): with self.lock: self.stream.flush()
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def enableFaulthandler(): """ Enable faulthandler for all threads.
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def qInitResources(): QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
haskelladdict/sconcho
[ 4, 4, 4, 7, 1367596365 ]
def __init__(self, init_dict: dict = None): self._data = init_dict or dict()
132nd-etcher/EMFT
[ 3, 1, 3, 59, 1486314013 ]
def __iter__(self) -> typing.Iterator[str]: return self._data.__iter__()
132nd-etcher/EMFT
[ 3, 1, 3, 59, 1486314013 ]
def data(self) -> dict: return self._data
132nd-etcher/EMFT
[ 3, 1, 3, 59, 1486314013 ]
def __delitem__(self, key): return self._data.__delitem__(key)
132nd-etcher/EMFT
[ 3, 1, 3, 59, 1486314013 ]
def deconv(data, params, savedir='results/'): global err, old_bkg, TRACE, TRACE2, err_bk, err_sm err = old_bkg = None
COSMOGRAIL/COSMOULINE
[ 4, 3, 4, 1, 1499237614 ]
def conv(a, b): return fn.cuda_conv(plan, a, b)
COSMOGRAIL/COSMOULINE
[ 4, 3, 4, 1, 1499237614 ]
def main(argv=None): cfg = 'config.py' if argv is not None: sys.argv = argv opt, args = fn.get_args(sys.argv) MAX_IT_D = MAXPOS_STEP = MAX_IRATIO_STEP = SHOW = FORCE_INI = None if args is not None: cfg = args[0] if 's' in opt: out.level = 0 if 'v' in opt: out.level = 2 if 'd' in opt: DEBUG = True out.level = 3 out(1, '~~~ DEBUG MODE ~~~') if 'b' in opt: import prepare prepare.main(['deconv.py', '-b', cfg]) if 'e' in opt: import prepare prepare.main(['deconv.py', '-ce', cfg]) if 'i' in opt: FORCE_INI = True if 'h' in opt: out(1, 'No help page yet!') return 0 out(1, 'Begin deconvolution process')
COSMOGRAIL/COSMOULINE
[ 4, 3, 4, 1, 1499237614 ]
def setUp(self): super(CandidateFilterTests, self).setUp() self.volunteer = User.objects.create_user(username="voluntario", password=PASSWORD, is_staff=True) self.area = Area.objects.get(identifier=ESTADO_IDENTIFIER) self.election = Election.objects.create(name="Deputado Estadual") self.election.area = self.area self.election.save() self.candidate = Candidate.objects.get(id=5) self.election.candidates.add(self.candidate) self.candidate2 = Candidate.objects.get(id=4)
ciudadanointeligente/votainteligente-portal-electoral
[ 43, 34, 43, 122, 1375904659 ]
def setUp(self): super(VolunteersIndexViewWithFilterTests, self).setUp()
ciudadanointeligente/votainteligente-portal-electoral
[ 43, 34, 43, 122, 1375904659 ]
def initialize(self): # Try to get in to a corner self.forseconds(5, self.force, 50) self.forseconds(0.9, self.force, -10) self.forseconds(0.7, self.torque, 100) self.forseconds(6, self.force, 50) # Then look around and shoot stuff self.forever(self.scanfire) self._turretdirection = 1 self.turret(180) self._pingfoundrobot = None
CodingRobots/CodingRobots
[ 3, 2, 3, 1, 1329409761 ]
def get_position_display(self): return self.EntryForm.POSITIONS.get(self.get_config('position'), 'N/A')
sfu-fas/coursys
[ 61, 17, 61, 39, 1407368110 ]
def default_title(cls): return 'Admin Position'
sfu-fas/coursys
[ 61, 17, 61, 39, 1407368110 ]
def load_initial_data(apps, schema_editor): Grade = apps.get_model('courses', 'Grade') # add some initial data if none has been created yet if not Grade.objects.exists(): Grade.objects.create( name="8", value=8 ) Grade.objects.create( name="9", value=9 ) Grade.objects.create( name="10", value=10 ) Grade.objects.create( name="11", value=11 ) Grade.objects.create( name="12", value=12 )
timberline-secondary/hackerspace
[ 13, 18, 13, 234, 1436242433 ]
def configure_workers(*args, **kwargs): import django django.setup()
tjm-1990/blueking
[ 1, 1, 1, 1, 1489313552 ]
def sizeof_fmt(num): for x in ['bytes','KB','MB','GB','TB']: if num < 1024.0: return "%3.1f%s" % (num, x) num /= 1024.0
odie5533/Python-RTSP
[ 64, 24, 64, 1, 1312799837 ]
def rn5_auth(username, realm, password, nonce, uuid): MUNGE_TEMPLATE ='%-.200s%-.200s%-.200sCopyright (C) 1995,1996,1997 RealNetworks, Inc.' authstr ="%-.200s:%-.200s:%-.200s" % (username, realm, password) first_pass = hashlib.md5(authstr).hexdigest()
odie5533/Python-RTSP
[ 64, 24, 64, 1, 1312799837 ]
def AV_WB32(d): """ Used by RealChallenge() """ d = d.decode('hex') return list(struct.unpack('%sB' % len(d), d))
odie5533/Python-RTSP
[ 64, 24, 64, 1, 1312799837 ]
def select_mlti_data(self, mlti_chunk, selection): """ Takes a MLTI-chunk from an SDP OpaqueData and a rule selection Returns the codec data based on the given rule selection """ if not mlti_chunk.startswith('MLTI'): print('MLTI tag missing') return mlti_chunk idx = 4 # past 'MLTI' numrules = struct.unpack('!H', mlti_chunk[idx:idx + 2])[0] idx += 2 rules = [] for i in range(0, numrules): rules.append(struct.unpack('!H', mlti_chunk[idx:idx + 2])[0]) idx += 2 if selection > numrules: return 0 numcodecs = struct.unpack('!H', mlti_chunk[idx:idx + 2])[0] idx += 2 codecs = [] for i in range(numcodecs): codec_length = struct.unpack('!I', mlti_chunk[idx:idx + 4])[0] idx += 4 # skip over codec length integer codecs.append(mlti_chunk[idx:idx + codec_length]) idx += codec_length # skip over codec length worth of data return codecs[rules[selection]]
odie5533/Python-RTSP
[ 64, 24, 64, 1, 1312799837 ]
def handleEndHeaders(self, headers): if headers.get('realchallenge1'): self.realchallenge1 = headers['realchallenge1'][0] elif headers.get('www-authenticate', [''])[0].startswith('RN5'): ##hack: resent describe header with auth self.sent_describe = False print 'RN5 Authendication' self.rn5_authdata ={} for authdate in headers['www-authenticate'][0][3:].split(','): key, value = authdate.split('=') ##remove " self.rn5_authdata[key.strip()] = value[1:-1]
odie5533/Python-RTSP
[ 64, 24, 64, 1, 1312799837 ]
def handleSdp(self, data): """ Called with SDP Response data Uses the SDP response to construct the file header """ sdp = Sdpplin(data) header = rmff_header_t() try: abstract = sdp['Abstract'] except KeyError: abstract = '' header.fileheader = rmff_fileheader_t(4 + sdp['StreamCount']) try: title = sdp['Title'] except KeyError: title = '' try: author = sdp['Author'] except KeyError: author = '' try: copyright = sdp['Copyright'] except KeyError: copyright = '' header.cont = rmff_cont_t(title, author, copyright, abstract) header.data = rmff_data_t(0, 0)
odie5533/Python-RTSP
[ 64, 24, 64, 1, 1312799837 ]
def heartbeat(self): target = '%s://%s:%s' % (self.factory.scheme, self.factory.host, self.factory.port) headers = {} headers['User-Agent'] = self.factory.agent headers['PlayerStarttime'] = self.factory.PLAYER_START_TIME headers['CompanyID'] = self.factory.companyID headers['GUID'] = self.factory.GUID headers['RegionData'] = '0' headers['ClientID'] = self.factory.clientID headers['Pragma'] = 'initiate-session' self.sendOptions('*', headers) reactor.callLater(30, self.heartbeat)
odie5533/Python-RTSP
[ 64, 24, 64, 1, 1312799837 ]
def handleContentResponse(self, data, content_type): """ Called when the entire content-length has been received Exepect to receive type application/sdp """ f = open('sdp.txt', 'w') f.write(data) f.close() if content_type == 'application/sdp': reactor.callLater(30, self.heartbeat) self.out_file = open(self.factory.filename, 'wb') self.header = self.handleSdp(data) self.streamids = [i for i in range(self.header.prop.num_streams)] self.subscribe = '' for i,rules in self.streammatches.items(): for r in rules: self.subscribe += 'stream=%s;rule=%s,' % (i,r) self.subscribe = self.subscribe[:-1] # Removes trailing comma self.out_file.write(self.header.dump()) self.num_packets = 0 self.data_size = 0
odie5533/Python-RTSP
[ 64, 24, 64, 1, 1312799837 ]
def handleRDTData(self, data, rmff_ph): self.num_packets += 1 self.data_size += len(data) rmff_str = str(rmff_ph) self.data_size += len(rmff_str) self.out_file.write(rmff_str) self.out_file.write(data)
odie5533/Python-RTSP
[ 64, 24, 64, 1, 1312799837 ]
def handleStreamEnd(self): self.header.prop.num_packets = self.num_packets self.header.data.num_packets = self.num_packets self.header.data.size += self.data_size if self.out_file: self.out_file.seek(0) self.out_file.write(self.header.dump()) self.out_file.close() self.factory.success(0)
odie5533/Python-RTSP
[ 64, 24, 64, 1, 1312799837 ]
def handleRDTPacket(self, data): """ Called with a full RDT data packet """ header, data = data[:10], data[10:] packet_flags = struct.unpack('B', header[0])[0]
odie5533/Python-RTSP
[ 64, 24, 64, 1, 1312799837 ]
def handleInterleavedData(self, data): """ Called when an interleaved data frame is received """ self.data_received += len(data) self.factory.data_received = self.data_received
odie5533/Python-RTSP
[ 64, 24, 64, 1, 1312799837 ]
def _sendOptions(self, headers={}): target = '%s://%s:%s' % (self.factory.scheme, self.factory.host, self.factory.port) headers['User-Agent'] = self.factory.agent headers['ClientChallenge'] = self.factory.CLIENT_CHALLENGE headers['PlayerStarttime'] = self.factory.PLAYER_START_TIME headers['CompanyID'] = self.factory.companyID headers['GUID'] = self.factory.GUID headers['RegionData'] = '0' headers['ClientID'] = self.factory.clientID headers['Pragma'] = 'initiate-session' self.sendOptions(target, headers)
odie5533/Python-RTSP
[ 64, 24, 64, 1, 1312799837 ]
def _sendDescribe(self, headers={}): target = '%s://%s:%s%s' % (self.factory.scheme, self.factory.host, self.factory.port, self.factory.path) headers['Accept'] = 'application/sdp'
odie5533/Python-RTSP
[ 64, 24, 64, 1, 1312799837 ]
def _sendSetup(self, headers={}, streamid=0): target = '%s://%s:%s%s/streamid=%s' % (self.factory.scheme, self.factory.host, self.factory.port, self.factory.path, streamid) headers['If-Match'] = self.session headers['Transport'] = 'x-pn-tng/tcp;mode=play,rtp/avp/tcp;unicast;mode=play' self.sendSetup(target, headers)
odie5533/Python-RTSP
[ 64, 24, 64, 1, 1312799837 ]
def _sendSetParameter(self, key, value, headers=None): target = '%s://%s:%s%s' % (self.factory.scheme, self.factory.host, self.factory.port, self.factory.path) if headers is None: headers = {} headers['Session'] = self.session headers[key] = value self.sendSetParameter(target, headers)
odie5533/Python-RTSP
[ 64, 24, 64, 1, 1312799837 ]
def _sendPlay(self, range='0-', headers={}): target = '%s://%s:%s%s' % (self.factory.scheme, self.factory.host, self.factory.port, self.factory.path) if self.session: headers['Session'] = self.session self.sendPlay(range, target, headers)
odie5533/Python-RTSP
[ 64, 24, 64, 1, 1312799837 ]
def sendNextMessage(self): """ This method goes in order sending messages to the server: OPTIONS, DESCRIBE, SETUP, SET_PARAMETER, SET_PARAMETER, PLAY Returns True if it sent a packet, False if it didn't """ if not self.sent_options: self.sent_options = True self._sendOptions() return True if not self.sent_describe: print 'sending describe' self.sent_describe = True self._sendDescribe() return True if len(self.streamids) > len(self.setup_streamids): headers = {} if not self.sent_realchallenge2: self.sent_realchallenge2 = True challenge_tuple = RealChallenge.compute(self.realchallenge1) headers['RealChallenge2'] = '%s, sd=%s' % challenge_tuple # Gets a streamid that hasn't been setup yet s = [s for s in self.streamids if s not in self.setup_streamids][0] self.setup_streamids.append(s) self._sendSetup(streamid=s, headers=headers) return True if not self.sent_parameter: self.sent_parameter = True self._sendSetParameter('Subscribe', self.subscribe) return True if not self.sent_bandwidth: self.sent_bandwidth = True self._sendSetParameter('SetDeliveryBandwidth', 'Bandwidth=%s;BackOff=0' % self.factory.bandwidth) return True if not self.sent_play: self.sent_play = True self._sendPlay() return True return False
odie5533/Python-RTSP
[ 64, 24, 64, 1, 1312799837 ]
def success(result): if result == 0: print('Success!') else: print('Result: %s' % result) reactor.stop()
odie5533/Python-RTSP
[ 64, 24, 64, 1, 1312799837 ]
def error(failure): print('Failure!: %s' % failure.getErrorMessage()) reactor.stop()
odie5533/Python-RTSP
[ 64, 24, 64, 1, 1312799837 ]
def progress(factory): print('Downloaded %s' % sizeof_fmt(factory.data_received)) reactor.callLater(1, progress, factory)
odie5533/Python-RTSP
[ 64, 24, 64, 1, 1312799837 ]
def __init__(self): self._recipe_actions = {} self._recipe_resources = {} self._recipes = {} reg = ComponentRegistry() for name, action in reg.load_extensions('iotile.recipe_action', product_name='build_step'): self._recipe_actions[name] = action for name, resource in reg.load_extensions('iotile.recipe_resource', product_name='build_resource'): self._recipe_resources[name] = resource
iotile/coretools
[ 13, 7, 13, 230, 1479861690 ]
def is_valid_recipe(self, recipe_name): """Check if a recipe is known and valid. Args: name (str): The name of the recipe to check Returns: bool: Whether the recipe is known and valid. """ return self._recipes.get(recipe_name, None) is not None
iotile/coretools
[ 13, 7, 13, 230, 1479861690 ]
def add_recipe_actions(self, recipe_actions): """Add additional valid recipe actions to RecipeManager args: recipe_actions (list): List of tuples. First value of tuple is the classname, second value of tuple is RecipeAction Object """ for action_name, action in recipe_actions: self._recipe_actions[action_name] = action
iotile/coretools
[ 13, 7, 13, 230, 1479861690 ]
def main_wf(current): current.task_data['from_main'] = True current.output['from_jumped'] = current.task_data.get('from_jumped') assert current.workflow.name == 'jump_to_wf'
zetaops/zengine
[ 82, 22, 82, 36, 1424353885 ]
def parse(self, field, data): try: return dbfread.FieldParser.parse(self, field, data) except ValueError: return data
bobintetley/asm3
[ 82, 55, 82, 201, 1479217555 ]
def gettype(animaldes): spmap = { "DOG": 2, "CAT": 11 } species = animaldes.split(" ")[0] if species in spmap: return spmap[species] else: return 2
bobintetley/asm3
[ 82, 55, 82, 201, 1479217555 ]
def getsize(size): if size == "VERY": return 0 elif size == "LARGE": return 1 elif size == "MEDIUM": return 2 else: return 3
bobintetley/asm3
[ 82, 55, 82, 201, 1479217555 ]
def __init__(self, hostname='127.0.0.1', port=7362): self.platform = sys.platform self.hostname = hostname self.port = int(port) if self.platform not in ['linux', 'win32', 'darwin']: raise Exception('You\'re probably using an OS that is unsupported. Sorry about that. I take pull requests.') self.client = xmlrpc.client.ServerProxy('http://{}:{}/'.format(self.hostname, self.port)) self.process = None
KM4YRI/pyFldigi
[ 26, 8, 26, 2, 1485615983 ]
def stop(self, save_options=True, save_log=True, save_macros=True, force=True): """Attempts to gracefully shut down fldigi. Returns the error code. :Example: >>> import pyfldigi >>> app = pyfldigi.ApplicationMonitor() >>> app.start() >>> time.sleep(10) # wait a bit >>> app.stop() """ bitmask = int('0b{}{}{}'.format(int(save_macros), int(save_log), int(save_options)), 0) self.client.fldigi.terminate(bitmask) if self.process is not None: error_code = self.process.wait(timeout=2) if force is True: if error_code is None: self.process.terminate() # attempt to terminate error_code = self.process.wait(timeout=2) if error_code is None: error_code = self.process.kill() self.process = None return error_code
KM4YRI/pyFldigi
[ 26, 8, 26, 2, 1485615983 ]
def _get_path(self): if self.platform == 'win32': # Below is a clever way to return a list of fldigi versions. This would fail if the user # did not install fldigi into Program Files. fldigi_versions = [d for d in os.listdir(os.environ["ProgramFiles(x86)"]) if 'fldigi' in d.lower()] if len(fldigi_versions) == 0: raise FileNotFoundError('Cannot find the path to fldigi. Is it installed?') elif len(fldigi_versions) == 1: path = os.path.join(os.environ["ProgramFiles(x86)"], fldigi_versions[0]) # Check to see if fldigi.exe is in the folder if 'fldigi.exe' in os.listdir(path): return os.path.join(path, 'fldigi.exe') else: raise Exception('Found more than one version of fldigi. Uninstall one.') else: # Assume all other OS's are smart enough to place fldigi in PATH return 'fldigi'
KM4YRI/pyFldigi
[ 26, 8, 26, 2, 1485615983 ]
def __init__(self, podcasts): if not podcasts or (None in podcasts): raise ValueError("podcasts must not be None") self.podcasts = podcasts
gpodder/mygpo
[ 236, 79, 236, 145, 1304023928 ]
def __init__(self): super().__init__("Delete ranking and all cache data and ranking data linked to it, used for broken " "rankings.", pid_file=True, stoppable=False) self.add_argument('--delete', dest="delete", action='store_true', default=False, help="If this is not set, deletes a dry run will be performed instead.") self.add_argument('--keep-rankings', '-r', dest="keep_rankings", default=None, help="Comma separated list of rankings to keep.")
andersroos/rankedftw
[ 61, 6, 61, 14, 1480368416 ]
def run(self, args, logger):
andersroos/rankedftw
[ 61, 6, 61, 14, 1480368416 ]
def _compute_mean(C, g, ctx): """ Compute mean according to equation 8a, page 773. """ mag = ctx.mag dis = ctx.rrup # computing r02 parameter and the average distance to the fault surface ro2 = 1.4447e-5 * np.exp(2.3026 * mag) avg = np.sqrt(dis ** 2 + ro2) # computing fourth term of Eq. 8a, page 773. trm4 = (exp1(C['c4'] * dis) - exp1(C['c4'] * avg)) / ro2 # computing the mean mean = C['c1'] + C['c2'] * mag + C['c3'] * np.log(trm4) # convert from cm/s**2 to 'g' mean = np.log(np.exp(mean) * 1e-2 / g) return mean
gem/oq-engine
[ 291, 241, 291, 48, 1277737182 ]
def compute(self, ctx: np.recarray, imts, mean, sig, tau, phi): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.compute>` for spec of input and result values. """ for m, imt in enumerate(imts): C = self.COEFFS[imt] mean[m] = _compute_mean(C, g, ctx) sig[m], tau[m], phi[m] = _get_stddevs(C)
gem/oq-engine
[ 291, 241, 291, 48, 1277737182 ]
def mainclues(self): return self.clues.filter(main=True)
wadobo/socializa
[ 4, 2, 4, 2, 1472891819 ]
def get_desc_html(self): # search #[NUM][solution] and return [('NUM', 'solution'), ... ] qregex = re.compile("#\[[\d]+\]\[([^#]*)\]") desc_html = self.desc[:] for sre in qregex.finditer(self.desc): ini_pos, end_pos = sre.span() rex = self.desc[ini_pos:end_pos] solution = sre.group(1) desc_html = desc_html.replace(rex, "<b>{}</b>".format(solution)) return desc_html
wadobo/socializa
[ 4, 2, 4, 2, 1472891819 ]
def get_desc_html(self): # search #[NUM][type][question] and return [('NUM', 'type', 'question'), ... ] qregex = re.compile("#\[[\d]+\]\[(?:option|text)\]\[([^#]*)\]") desc_html = self.desc[:] for sre in qregex.finditer(self.desc): ini_pos, end_pos = sre.span() rex = self.desc[ini_pos:end_pos] question = sre.group(1) desc_html = desc_html.replace(rex, "<b>{}</b>".format(question)) return desc_html
wadobo/socializa
[ 4, 2, 4, 2, 1472891819 ]
def setUp(self): super().setUp() self.user = UserFactory(is_staff=True, is_superuser=True) self.client.login(username=self.user.username, password=USER_PASSWORD)
edx/course-discovery
[ 51, 133, 51, 43, 1447102674 ]
def test_list(self): """ Verify the endpoint returns a list of all program types. """ LevelTypeFactory.create_batch(4) expected = LevelType.objects.all() with self.assertNumQueries(6): response = self.client.get(self.list_path) assert response.status_code == 200 assert response.data['results'] == self.serialize_level_type(expected, many=True)
edx/course-discovery
[ 51, 133, 51, 43, 1447102674 ]
def __init__(self): Telecommand.__init__(self)
PW-Sat2/PWSat2OBC
[ 53, 9, 53, 2, 1444677850 ]
def apid(self): return 0x27
PW-Sat2/PWSat2OBC
[ 53, 9, 53, 2, 1444677850 ]
def __init__(self, cr, uid, name, context): super(doctor_disability, self).__init__(cr, uid, name, context=context) self.localcontext.update({ 'time': time, 'select_type': self.select_type, 'select_age': self.select_age, 'select_diseases': self.select_diseases, 'select_diseases_type': self.select_diseases_type, 'return_street_home': self.return_street_home, 'return_number_phone': self.return_number_phone, 'return_sex': self.return_sex })
hivam/l10n_co_doctor
[ 2, 3, 2, 3, 1403128853 ]
def return_number_phone(self, phone, mobile): return_phone = "" if phone: return_phone += phone + " - " if mobile: return_phone += mobile + " - " return return_phone[:len(return_phone)-2]
hivam/l10n_co_doctor
[ 2, 3, 2, 3, 1403128853 ]
def select_type(self, tipo_usuario): if tipo_usuario: tipo = self.pool.get('doctor.tipousuario.regimen').browse(self.cr, self.uid, tipo_usuario).name else: tipo= None return tipo
hivam/l10n_co_doctor
[ 2, 3, 2, 3, 1403128853 ]
def select_diseases(self, status): if status== 'presumptive': return "Impresión Diagnóstica" if status== 'confirm': return "Confirmado" if status== 'recurrent': return "Recurrente" return ""
hivam/l10n_co_doctor
[ 2, 3, 2, 3, 1403128853 ]
def authenticate(self, request, username=None, password=None, **kwargs): UserModel = get_user_model() case_sensitive = UserModel.objects.filter(Q(username__exact=username) | Q(email__iexact=username)).distinct() case_insensitive = UserModel.objects.filter(Q(username__iexact=username) | Q(email__iexact=username)).distinct() user = None if case_sensitive.exists(): user = case_sensitive.first() elif case_insensitive.exists(): count = case_insensitive.count() if count == 1: user = case_insensitive.first() if user and user.check_password(password): return user return None
astrobin/astrobin
[ 90, 26, 90, 17, 1510218687 ]
def get_recent_posts(num=9): return Post.objects.all().order_by('-modified_time')[:num]
RewrZ/RewrZ
[ 3, 3, 3, 8, 1507722014 ]
def archives(): return Post.objects.dates('created_time', 'month', order='DESC')
RewrZ/RewrZ
[ 3, 3, 3, 8, 1507722014 ]
def get_categories(): return Category.objects.annotate(num_posts=Count('post')).filter(num_posts__gt=0)
RewrZ/RewrZ
[ 3, 3, 3, 8, 1507722014 ]
def get_price_available(self, order): self.ensure_one() category_price = 0.0 price_dict = self.get_price_dict(order) for line in self.price_rule_ids: if line.product_category_id: products = order.mapped('order_line.product_id') test = any(product.categ_id == line.product_category_id for product in products) if test: category_price = line.product_category_price break else: test = safe_eval( line.variable + line.operator + str(line.max_value), price_dict) if test: break if category_price: return category_price # Note that this will evaluate all the price_rule_ids again and # our category rules might interfere withthe correct computation return super(DeliveryCarrier, self).get_price_available(order)
OCA/carrier-delivery
[ 92, 288, 92, 24, 1402934179 ]
def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column( "comment", sa.Column( "replies", postgresql.JSONB(astext_type=sa.Text()), nullable=True ), ) # ### end Alembic commands ###
cgwire/zou
[ 145, 88, 145, 11, 1490485144 ]
def find_elements(self): for el in self.el[0].get(self.item_xpath): yield el
frankrousseau/weboob
[ 4, 3, 4, 1, 1381825736 ]
def next_page(self): js_datas = CleanText('//div[@id="js-data"]/@data-rest-search-request')(self) total_page = self.page.browser.get_total_page(js_datas.split('?')[-1]) m = re.match(".*page=(\d?)(?:&.*)?", self.page.url) if m: current_page = int(m.group(1)) next_page = current_page + 1 if next_page <= total_page: return self.page.url.replace('page=%d' % current_page, 'page=%d' % next_page)
frankrousseau/weboob
[ 4, 3, 4, 1, 1381825736 ]
def obj_phone(self): phone = CleanText('./div/div/ul/li/span[@class="js-clickphone"]', replace=[(u'Téléphoner : ', u'')], default=NotAvailable)(self) if '...' in phone: return NotLoaded return phone
frankrousseau/weboob
[ 4, 3, 4, 1, 1381825736 ]
def filter(self, el): return Decimal(el)
frankrousseau/weboob
[ 4, 3, 4, 1, 1381825736 ]
def filter(self, el): return datetime.fromtimestamp(el / 1000.0)
frankrousseau/weboob
[ 4, 3, 4, 1, 1381825736 ]
def get_phone(self): return self.doc.get('phoneNumber')
frankrousseau/weboob
[ 4, 3, 4, 1, 1381825736 ]
def obj_photos(self): photos = [] for img in Dict('characteristics/images')(self): m = re.search('http://thbr\.figarocms\.net.*(http://.*)', img) if m: photos.append(HousingPhoto(m.group(1))) return photos
frankrousseau/weboob
[ 4, 3, 4, 1, 1381825736 ]
def get_total_page(self): return self.doc.get('pagination').get('total')
frankrousseau/weboob
[ 4, 3, 4, 1, 1381825736 ]
def obj_photos(self): photos = [] for img in XPath('//a[@class="thumbnail-link"]/img[@itemprop="image"]')(self): url = Regexp(CleanText('./@src'), 'http://thbr\.figarocms\.net.*(http://.*)')(img) photos.append(HousingPhoto(url)) return photos
frankrousseau/weboob
[ 4, 3, 4, 1, 1381825736 ]
def setUp(self): super(AccountInvoiceLineTestBase, self).setUp() self.model = 'carepoint.account.invoice.line' self.mock_env = self.get_carepoint_helper( self.model )
laslabs/odoo-connector-carepoint
[ 1, 1, 1, 2, 1449883667 ]
def record(self): """ Model record fixture """ return { 'rxdisp_id': 12345, 'primary_pay_date': '2016-01-23 01:23:45', 't_patient_pay_sub': '10.23', }
laslabs/odoo-connector-carepoint
[ 1, 1, 1, 2, 1449883667 ]
def setUp(self): super(TestAccountInvoiceLineUnit, self).setUp() self.Unit = account_invoice_line.AccountInvoiceLineUnit self.unit = self.Unit(self.mock_env)
laslabs/odoo-connector-carepoint
[ 1, 1, 1, 2, 1449883667 ]
def test_import_invoice_lines_for_procurement_unit_for_importer(self): """ It should get unit for importer """ with mock.patch.object(self.unit, 'unit_for') as mk: mk.side_effect = [None, EndTestException] with self.assertRaises(EndTestException): self.unit._import_invoice_lines_for_procurement(True) mk.assert_called_with( account_invoice_line.AccountInvoiceLineImporter )
laslabs/odoo-connector-carepoint
[ 1, 1, 1, 2, 1449883667 ]
def test_import_invoice_lines_for_procurement_imports(self): """ It should run importer on records """ with mock.patch.object(self.unit, 'unit_for') as mk: expect = mock.MagicMock() adapter = mock.MagicMock() adapter.search.return_value = [True] mk.side_effect = [adapter, expect] expect.run.side_effect = EndTestException with self.assertRaises(EndTestException): self.unit._import_invoice_lines_for_procurement(True) expect.run.assert_called_once_with( adapter.search()[0] )
laslabs/odoo-connector-carepoint
[ 1, 1, 1, 2, 1449883667 ]
def setUp(self): super(TestAccountInvoiceLineImportMapper, self).setUp() self.Unit = account_invoice_line.AccountInvoiceLineImportMapper self.unit = self.Unit(self.mock_env)
laslabs/odoo-connector-carepoint
[ 1, 1, 1, 2, 1449883667 ]
def test_invoice_id_get_binder(self): """ It should get binder for record type """ with mock.patch.object(self.unit, 'binder_for'): self.unit.binder_for.side_effect = EndTestException with self.assertRaises(EndTestException): self.unit.invoice_id(self.record) self.unit.binder_for.assert_called_once_with( 'carepoint.procurement.order' )
laslabs/odoo-connector-carepoint
[ 1, 1, 1, 2, 1449883667 ]
def test_invoice_id_search(self): """ It should search for invoice from origin """ with mock.patch.object(self.unit, 'binder_for'): with mock.patch.object(self.unit.session, 'env') as env: env['account.invoice'].search.side_effect = EndTestException proc_id = self.unit.binder_for().to_odoo() with self.assertRaises(EndTestException): self.unit.invoice_id(self.record) env['account.invoice'].search.assert_called_once_with( [('origin', '=', proc_id.sale_line_id.order_id.name)], limit=1, )
laslabs/odoo-connector-carepoint
[ 1, 1, 1, 2, 1449883667 ]
def test_invoice_id_new_invoice_prepare_invoice(self): """ It should prepare invoice from sale order if not existing """ with mock.patch.object(self.unit, 'binder_for') as mk: with mock.patch.object(self.unit.session, 'env') as env: env['account.invoice'].search.return_value = [] prep = mk().to_odoo().sale_line_id.order_id._prepare_invoice prep.side_effect = EndTestException with self.assertRaises(EndTestException): self.unit.invoice_id(self.record)
laslabs/odoo-connector-carepoint
[ 1, 1, 1, 2, 1449883667 ]
def test_invoice_id_new_invoice_create(self): """ It should create invoice with proper vals """ with mock.patch.object(self.unit, 'binder_for') as mk: with mock.patch.object(self.unit.session, 'env') as env: env['account.invoice'].search.return_value = [] prep = mk().to_odoo().sale_line_id.order_id._prepare_invoice self.unit.invoice_id(self.record) env['account.invoice'].create.assert_called_once_with(prep())
laslabs/odoo-connector-carepoint
[ 1, 1, 1, 2, 1449883667 ]
def test_sale_line_ids_get_binder(self): """ It should get binder for record type """ with mock.patch.object(self.unit, 'binder_for'): self.unit.binder_for.side_effect = EndTestException with self.assertRaises(EndTestException): self.unit.sale_line_ids(self.record) self.unit.binder_for.assert_called_once_with( 'carepoint.procurement.order' )
laslabs/odoo-connector-carepoint
[ 1, 1, 1, 2, 1449883667 ]
def test_sale_line_ids_return(self): """ It should return proper values dict """ with mock.patch.object(self.unit, 'binder_for') as mk: res = self.unit.sale_line_ids(self.record) expect = { 'sale_line_ids': [(6, 0, [mk().to_odoo().sale_line_id.id])] } self.assertDictEqual(expect, res)
laslabs/odoo-connector-carepoint
[ 1, 1, 1, 2, 1449883667 ]
def test_invoice_line_data_to_odoo(self): """ It should get Odoo record for binding """ with mock.patch.object(self.unit, 'binder_for'): self.unit.binder_for().to_odoo.side_effect = EndTestException with self.assertRaises(EndTestException): self.unit.invoice_line_data(self.record) self.unit.binder_for().to_odoo.assert_called_once_with( self.record['rxdisp_id'], browse=True, )
laslabs/odoo-connector-carepoint
[ 1, 1, 1, 2, 1449883667 ]