function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
sequence
def get_channels_links(self): pages = self.get_channels_pages() items = thread_pool(self.get_channels_page_links, pages) return items
jonian/kickoff-player
[ 40, 10, 40, 3, 1473685315 ]
def get_channels(self): links = self.get_channels_links() items = thread_pool(self.get_channel_details, links) return items
jonian/kickoff-player
[ 40, 10, 40, 3, 1473685315 ]
def get_events_page(self): data = self.get() page = None if data is not None: link = data.xpath('//div[@id="system"]//a[starts-with(@href, "/live-football")]') page = link[0].get('href') if len(link) else None return page
jonian/kickoff-player
[ 40, 10, 40, 3, 1473685315 ]
def get_event_channels(self, url): data = self.get(url=url, ttl=60) items = [] if data is None: return items try: root = data.xpath('//div[@id="system"]//table')[0] comp = root.xpath('.//td[text()="Competition"]//following-sibling::td[1]')[0] team = root.xpath('.//td[text()="Match"]//following-sibling::td[1]')[0] comp = comp.text_content().strip() team = team.text_content().strip().split('-') home = team[0].strip() away = team[1].strip() event = { 'competition': comp, 'home': home, 'away': away } chann = [] for link in data.xpath('//div[@id="system"]//a[contains(@href, "/channels/")]'): name = link.text_content() name = self.parse_name(name) chann.append(name) if chann: items.append({ 'event': event, 'channels': chann }) except (IndexError, ValueError): pass return items
jonian/kickoff-player
[ 40, 10, 40, 3, 1473685315 ]
def save_events(self): fixtures = self.data.load_fixtures(today_only=True) events = self.get_events() items = [] for fixture in fixtures: channels = self.get_fixture_channels(events, fixture) streams = self.data.get_multiple('stream', 'channel', channels) for stream in streams: items.append({ 'fs_id': "%s_%s" % (fixture.id, stream.id), 'fixture': fixture.id, 'stream': stream }) self.data.set_multiple('event', items, 'fs_id')
jonian/kickoff-player
[ 40, 10, 40, 3, 1473685315 ]
def __init__(self, p_args, p_todolist, # pragma: no branch p_out=lambda a: None, p_err=lambda a: None, p_prompt=lambda a: None): super().__init__( p_args, p_todolist, p_out, p_err, p_prompt) self.text = ' '.join(p_args) self.from_file = None
bram85/topydo
[ 653, 78, 653, 61, 1413726583 ]
def get_todos_from_file(self): if self.from_file == '-': f = stdin else: f = codecs.open(self.from_file, 'r', encoding='utf-8') todos = f.read().splitlines() return todos
bram85/topydo
[ 653, 78, 653, 61, 1413726583 ]
def _preprocess_input_todo(p_todo_text): """ Pre-processes user input when adding a task. It detects a priority mid-sentence and puts it at the start. """ todo_text = re.sub(r'^(.+) (\([A-Z]\))(.*)$', r'\2 \1\3', p_todo_text) return todo_text
bram85/topydo
[ 653, 78, 653, 61, 1413726583 ]
def execute(self): """ Adds a todo item to the list. """ if not super().execute(): return False self.printer.add_filter(PrettyPrinterNumbers(self.todolist)) self._process_flags() if self.from_file: try: new_todos = self.get_todos_from_file() for todo in new_todos: self._add_todo(todo) except (IOError, OSError): self.error('File not found: ' + self.from_file) else: if self.text: self._add_todo(self.text) else: self.error(self.usage())
bram85/topydo
[ 653, 78, 653, 61, 1413726583 ]
def help(self): return """\
bram85/topydo
[ 653, 78, 653, 61, 1413726583 ]
def _delay_property(self, delay=None): """ return delay value for current item """ if delay is not None: self.__delay = delay return self.__delay
kierse/mediarover
[ 11, 1, 11, 25, 1241391953 ]
def source(self): return NZBMATRIX
kierse/mediarover
[ 11, 1, 11, 25, 1241391953 ]
def __init__(self, filename): self.filename = filename self.conn = sqlite3.connect(filename) self.conn.row_factory = sqlite3.Row self.queue = {}
FoldingAtHome/fah-control
[ 121, 45, 121, 32, 1364520553 ]
def get_version(self): return 6
FoldingAtHome/fah-control
[ 121, 45, 121, 32, 1364520553 ]
def set_current_version(self, version): self.write('PRAGMA user_version=%d' % version, True)
FoldingAtHome/fah-control
[ 121, 45, 121, 32, 1364520553 ]
def clear(self, name, commit = True): self.delete('config', name = name) if commit: self.commit()
FoldingAtHome/fah-control
[ 121, 45, 121, 32, 1364520553 ]
def has(self, name): return self.get(name) != None
FoldingAtHome/fah-control
[ 121, 45, 121, 32, 1364520553 ]
def flush_queued(self): if len(self.queue) == 0: return for name, value in self.queue.items(): self.set(name, value, commit = False) self.commit() self.queue.clear()
FoldingAtHome/fah-control
[ 121, 45, 121, 32, 1364520553 ]
def execute_one(self, sql): c = self.execute(sql) result = c.fetchone() c.close() return result
FoldingAtHome/fah-control
[ 121, 45, 121, 32, 1364520553 ]
def commit(self): self.conn.commit()
FoldingAtHome/fah-control
[ 121, 45, 121, 32, 1364520553 ]
def insert(self, table, **kwargs): self.get_table(table).insert(self, **kwargs)
FoldingAtHome/fah-control
[ 121, 45, 121, 32, 1364520553 ]
def select(self, table, cols = None, **kwargs): return self.get_table(table).select(self, cols, **kwargs)
FoldingAtHome/fah-control
[ 121, 45, 121, 32, 1364520553 ]
def __init__(self, parent_server, poll_interval): """ Initialize the class. :param parent_server: the TwistedServer instance that started this :type parent_server: :py:class:`~.TwistedServer` :param poll_interval: interval in seconds to poll MumbleLink :type poll_interval: float """ logger.debug("Instantiating WineMumbleLinkReader") self.server = parent_server self._poll_interval = poll_interval self._wine_protocol = None self._wine_process = None self._looping_deferred = None self._setup_process() self._add_update_loop()
jantman/gw2copilot
[ 5, 1, 5, 8, 1477907358 ]
def _setup_process(self): """ Setup and spawn the process to read MumbleLink. """ logger.debug("Creating WineProcessProtocol") self._wine_protocol = WineProcessProtocol(self.server) logger.debug("Finding process executable, args and environ") executable, args, env = self._gw2_wine_spawn_info # this seems to cause problems if 'WINESERVERSOCKET' in env: del env['WINESERVERSOCKET'] logger.debug( "Creating spawned process; executable=%s args=%s len(env)=%d", executable, args, len(env) ) logger.debug("Process environment:") for k in sorted(env.keys()): logger.debug('%s=%s' % (k, env[k])) self._wine_process = self.server.reactor.spawnProcess( self._wine_protocol, executable, args, env)
jantman/gw2copilot
[ 5, 1, 5, 8, 1477907358 ]
def _gw2_wine_spawn_info(self): """ Return the information required to spawn :py:mod:`~.read_mumble_link` as a Python script running under GW2's wine install. :return: return a 3-tuple of wine executable path (str), args to pass to wine (list, wine python binary path and ``read_mumble_link.py`` module path), wine process environment (dict) :rtype: tuple """ gw2_ps = self._gw2_process env = gw2_ps.environ() wine_path = os.path.join(os.path.dirname(gw2_ps.exe()), 'wine') logger.debug("Gw2.exe executable: %s; inferred wine binary as: %s", gw2_ps.exe(), wine_path) wine_args = [ wine_path, self._wine_python_path(env['WINEPREFIX']), self._read_mumble_path, '-i' ] return wine_path, wine_args, env
jantman/gw2copilot
[ 5, 1, 5, 8, 1477907358 ]
def _read_mumble_path(self): """ Return the absolute path to :py:mod:`~.read_mumble_link` on disk. :return: absolute path to :py:mod:`~.read_mumble_link` :rtype: str """ p = pkg_resources.resource_filename('gw2copilot', 'read_mumble_link.py') p = os.path.abspath(os.path.realpath(p)) logger.debug('Found path to read_mumble_link as: %s', p) return p
jantman/gw2copilot
[ 5, 1, 5, 8, 1477907358 ]
def _gw2_process(self): """ Find the Gw2.exe process; return the Process object. :return: Gw2.exe process :rtype: psutil.Process """ gw2_p = None for p in psutil.process_iter(): if p.name() != 'Gw2.exe': continue if gw2_p is not None: raise Exception("Error: more than one Gw2.exe process found") gw2_p = p if gw2_p is None: raise Exception("Error: could not find a running Gw2.exe process") logger.debug("Found Gw2.exe process, PID %d", gw2_p.pid) return gw2_p
jantman/gw2copilot
[ 5, 1, 5, 8, 1477907358 ]
def __init__(self, parent_server): """ Initialize; save an instance variable pointing to our :py:class:`~.TwistedServer` :param parent_server: the TwistedServer instance that started this :type parent_server: :py:class:`~.TwistedServer` """ logger.debug("Initializing WineProcessProtocol") self.parent_server = parent_server self.have_data = False
jantman/gw2copilot
[ 5, 1, 5, 8, 1477907358 ]
def ask_for_output(self): """ Write a newline to the process' STDIN, prompting it to re-read the map and write the results to STDOUT, which will be received by :py:meth:`~.outReceived`. """ logger.debug("asking for output") self.transport.write("\n")
jantman/gw2copilot
[ 5, 1, 5, 8, 1477907358 ]
def errReceived(self, data): """ Called when STDERR from the process has output; if we have not yet successfully deserialized a JSON message, logs STDERR at debug-level; otherwise discards it. :param data: STDERR from the process :type data: str """ if not self.have_data: logger.debug('Process STDERR: %s', data)
jantman/gw2copilot
[ 5, 1, 5, 8, 1477907358 ]
def processEnded(self, status): """called when the process ends and is cleaned up; just logs a debug message""" logger.debug("Process ended %s", status)
jantman/gw2copilot
[ 5, 1, 5, 8, 1477907358 ]
def outConnectionLost(self): """called when STDOUT connection is lost; just logs a debug message""" logger.debug("STDOUT connection lost") raise Exception('read_mumble_link.py (wine process) ' 'STDOUT connection lost')
jantman/gw2copilot
[ 5, 1, 5, 8, 1477907358 ]
def __init__(self, task_list_func, dispenser_data): """ Instantiate a new TaskDispenser :param task_list_func: A function returning the list of available course tasks from the task factory :param dispenser_data: The dispenser data structure/configuration """ pass
UCL-INGI/INGInious
[ 174, 124, 174, 110, 1407086326 ]
def get_id(cls): """ Returns the task dispenser id """ pass
UCL-INGI/INGInious
[ 174, 124, 174, 110, 1407086326 ]
def get_name(cls, language): """ Returns the localized task dispenser name """ pass
UCL-INGI/INGInious
[ 174, 124, 174, 110, 1407086326 ]
def get_dispenser_data(self): """ Returns the task dispenser data structure """ pass
UCL-INGI/INGInious
[ 174, 124, 174, 110, 1407086326 ]
def render_edit(self, template_helper, course, task_data): """ Returns the formatted task list edition form """ pass
UCL-INGI/INGInious
[ 174, 124, 174, 110, 1407086326 ]
def render(self, template_helper, course, tasks_data, tag_list): """ Returns the formatted task list""" pass
UCL-INGI/INGInious
[ 174, 124, 174, 110, 1407086326 ]
def check_dispenser_data(cls, dispenser_data): """ Checks the dispenser data as formatted by the form from render_edit function """ pass
UCL-INGI/INGInious
[ 174, 124, 174, 110, 1407086326 ]
def get_user_task_list(self, usernames): """ Returns the user task list that are eligible for grade computation :param usernames: List of usernames for which get the user task list :return: Returns a dictionary with username as key and the user task list as value """
UCL-INGI/INGInious
[ 174, 124, 174, 110, 1407086326 ]
def get_ordered_tasks(self): """ Returns a serialized version of the tasks structure as an OrderedDict""" pass
UCL-INGI/INGInious
[ 174, 124, 174, 110, 1407086326 ]
def import_key(keyserver: str, keyid: str): """ Attempts to import a key from the keyserver. :param keyserver: The keyserver to import from. :param keyid: The Key ID to import. :return: One of many codes: - 0: Success - -1: key not found - -2: Could not connect to keyserver - -3: Invalid key - -4: Already exists on server unchanged """ # Check to see if the server is a skier server. is_skier = False try: if 'http://' not in keyserver and "https://" not in keyserver: keyserver = "http://" + keyserver r = requests.post(keyserver + "/skier", data=[API_VERSION,SKIER_VERSION]) if r.status_code == 200: js = r.json() # Check the API version to make sure we're compatible. if js['api_version'] == API_VERSION: is_skier = True except: pass # Lookup the key. data = None if not is_skier: name = keyserver + "/pks/lookup" params = {"op": "get", "search": keyid, "options": "mr"} try: r = requests.get(name, params=params) except requests.exceptions.ConnectionError: return -2 else: if r.status_code == 200: data = r.text elif r.status_code == 404: return -1 elif r.status_code == 500: return -2 else: name = keyserver + "/api/{}/getkey/{}".format(API_VERSION, keyid) try: r = requests.get(name) except requests.exceptions.ConnectionError: return -2 else: if r.status_code == 200: data = r.json()['key'] else: return -1 if data: added = pgp.add_pgp_key(data) if added[0]: return 0 else: if added[1] == -1: # invalid return -3 elif added[1] == -2: # exists return -4
SkierPGP/Skier
[ 28, 4, 28, 1, 1439154717 ]
def _broadcast_add(key: db.Key): # Load the keyservers from the config file. keyservers = cfg.cfg.config.keyservers_synch for server in keyservers: assert isinstance(server, str) if not server.startswith("http"): # Force HTTPS by default, for security. server_url = "https://" + server else: server_url = server server = server.split("://")[1] try: r = requests.post(server_url + "/api/v{}/sync/new".format(cfg.API_VERSION), data={"key": key.armored}) except requests.exceptions.ConnectionError: continue if r.status_code == 200: # good! continue elif r.status_code == 599: # Invalid key. break
SkierPGP/Skier
[ 28, 4, 28, 1, 1439154717 ]
def forwards(self, orm): # Adding model 'Notification' db.create_table('notification_notification', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('user', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['auth.User'], unique=True)), ('notify_late_invoices', self.gf('django.db.models.fields.BooleanField')(default=False)), ('notify_invoices_to_send', self.gf('django.db.models.fields.BooleanField')(default=False)), ('notify_bug_comments', self.gf('django.db.models.fields.BooleanField')(default=False)), )) db.send_create_signal('notification', ['Notification'])
fgaudin/aemanager
[ 38, 20, 38, 17, 1292269932 ]
def _prepare_asset_vals(self, aml): vals = super()._prepare_asset_vals(aml) vals["move_id"] = aml.move_id vals["move_line_id"] = aml return vals
nuobit/odoo-addons
[ 8, 19, 8, 5, 1439376524 ]
def wrapper%(signature)s: with smtpmock: return func%(funcargs)s
privacyidea/privacyidea
[ 1321, 287, 1321, 217, 1401806822 ]
def get_wrapped(func, wrapper_template, evaldict): # Preserve the argspec for the wrapped function so that testing # tools such as pytest can continue to use their fixture injection. args = getargspec(func) values = args.args[-len(args.defaults):] if args.defaults else None signature = formatargspec(*args) is_bound_method = hasattr(func, '__self__') if is_bound_method: args.args = args.args[1:] # Omit 'self' callargs = formatargspec(*args, formatvalue=lambda v: '=' + v) ctx = {'signature': signature, 'funcargs': callargs} six.exec_(wrapper_template % ctx, evaldict) wrapper = evaldict['wrapper'] update_wrapper(wrapper, func) if is_bound_method: wrapper = wrapper.__get__(func.__self__, type(func.__self__)) return wrapper
privacyidea/privacyidea
[ 1321, 287, 1321, 217, 1401806822 ]
def __init__(self): self._calls = []
privacyidea/privacyidea
[ 1321, 287, 1321, 217, 1401806822 ]
def __len__(self): return len(self._calls)
privacyidea/privacyidea
[ 1321, 287, 1321, 217, 1401806822 ]
def setdata(self, request, response): self._calls.append(Call(request, response))
privacyidea/privacyidea
[ 1321, 287, 1321, 217, 1401806822 ]
def __init__(self): self._calls = CallList() self.sent_message = None self.smtp_ssl = False self.reset()
privacyidea/privacyidea
[ 1321, 287, 1321, 217, 1401806822 ]
def get_smtp_ssl(self): return self.smtp_ssl
privacyidea/privacyidea
[ 1321, 287, 1321, 217, 1401806822 ]
def get_sent_message(self): return self.sent_message
privacyidea/privacyidea
[ 1321, 287, 1321, 217, 1401806822 ]
def calls(self): return self._calls
privacyidea/privacyidea
[ 1321, 287, 1321, 217, 1401806822 ]
def __exit__(self, *args): self.stop() self.reset()
privacyidea/privacyidea
[ 1321, 287, 1321, 217, 1401806822 ]
def _on_request(self, SMTP_instance, sender, recipient, msg): # mangle request packet response = self._request_data.get("response") if not self._request_data.get("authenticated"): response = {self._request_data.get("recipient"): (530, "Authorization required (#5.7.1)")} return response
privacyidea/privacyidea
[ 1321, 287, 1321, 217, 1401806822 ]
def _on_init(self, *args, **kwargs): SMTP_instance = args[0] host = args[1] if isinstance(SMTP_instance, smtplib.SMTP_SSL): # in case we need sth. to do with SMTL_SSL self.smtp_ssl = True # mangle request packet self.timeout = kwargs.get("timeout", 10) self.port = kwargs.get("port", 25) self.esmtp_features = {} return None
privacyidea/privacyidea
[ 1321, 287, 1321, 217, 1401806822 ]
def _on_debuglevel(SMTP_instance, level): return None
privacyidea/privacyidea
[ 1321, 287, 1321, 217, 1401806822 ]
def _on_quit(SMTP_instance): return None
privacyidea/privacyidea
[ 1321, 287, 1321, 217, 1401806822 ]
def start(self): import mock def unbound_on_send(SMTP, sender, recipient, msg, *a, **kwargs): self.sent_message = msg return self._on_request(SMTP, sender, recipient, msg, *a, **kwargs) self._patcher = mock.patch('smtplib.SMTP.sendmail', unbound_on_send) self._patcher.start() def unbound_on_login(SMTP, username, password, *a, **kwargs): return self._on_login(SMTP, username, password, *a, **kwargs) self._patcher2 = mock.patch('smtplib.SMTP.login', unbound_on_login) self._patcher2.start() def unbound_on_init(SMTP, server, *a, **kwargs): return self._on_init(SMTP, server, *a, **kwargs) self._patcher3 = mock.patch('smtplib.SMTP.__init__', unbound_on_init) self._patcher3.start() def unbound_on_debuglevel(SMTP, level, *a, **kwargs): return self._on_debuglevel(SMTP, level, *a, **kwargs) self._patcher4 = mock.patch('smtplib.SMTP.debuglevel', unbound_on_debuglevel) self._patcher4.start() def unbound_on_quit(SMTP, *a, **kwargs): return self._on_quit(SMTP, *a, **kwargs) def unbound_on_starttls(SMTP, *a, **kwargs): return self._on_starttls(SMTP, *a, **kwargs) self._patcher5 = mock.patch('smtplib.SMTP.quit', unbound_on_quit) self._patcher5.start() def unbound_on_empty(SMTP, *a, **kwargs): return None self._patcher6 = mock.patch('smtplib.SMTP.ehlo', unbound_on_empty) self._patcher6.start() self._patcher7 = mock.patch('smtplib.SMTP.close', unbound_on_empty) self._patcher7.start() self._patcher8 = mock.patch('smtplib.SMTP.starttls', unbound_on_starttls) self._patcher8.start()
privacyidea/privacyidea
[ 1321, 287, 1321, 217, 1401806822 ]
def create_etag(pairs: List[Tuple[QuerySet, str]]) -> str: """ Turn a list of queryset and timestamp pairs into an etag. The latest timestamp will be chosen as the etag :param pairs: a list of queryset and attribute which holds a timestamp :return: an etag """ result = map(lambda p: p[0].aggregate(m=Max(p[1]))['m'], pairs) result = filter(lambda r: r is not None, result) return str(max(result, default=''))
nextcloud/appstore
[ 235, 131, 235, 80, 1464972556 ]
def apps_all_etag(request: Any) -> str: return create_etag([ (App.objects.all(), 'last_release'), (AppReleaseDeleteLog.objects.all(), 'last_modified'), ])
nextcloud/appstore
[ 235, 131, 235, 80, 1464972556 ]
def app_rating_etag(request: Any, id: str) -> str: return create_etag([(AppRating.objects.filter(app__id=id), 'rated_at')])
nextcloud/appstore
[ 235, 131, 235, 80, 1464972556 ]
def app_ratings_etag(request: Any) -> str: return create_etag([(AppRating.objects.all(), 'rated_at')])
nextcloud/appstore
[ 235, 131, 235, 80, 1464972556 ]
def verbose_name(obj, arg): return capfirst(obj._meta.get_field(arg).verbose_name)
sbsdev/daisyproducer
[ 5, 3, 5, 4, 1251982227 ]
def test_get_all_manual_checks_for_specific_team(self): self.login_user('admin', 'admin') rest_result = self.app.get('/teams/1/checks/manual') print rest_result.status_code, rest_result.data assert rest_result.status_code == 200 expected_result = [obj for obj in self.data['completed_checks'] if obj['team_id'] == '1' and obj['type'] == 'manual'] json_result = json.loads(rest_result.data) assert len(json_result) == len(expected_result) for i in expected_result: del i['team_id'], i['type'] convert_all_datetime_to_timestamp(i, ['timestamp', 'time_to_check']) assert json_result == expected_result
smartboyathome/Wonderland-Engine
[ 9, 3, 9, 1, 1341121049 ]
def test_get_specific_manual_check_for_specific_team(self): self.login_user('admin', 'admin') rest_result = self.app.get('/teams/1/checks/manual/BoardPresentation') print rest_result.status_code, rest_result.data assert rest_result.status_code == 200 expected_result = [obj for obj in self.data['completed_checks'] if obj['team_id'] == '1' and obj['type'] == 'manual' and obj['id'] == 'BoardPresentation'] json_result = json.loads(rest_result.data) assert len(json_result) == len(expected_result) for i in expected_result: del i['team_id'], i['type'], i['id'] convert_all_datetime_to_timestamp(i, ['timestamp', 'time_to_check']) assert json_result == expected_result
smartboyathome/Wonderland-Engine
[ 9, 3, 9, 1, 1341121049 ]
def genlist(self, limit, start, stop=None, step=None): if stop is None: stop = start start = None return list(slicerange(slice(start, stop, step), limit))
stoq/kiwi
[ 24, 20, 24, 1, 1361812566 ]
def testStartStop(self): self.assertEqual(self.genlist(10, 0, 10), list(range(10))) self.assertEqual(self.genlist(10, 1, 9), list(range(10))[1:9]) self.assertEqual(self.genlist(10, -1, -1), list(range(10))[-1:-1]) self.assertEqual(self.genlist(10, 0, -15), list(range(10))[0:-15]) self.assertEqual(self.genlist(10, 15, 0), list(range(10))[-15:0])
stoq/kiwi
[ 24, 20, 24, 1, 1361812566 ]
def testEnums(self): self.assertTrue(issubclass(enum, int)) self.assertTrue(isinstance(Color.RED, Color)) self.assertTrue(isinstance(Color.RED, int)) self.assertTrue('RED' in repr(Color.RED), repr(Color.RED)) self.assertTrue(int(Color.RED) is not None)
stoq/kiwi
[ 24, 20, 24, 1, 1361812566 ]
def testGet(self): self.assertEqual(Color.get(0), Color.RED) self.assertRaises(ValueError, Color.get, 3)
stoq/kiwi
[ 24, 20, 24, 1, 1361812566 ]
def testForward(self): class FW(AttributeForwarder): attributes = ['forward'] class Target(object): forward = 'foo' target = Target() f = FW(target) self.assertEqual(f.target, target) self.assertEqual(f.forward, 'foo') f.forward = 'bar' self.assertEqual(target.forward, 'bar') self.assertEqual(f.forward, 'bar')
stoq/kiwi
[ 24, 20, 24, 1, 1361812566 ]
def testStripAccents(self): for string, string_without_accentuation in [ # bytes ('áâãäåāăąàÁÂÃÄÅĀĂĄÀ'.encode(), b'aaaaaaaaaAAAAAAAAA'), ('èééêëēĕėęěĒĔĖĘĚ'.encode(), b'eeeeeeeeeeEEEEE'), ('ìíîïìĩīĭÌÍÎÏÌĨĪĬ'.encode(), b'iiiiiiiiIIIIIIII'), ('óôõöōŏőÒÓÔÕÖŌŎŐ'.encode(), b'oooooooOOOOOOOO'), ('ùúûüũūŭůÙÚÛÜŨŪŬŮ'.encode(), b'uuuuuuuuUUUUUUUU'), ('çÇ'.encode(), b'cC'), # strings ('áâãäåāăąàÁÂÃÄÅĀĂĄÀ', 'aaaaaaaaaAAAAAAAAA'), ('èééêëēĕėęěĒĔĖĘĚ', 'eeeeeeeeeeEEEEE'), ('ìíîïìĩīĭÌÍÎÏÌĨĪĬ', 'iiiiiiiiIIIIIIII'), ('óôõöōŏőÒÓÔÕÖŌŎŐ', 'oooooooOOOOOOOO'), ('ùúûüũūŭůÙÚÛÜŨŪŬŮ', 'uuuuuuuuUUUUUUUU'), ('çÇ', 'cC'), ]: self.assertEqual(strip_accents(string), string_without_accentuation)
stoq/kiwi
[ 24, 20, 24, 1, 1361812566 ]
def n2k(*args, **kwargs): return num2words(*args, lang='ko', **kwargs)
savoirfairelinux/num2words
[ 692, 422, 692, 153, 1369760071 ]
def test_low(self): cases = [(0, "영"), (1, "일"), (2, "이"), (3, "삼"), (4, "사"), (5, "오"), (6, "육"), (7, "칠"), (8, "팔"), (9, "구"), (10, "십"), (11, "십일"), (12, "십이"), (13, "십삼"), (14, "십사"), (15, "십오"), (16, "십육"), (17, "십칠"), (18, "십팔"), (19, "십구"), (20, "이십"), (25, "이십오"), (31, "삼십일"), (42, "사십이"), (54, "오십사"), (63, "육십삼"), (76, "칠십육"), (89, "팔십구"), (98, "구십팔")] for num, out in cases: self.assertEqual(n2k(num), out)
savoirfairelinux/num2words
[ 692, 422, 692, 153, 1369760071 ]
def test_high(self): cases = [(10000, "만"), (11020, "만 천이십"), (25891, "이만 오천팔백구십일"), (64237, "육만 사천이백삼십칠"), (241572, "이십사만 천오백칠십이"), (100000000, "일억"), (5000500000000, "오조 오억")] for num, out in cases: self.assertEqual(n2k(num), out)
savoirfairelinux/num2words
[ 692, 422, 692, 153, 1369760071 ]
def test_year(self): cases = [(2000, "이천년"), (2002, "이천이년"), (2018, "이천십팔년"), (1954, "천구백오십사년"), (1910, "천구백십년"), (-1000, "기원전 천년")] for num, out in cases: self.assertEqual(n2k(num, to="year"), out)
savoirfairelinux/num2words
[ 692, 422, 692, 153, 1369760071 ]
def test_ordinal(self): cases = [(1, "첫 번째"), (101, "백 한 번째"), (2, "두 번째"), (5, "다섯 번째"), (10, "열 번째"), (25, "스물다섯 번째"), (137, "백 서른일곱 번째")] for num, out in cases: self.assertEqual(n2k(num, to="ordinal"), out)
savoirfairelinux/num2words
[ 692, 422, 692, 153, 1369760071 ]
def __init__(self) -> None: super().__init__() # Listen to a Signal that indicates a change in the list of printers, just if the user has enabled the # "check for updates" option Application.getInstance().getPreferences().addPreference("info/automatic_update_check", True) if Application.getInstance().getPreferences().getValue("info/automatic_update_check"): ContainerRegistry.getInstance().containerAdded.connect(self._onContainerAdded) self._check_job = None self._checked_printer_names = set() # type: Set[str]
Ultimaker/Cura
[ 4656, 1806, 4656, 2468, 1402923331 ]
def _onContainerAdded(self, container): # Only take care when a new GlobalStack was added from cura.Settings.GlobalStack import GlobalStack # otherwise circular imports if isinstance(container, GlobalStack): self.checkFirmwareVersion(container, True)
Ultimaker/Cura
[ 4656, 1806, 4656, 2468, 1402923331 ]
def test_min_degree_elimination_order(self): bn = XMLBIFParser.parse("primo2/tests/slippery.xbif") order = Orderer.get_min_degree_order(bn) #Test for all possible/equivalent orders since the actual order might is not #determined based on the random nature hash in Python3 potentialOrders = [["slippery_road", "wet_grass", "sprinkler", "winter", "rain"], ["slippery_road", "wet_grass", "sprinkler", "rain", "winter"], ["slippery_road", "wet_grass", "rain", "sprinkler", "winter"], ["slippery_road", "wet_grass", "rain", "winter", "sprinkler"], ["slippery_road", "wet_grass", "winter", "rain", "sprinkler"], ["slippery_road", "wet_grass", "winter", "sprinkler", "rain"], ["slippery_road", "winter", "sprinkler", "wet_grass", "rain"], ["slippery_road", "winter", "sprinkler", "rain", "wet_grass"], ["slippery_road", "winter", "rain", "sprinkler", "wet_grass"], ["slippery_road", "winter", "rain", "wet_grass", "sprinkler"], ["slippery_road", "winter", "wet_grass", "sprinkler", "rain"], ["slippery_road", "winter", "wet_grass", "rain", "sprinkler"], ["slippery_road", "sprinkler", "winter", "wet_grass", "rain"], ["slippery_road", "sprinkler", "winter", "rain", "wet_grass"], ["slippery_road", "sprinkler", "wet_grass", "winter", "rain"], ["slippery_road", "sprinkler", "wet_grass", "rain", "winter"], ["slippery_road", "sprinkler", "rain", "winter", "wet_grass"], ["slippery_road", "sprinkler", "rain", "wet_grass", "winter"], ["slippery_road", "rain", "wet_grass", "sprinkler", "winter"], ["slippery_road", "rain", "wet_grass", "winter", "sprinkler"], ["slippery_road", "rain", "winter", "wet_grass", "sprinkler"], ["slippery_road", "rain", "winter", "sprinkler", "wet_grass"], ["slippery_road", "rain", "sprinkler", "wet_grass", "winter"], ["slippery_road", "rain", "sprinkler", "winter", "wet_grass"]] self.assertTrue(order in potentialOrders)
SocialCognitiveSystems/PRIMO
[ 4, 3, 4, 10, 1486413504 ]
def test_random_elimination_order(self): bn = XMLBIFParser.parse("primo2/tests/slippery.xbif") order = Orderer.get_random_order(bn) variables = ["slippery_road", "winter", "rain", "sprinkler", "wet_grass"] self.assertEqual(len(order), len(variables)) for v in variables: self.assertTrue(v in order)
SocialCognitiveSystems/PRIMO
[ 4, 3, 4, 10, 1486413504 ]
def setUp(self): self.bn = XMLBIFParser.parse("primo2/tests/slippery.xbif")
SocialCognitiveSystems/PRIMO
[ 4, 3, 4, 10, 1486413504 ]
def test_empty_cpt(self): bn = BayesianNetwork() from primo2.nodes import DiscreteNode n1 = DiscreteNode("a") n2 = DiscreteNode("b") bn.add_node(n1) bn.add_node(n2) bn.add_edge(n1,n2) res = VariableElimination.naive_marginals(bn, ["a"]) np.testing.assert_array_almost_equal(res.get_potential(), np.array([0.0, 0.0]))
SocialCognitiveSystems/PRIMO
[ 4, 3, 4, 10, 1486413504 ]
def test_naive_marginals(self): resFactor = VariableElimination.naive_marginals(self.bn, ["winter"]) np.testing.assert_array_almost_equal(resFactor.get_potential(), np.array([0.6, 0.4]))
SocialCognitiveSystems/PRIMO
[ 4, 3, 4, 10, 1486413504 ]
def test_naive_marginal_evidence_trivial(self): resFactor = VariableElimination.naive_marginals(self.bn, ["rain"], {"winter": "true"}) np.testing.assert_array_almost_equal(resFactor.get_potential(), np.array([0.8, 0.2]))
SocialCognitiveSystems/PRIMO
[ 4, 3, 4, 10, 1486413504 ]
def test_naive_marginal_evidence_trivial_multiple_evidence(self): resFactor = VariableElimination.naive_marginals(self.bn, ["wet_grass"], {"sprinkler": "true", "rain": "false"}) np.testing.assert_array_almost_equal(resFactor.get_potential(), np.array([0.1, 0.9]))
SocialCognitiveSystems/PRIMO
[ 4, 3, 4, 10, 1486413504 ]
def test_naive_marginal_evidence(self): resFactor = VariableElimination.naive_marginals(self.bn, ["wet_grass"], {"winter": "true"}) np.testing.assert_array_almost_equal(resFactor.get_potential(), np.array([0.668, 0.332]))
SocialCognitiveSystems/PRIMO
[ 4, 3, 4, 10, 1486413504 ]
def test_naive_marginal_evidence_multiple_evidence(self): resFactor = VariableElimination.naive_marginals(self.bn, ["wet_grass"], {"winter": "true", "rain": "false"}) np.testing.assert_array_almost_equal(resFactor.get_potential(), np.array([0.02, 0.98]))
SocialCognitiveSystems/PRIMO
[ 4, 3, 4, 10, 1486413504 ]
def test_bucket_marginals(self): resFactor = VariableElimination.bucket_marginals(self.bn, ["winter"]) np.testing.assert_array_almost_equal(resFactor.get_potential(), np.array([0.6, 0.4]))
SocialCognitiveSystems/PRIMO
[ 4, 3, 4, 10, 1486413504 ]
def test_bucket_marginal_evidence_trivial(self): resFactor = VariableElimination.bucket_marginals(self.bn, ["rain"], {"wet_grass": "false"}) np.testing.assert_array_almost_equal(resFactor.get_potential(), np.array([0.158858, 0.841142]))
SocialCognitiveSystems/PRIMO
[ 4, 3, 4, 10, 1486413504 ]
def test_bucket_marginal_evidence_trivial_multiple_evidence(self): resFactor = VariableElimination.bucket_marginals(self.bn, ["wet_grass"], {"sprinkler": "true", "rain": "false"}) np.testing.assert_array_almost_equal(resFactor.get_potential(), np.array([0.1, 0.9]))
SocialCognitiveSystems/PRIMO
[ 4, 3, 4, 10, 1486413504 ]
def test_bucket_marginal_evidence(self): resFactor = VariableElimination.bucket_marginals(self.bn, ["wet_grass"], {"winter": "true"}) np.testing.assert_array_almost_equal(resFactor.get_potential(), np.array([0.668, 0.332]))
SocialCognitiveSystems/PRIMO
[ 4, 3, 4, 10, 1486413504 ]
def test_bucket_marginal_evidence_multiple_evidence(self): resFactor = VariableElimination.bucket_marginals(self.bn, ["wet_grass"], {"winter": "true", "rain": "false"}) np.testing.assert_array_almost_equal(resFactor.get_potential(), np.array([0.02, 0.98]))
SocialCognitiveSystems/PRIMO
[ 4, 3, 4, 10, 1486413504 ]
def setUp(self): self.bn = XMLBIFParser.parse("primo2/tests/slippery.xbif")
SocialCognitiveSystems/PRIMO
[ 4, 3, 4, 10, 1486413504 ]
def test_not_connected_node_without_cpt(self):
SocialCognitiveSystems/PRIMO
[ 4, 3, 4, 10, 1486413504 ]
def test_empty_cpt(self): bn = BayesianNetwork() from primo2.nodes import DiscreteNode n1 = DiscreteNode("a") n2 = DiscreteNode("b") bn.add_node(n1) bn.add_node(n2) bn.add_edge(n1,n2) ft = FactorTree.create_jointree(bn) res = ft.marginals(["a"]) np.testing.assert_array_almost_equal(res.get_potential(), np.array([0.0, 0.0]))
SocialCognitiveSystems/PRIMO
[ 4, 3, 4, 10, 1486413504 ]
def test_create_jointree(self): order = ["slippery_road", "wet_grass", "sprinkler", "winter", "rain"] ft = FactorTree.create_jointree(self.bn, order=order) #As above, alternatives need to be contained as well for python3 desiredCliques = ["slippery_roadrain", "wet_grasssprinklerrain", "wet_grassrainsprinkler", "sprinklerwinterrain", "sprinklerrainwinter", "wintersprinklerrain", "winterrainsprinkler", "rainsprinklerwinter", "rainwintersprinkler"] self.assertEqual(len(ft.tree), 3) for n in ft.tree.nodes(): # was nodes_iter in networkx 1.x self.assertTrue(n in desiredCliques)
SocialCognitiveSystems/PRIMO
[ 4, 3, 4, 10, 1486413504 ]
def test_jointree_marginals(self): ft = FactorTree.create_jointree(self.bn) resFactor = ft.marginals(["winter"]) np.testing.assert_array_almost_equal(resFactor.get_potential(), np.array([0.6, 0.4]))
SocialCognitiveSystems/PRIMO
[ 4, 3, 4, 10, 1486413504 ]
def test_jointree_marginals2(self): ft = FactorTree.create_jointree(self.bn) resFactor = ft.marginals(["slippery_road"]) np.testing.assert_array_almost_equal(resFactor.get_potential(), np.array([0.364, 0.636]))
SocialCognitiveSystems/PRIMO
[ 4, 3, 4, 10, 1486413504 ]