function
stringlengths
16
7.61k
repo_name
stringlengths
9
46
features
sequence
def string_match(cls, pattern, value): return pattern.lower() in value.lower()
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def __init__(self, field, pattern, fast=True): super().__init__(field, pattern, fast) pattern = self._normalize(pattern) try: self.pattern = re.compile(self.pattern) except re.error as exc: # Invalid regular expression. raise InvalidQueryArgumentValueError(pattern, "a regular expression", format(exc))
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def _normalize(s): """Normalize a Unicode string's representation (used on both patterns and matched values). """ return unicodedata.normalize('NFC', s)
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def string_match(cls, pattern, value): return pattern.search(cls._normalize(value)) is not None
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def __init__(self, field, pattern, fast=True): super().__init__(field, pattern, fast) if isinstance(pattern, str): self.pattern = util.str2bool(pattern) self.pattern = int(self.pattern)
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def __init__(self, field, pattern): super().__init__(field, pattern) # Use a buffer/memoryview representation of the pattern for SQLite # matching. This instructs SQLite to treat the blob as binary # rather than encoded Unicode. if isinstance(self.pattern, (str, bytes)): if isinstance(self.pattern, str): self.pattern = self.pattern.encode('utf-8') self.buf_pattern = memoryview(self.pattern) elif isinstance(self.pattern, memoryview): self.buf_pattern = self.pattern self.pattern = bytes(self.pattern)
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def _convert(self, s): """Convert a string to a numeric type (float or int). Return None if `s` is empty. Raise an InvalidQueryError if the string cannot be converted. """ # This is really just a bit of fun premature optimization. if not s: return None try: return int(s) except ValueError: try: return float(s) except ValueError: raise InvalidQueryArgumentValueError(s, "an int or a float")
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def match(self, item): if self.field not in item: return False value = item[self.field] if isinstance(value, str): value = self._convert(value) if self.point is not None: return value == self.point else: if self.rangemin is not None and value < self.rangemin: return False if self.rangemax is not None and value > self.rangemax: return False return True
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def __init__(self, subqueries=()): self.subqueries = subqueries
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def __len__(self): return len(self.subqueries)
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def __iter__(self): return iter(self.subqueries)
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def clause_with_joiner(self, joiner): """Return a clause created by joining together the clauses of all subqueries with the string joiner (padded by spaces). """ clause_parts = [] subvals = [] for subq in self.subqueries: subq_clause, subq_subvals = subq.clause() if not subq_clause: # Fall back to slow query. return None, () clause_parts.append('(' + subq_clause + ')') subvals += subq_subvals clause = (' ' + joiner + ' ').join(clause_parts) return clause, subvals
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def __eq__(self, other): return super().__eq__(other) and \ self.subqueries == other.subqueries
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def __init__(self, pattern, fields, cls): self.pattern = pattern self.fields = fields self.query_class = cls subqueries = [] for field in self.fields: subqueries.append(cls(field, pattern, True)) super().__init__(subqueries)
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def match(self, item): for subq in self.subqueries: if subq.match(item): return True return False
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def __eq__(self, other): return super().__eq__(other) and \ self.query_class == other.query_class
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def __setitem__(self, key, value): self.subqueries[key] = value
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def clause(self): return self.clause_with_joiner('and')
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def clause(self): return self.clause_with_joiner('or')
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def __init__(self, subquery): self.subquery = subquery
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def match(self, item): return not self.subquery.match(item)
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def __eq__(self, other): return super().__eq__(other) and \ self.subquery == other.subquery
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def clause(self): return '1', ()
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def clause(self): return '0', ()
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def _to_epoch_time(date): """Convert a `datetime` object to an integer number of seconds since the (local) Unix epoch. """ if hasattr(date, 'timestamp'): # The `timestamp` method exists on Python 3.3+. return int(date.timestamp()) else: epoch = datetime.fromtimestamp(0) delta = date - epoch return int(delta.total_seconds())
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def __init__(self, date, precision): """Create a period with the given date (a `datetime` object) and precision (a string, one of "year", "month", "day", "hour", "minute", or "second"). """ if precision not in Period.precisions: raise ValueError(f'Invalid precision {precision}') self.date = date self.precision = precision
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def parse(cls, string): """Parse a date and return a `Period` object or `None` if the string is empty, or raise an InvalidQueryArgumentValueError if the string cannot be parsed to a date. The date may be absolute or relative. Absolute dates look like `YYYY`, or `YYYY-MM-DD`, or `YYYY-MM-DD HH:MM:SS`, etc. Relative dates have three parts: - Optionally, a ``+`` or ``-`` sign indicating the future or the past. The default is the future. - A number: how much to add or subtract. - A letter indicating the unit: days, weeks, months or years (``d``, ``w``, ``m`` or ``y``). A "month" is exactly 30 days and a "year" is exactly 365 days. """ def find_date_and_format(string): for ord, format in enumerate(cls.date_formats): for format_option in format: try: date = datetime.strptime(string, format_option) return date, ord except ValueError: # Parsing failed. pass return (None, None) if not string: return None # Check for a relative date. match_dq = re.match(cls.relative_re, string) if match_dq: sign = match_dq.group('sign') quantity = match_dq.group('quantity') timespan = match_dq.group('timespan') # Add or subtract the given amount of time from the current # date. multiplier = -1 if sign == '-' else 1 days = cls.relative_units[timespan] date = datetime.now() + \ timedelta(days=int(quantity) * days) * multiplier return cls(date, cls.precisions[5]) # Check for an absolute date. date, ordinal = find_date_and_format(string) if date is None: raise InvalidQueryArgumentValueError(string, 'a valid date/time string') precision = cls.precisions[ordinal] return cls(date, precision)
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def __init__(self, start, end): if start is not None and end is not None and not start < end: raise ValueError("start date {} is not before end date {}" .format(start, end)) self.start = start self.end = end
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def from_periods(cls, start, end): """Create an interval with two Periods as the endpoints. """ end_date = end.open_right_endpoint() if end is not None else None start_date = start.date if start is not None else None return cls(start_date, end_date)
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def __str__(self): return f'[{self.start}, {self.end})'
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def __init__(self, field, pattern, fast=True): super().__init__(field, pattern, fast) start, end = _parse_periods(pattern) self.interval = DateInterval.from_periods(start, end)
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def col_clause(self): clause_parts = [] subvals = [] if self.interval.start: clause_parts.append(self._clause_tmpl.format(self.field, ">=")) subvals.append(_to_epoch_time(self.interval.start)) if self.interval.end: clause_parts.append(self._clause_tmpl.format(self.field, "<")) subvals.append(_to_epoch_time(self.interval.end)) if clause_parts: # One- or two-sided interval. clause = ' AND '.join(clause_parts) else: # Match any date. clause = '1' return clause, subvals
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def _convert(self, s): """Convert a M:SS or numeric string to a float. Return None if `s` is empty. Raise an InvalidQueryError if the string cannot be converted. """ if not s: return None try: return util.raw_seconds_short(s) except ValueError: try: return float(s) except ValueError: raise InvalidQueryArgumentValueError( s, "a M:SS string or a float")
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def order_clause(self): """Generates a SQL fragment to be used in a ORDER BY clause, or None if no fragment is used (i.e., this is a slow sort). """ return None
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def is_slow(self): """Indicate whether this query is *slow*, meaning that it cannot be executed in SQL and must be executed in Python. """ return False
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def __eq__(self, other): return type(self) == type(other)
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def __init__(self, sorts=None): self.sorts = sorts or []
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def _sql_sorts(self): """Return the list of sub-sorts for which we can be (at least partially) fast. A contiguous suffix of fast (SQL-capable) sub-sorts are executable in SQL. The remaining, even if they are fast independently, must be executed slowly. """ sql_sorts = [] for sort in reversed(self.sorts): if not sort.order_clause() is None: sql_sorts.append(sort) else: break sql_sorts.reverse() return sql_sorts
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def is_slow(self): for sort in self.sorts: if sort.is_slow(): return True return False
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def __repr__(self): return f'MultipleSort({self.sorts!r})'
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def __eq__(self, other): return super().__eq__(other) and \ self.sorts == other.sorts
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def __init__(self, field, ascending=True, case_insensitive=True): self.field = field self.ascending = ascending self.case_insensitive = case_insensitive
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def key(item): field_val = item.get(self.field, '') if self.case_insensitive and isinstance(field_val, str): field_val = field_val.lower() return field_val
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def __repr__(self): return '<{}: {}{}>'.format( type(self).__name__, self.field, '+' if self.ascending else '-', )
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def __eq__(self, other): return super().__eq__(other) and \ self.field == other.field and \ self.ascending == other.ascending
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def order_clause(self): order = "ASC" if self.ascending else "DESC" if self.case_insensitive: field = '(CASE ' \ 'WHEN TYPEOF({0})="text" THEN LOWER({0}) ' \ 'WHEN TYPEOF({0})="blob" THEN LOWER({0}) ' \ 'ELSE {0} END)'.format(self.field) else: field = self.field return f"{field} {order}"
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def is_slow(self): return True
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def sort(self, items): return items
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def __bool__(self): return False
beetbox/beets
[ 11484, 1774, 11484, 509, 1281395840 ]
def format_time(seconds): v = seconds if v * 1000 * 1000 * 1000 < 1000: scale = u'ns' v = int(round(v*1000*1000*1000)) elif v * 1000 * 1000 < 1000: scale = u'μs' v = int(round(v*1000*1000)) elif v * 1000 < 1000: scale = u'ms' v = round(v*1000, 4) else: scale = u'sec' v = int(v) return u'{} {}'.format(v, scale)
simonz05/pack-command
[ 3, 3, 3, 1, 1369224768 ]
def runit(): pack_command.pack_command("ZADD", "foo", 1369198341, 10000)
simonz05/pack-command
[ 3, 3, 3, 1, 1369224768 ]
def preprocess_image(screen_image): # crop the top and bottom screen_image = screen_image[35:195] # down sample by a factor of 2 screen_image = screen_image[::2, ::2] # convert to grey scale grey_image = np.zeros(screen_image.shape[0:2]) for i in range(len(screen_image)): for j in range(len(screen_image[i])): grey_image[i][j] = np.mean(screen_image[i][j]) return np.array([grey_image.astype(np.float)])
tuzzer/ai-gym
[ 36, 34, 36, 8, 1474787414 ]
def __init__(self): #### Construct the model #### observation = cntk.ops.input_variable(STATE_DIMS, np.float32, name="s") q_target = cntk.ops.input_variable(NUM_ACTIONS, np.float32, name="q") # Define the structure of the neural network self.model = self.create_convolutional_neural_network(observation, NUM_ACTIONS) #### Define the trainer #### self.learning_rate = cntk.learner.training_parameter_schedule(0.0001, cntk.UnitType.sample) self.momentum = cntk.learner.momentum_as_time_constant_schedule(0.99) self.loss = cntk.ops.reduce_mean(cntk.ops.square(self.model - q_target), axis=0) mean_error = cntk.ops.reduce_mean(cntk.ops.square(self.model - q_target), axis=0) learner = cntk.adam_sgd(self.model.parameters, self.learning_rate, momentum=self.momentum) self.trainer = cntk.Trainer(self.model, self.loss, mean_error, learner)
tuzzer/ai-gym
[ 36, 34, 36, 8, 1474787414 ]
def predict(self, s): return self.model.eval([s])
tuzzer/ai-gym
[ 36, 34, 36, 8, 1474787414 ]
def create_multi_layer_neural_network(input_vars, out_dims, num_hidden_layers): num_hidden_neurons = 128 hidden_layer = lambda: Dense(num_hidden_neurons, activation=cntk.ops.relu) output_layer = Dense(out_dims, activation=None) model = Sequential([LayerStack(num_hidden_layers, hidden_layer), output_layer])(input_vars) return model
tuzzer/ai-gym
[ 36, 34, 36, 8, 1474787414 ]
def create_convolutional_neural_network(input_vars, out_dims): convolutional_layer_1 = Convolution((5, 5), 32, strides=1, activation=cntk.ops.relu, pad=True, init=glorot_normal(), init_bias=0.1) pooling_layer_1 = MaxPooling((2, 2), strides=(2, 2), pad=True) convolutional_layer_2 = Convolution((5, 5), 64, strides=1, activation=cntk.ops.relu, pad=True, init=glorot_normal(), init_bias=0.1) pooling_layer_2 = MaxPooling((2, 2), strides=(2, 2), pad=True) convolutional_layer_3 = Convolution((5, 5), 128, strides=1, activation=cntk.ops.relu, pad=True, init=glorot_normal(), init_bias=0.1) pooling_layer_3 = MaxPooling((2, 2), strides=(2, 2), pad=True) fully_connected_layer = Dense(1024, activation=cntk.ops.relu, init=glorot_normal(), init_bias=0.1) output_layer = Dense(out_dims, activation=None, init=glorot_normal(), init_bias=0.1) model = Sequential([convolutional_layer_1, pooling_layer_1, convolutional_layer_2, pooling_layer_2, #convolutional_layer_3, pooling_layer_3, fully_connected_layer, output_layer])(input_vars) return model
tuzzer/ai-gym
[ 36, 34, 36, 8, 1474787414 ]
def __init__(self, capacity): self.examplers = deque(maxlen=capacity) self.capacity = capacity
tuzzer/ai-gym
[ 36, 34, 36, 8, 1474787414 ]
def get_random_samples(self, num_samples): num_samples = min(num_samples, len(self.examplers)) return random.sample(tuple(self.examplers), num_samples)
tuzzer/ai-gym
[ 36, 34, 36, 8, 1474787414 ]
def get_random_stacks(self, num_samples, stack_size): start_indices = random.sample(range(len(self.examplers)), num_samples) return [self.get_stack(start_index, stack_size) for start_index in start_indices]
tuzzer/ai-gym
[ 36, 34, 36, 8, 1474787414 ]
def __init__(self): self.explore_rate = self.MAX_EXPLORATION_RATE self.brain = Brain() self.memory = Memory(self.MEMORY_CAPACITY) self.steps = 0
tuzzer/ai-gym
[ 36, 34, 36, 8, 1474787414 ]
def observe(self, sample): self.steps += 1 self.memory.add(sample) # Reduces exploration rate linearly self.explore_rate = self.MIN_EXPLORATION_RATE + (self.MAX_EXPLORATION_RATE - self.MIN_EXPLORATION_RATE) * math.exp(-self.DECAY_RATE * self.steps)
tuzzer/ai-gym
[ 36, 34, 36, 8, 1474787414 ]
def action_from_output(cls, output_array): return np.argmax(output_array)
tuzzer/ai-gym
[ 36, 34, 36, 8, 1474787414 ]
def test(model_path, num_episodes=10): root = cntk.load_model(model_path) observation = env.reset() # reset environment for new episode done = False for episode in range(num_episodes): while not done: try: env.render() except Exception: # this might fail on a VM without OpenGL pass observation = preprocess_image(observation) action = np.argmax(root.eval(observation.astype(np.float32))) observation, reward, done, info = env.step(action) if done: observation = env.reset() # reset environment for new episode
tuzzer/ai-gym
[ 36, 34, 36, 8, 1474787414 ]
def __init__(self): self.priority = 1 self.language = ['en'] self.domains = ['coolmoviezone.online'] self.base_link = 'https://coolmoviezone.online' self.scraper = cfscrape.create_scraper()
repotvsupertuga/tvsupertuga.repository
[ 1, 8, 1, 4, 1493763534 ]
def sources(self, url, hostDict, hostprDict): try: sources = [] r = self.scraper.get(url).content match = re.compile('<td align="center"><strong><a href="(.+?)"').findall(r) for url in match: host = url.split('//')[1].replace('www.', '') host = host.split('/')[0].split('.')[0].title() quality = source_utils.check_sd_url(url) sources.append({'source': host, 'quality': quality, 'language': 'en', 'url': url, 'direct': False, 'debridonly': False}) except Exception: return return sources
repotvsupertuga/tvsupertuga.repository
[ 1, 8, 1, 4, 1493763534 ]
def __init__(self, tableName, tableColumns=[], coreInfo={}): self.tableName = tableName self.columnsDict = OrderedDict(tableColumns) self.dbFile = os.path.join(os.getcwd().replace("python", "metadata"), "libretro.sqlite") self.dbFileExists = os.path.isfile(self.dbFile) self.coreInfo = coreInfo # self.filterUnusedCores()
team-phoenix/Phoenix
[ 373, 39, 373, 140, 1403229704 ]
def updateColumns(self, database, additionalStatement: str = ""): if not self.dbFileExists: database.createTable(self.tableName, self.columnsDict, additionalStatement) else: try: database.deleteTable(self.tableName) except: database.createTable(self.tableName, self.columnsDict, additionalStatement)
team-phoenix/Phoenix
[ 373, 39, 373, 140, 1403229704 ]
def libretroSystemList(self): systems = [] for k, v in self.coreInfo['cores'].items(): if "categories" not in v or v["categories"] != "Emulator": continue if "database" in v: name = v["database"].split("|") for n in name: systems.append(n) # Split console and manufacturer names # Not really necessary for Libretro identifiers #tup = n.split(" - ") # ## "MAME" #if len(tup) == 1: # systems.append(tup[0]) # ## Nearly every one #elif len(tup) == 2: # systems.append(tup[1]) # ## Sega - Master System - Mark III ## Sega - Mega Drive - Genesis #elif len(tup) == 3: # systems.append(tup[1]) # There are some cores that do not have "database" defined elif "systemname" in v: systems.append(v["systemname"]) systems = list(set(systems)) systems.sort() return systems
team-phoenix/Phoenix
[ 373, 39, 373, 140, 1403229704 ]
def phoenixSystems(self): return OrderedDict(sorted(self.phoenixSystemDatabase.items(), key=lambda t: t[0]))
team-phoenix/Phoenix
[ 373, 39, 373, 140, 1403229704 ]
def phoenixToOpenVGDB(self, phoenixID): ret = "" try: ret = self.phoenixToOpenVGDBMap[phoenixID] except KeyError: ret = "" return ret
team-phoenix/Phoenix
[ 373, 39, 373, 140, 1403229704 ]
def getOpenVGDBToPhoenixMap(self): return OrderedDict(sorted(self.openVGDBToPhoenixMap.items(), key=lambda t: t[0]))
team-phoenix/Phoenix
[ 373, 39, 373, 140, 1403229704 ]
def __call__(self, parser, namespace, values, option_string=None): print "Official Repository" # Name print "web" # Type (maybe web for web, or anything else for usb) print "http://www.gcw-zero.com/files/upload/opk/" #URL print "official.py --update" #Call for updating the list print "O" #letter to show
theZiz/OPKManager
[ 5, 1, 5, 1, 1387295304 ]
def __call__(self, parser, namespace, values, option_string=None): process = subprocess.Popen('wget --timeout='+str(values[0])+' -qO- http://ziz.gp2x.de/gcw-repos/count.php',stdout=subprocess.PIPE,shell=True) process = subprocess.Popen('wget --timeout='+str(values[0])+' -qO- http://www.gcw-zero.com/downloads',stdout=subprocess.PIPE,shell=True) #process = subprocess.Popen('wget --timeout='+str(values[0])+' -qO- http://ziz.gp2x.de/temp/test.htm',stdout=subprocess.PIPE,shell=True) #process = subprocess.Popen('cat downloads',stdout=subprocess.PIPE,shell=True) output = process.stdout.read().split('<div class="downloads_overview">') for output_part in output: part = output_part.split('\n') line_number = 0; not_found = 1; while (line_number < len(part)): if (part[line_number].strip().startswith('<span class="downloads_title">')): not_found = 0; break; line_number += 1; if not_found: continue; program_name_description = part[line_number]; name = program_name_description.split('>')[1].split('<')[0]; if (name == ""): continue line_number = 0; not_found = 1; while (line_number < len(part)): if (part[line_number].strip().startswith('<a class="downloads_link"')): not_found = 0; break; line_number += 1; if not_found: continue; filename = part[line_number].split('href="file.php?file=')[1].split('">')[0]; print "["+name+"]" description = program_name_description.split('>')[3]; print "description: "+description print "filename: " + filename l = len(part) found_version = 0 found_image = 0 found_long = 0; for i in range(0,l-1): if string.find(part[i],'Publication Date') != -1: version = part[i+1] version = version.split('>')[1] version = version.split('<')[0] t = time.strptime(version,"%A, %d %b %Y") print "version: " + str(calendar.timegm(t)) #NEEDED! found_version = 1 if string.find(part[i],'<div class="downloads_preview"') != -1: image = part[i]; image = image.split("background-image: url('")[1].split("');")[0]; print "image_url: http://www.gcw-zero.com/" + image if string.find(part[i],'<p class="more fade">') != -1: long_description = part[i]; long_description = long_description.split('<p class="more fade">')[1].split("</p>")[0]; long_description = long_description.replace('<br /> ','\\n') long_description = long_description.split('>') sys.stdout.write("long_description: ") for long_description_part in long_description: sys.stdout.write(long_description_part.split('<')[0]) sys.stdout.write('\n') found_long = 1 if (found_version and found_image and found_long): break print ""
theZiz/OPKManager
[ 5, 1, 5, 1, 1387295304 ]
def define_tables(cls, metadata): Table( "some_table", metadata, Column("id", Integer, primary_key=True), Column("data", String(100)), )
gltn/stdm
[ 26, 29, 26, 55, 1401777923 ]
def insert_data(cls, connection): connection.execute( cls.tables.some_table.insert(), [ {"id": 1, "data": "collate data1"}, {"id": 2, "data": "collate data2"}, ], )
gltn/stdm
[ 26, 29, 26, 55, 1401777923 ]
def test_collate_order_by(self): collation = testing.requires.get_order_by_collation(testing.config) self._assert_result( select([self.tables.some_table]).order_by( self.tables.some_table.c.data.collate(collation).asc() ), [(1, "collate data1"), (2, "collate data2")], )
gltn/stdm
[ 26, 29, 26, 55, 1401777923 ]
def define_tables(cls, metadata): Table( "some_table", metadata, Column("id", Integer, primary_key=True), Column("x", Integer), Column("y", Integer), Column("q", String(50)), Column("p", String(50)), )
gltn/stdm
[ 26, 29, 26, 55, 1401777923 ]
def insert_data(cls, connection): connection.execute( cls.tables.some_table.insert(), [ {"id": 1, "x": 1, "y": 2, "q": "q1", "p": "p3"}, {"id": 2, "x": 2, "y": 3, "q": "q2", "p": "p2"}, {"id": 3, "x": 3, "y": 4, "q": "q3", "p": "p1"}, ], )
gltn/stdm
[ 26, 29, 26, 55, 1401777923 ]
def test_plain(self): table = self.tables.some_table lx = table.c.x.label("lx") self._assert_result(select([lx]).order_by(lx), [(1,), (2,), (3,)])
gltn/stdm
[ 26, 29, 26, 55, 1401777923 ]
def test_composed_multiple(self): table = self.tables.some_table lx = (table.c.x + table.c.y).label("lx") ly = (func.lower(table.c.q) + table.c.p).label("ly") self._assert_result( select([lx, ly]).order_by(lx, ly.desc()), [(3, util.u("q1p3")), (5, util.u("q2p2")), (7, util.u("q3p1"))], )
gltn/stdm
[ 26, 29, 26, 55, 1401777923 ]
def test_composed_int_desc(self): table = self.tables.some_table lx = (table.c.x + table.c.y).label("lx") self._assert_result( select([lx]).order_by(lx.desc()), [(7,), (5,), (3,)] )
gltn/stdm
[ 26, 29, 26, 55, 1401777923 ]
def test_group_by_composed(self): table = self.tables.some_table expr = (table.c.x + table.c.y).label("lx") stmt = ( select([func.count(table.c.id), expr]) .group_by(expr) .order_by(expr) ) self._assert_result(stmt, [(1, 3), (1, 5), (1, 7)])
gltn/stdm
[ 26, 29, 26, 55, 1401777923 ]
def define_tables(cls, metadata): Table( "some_table", metadata, Column("id", Integer, primary_key=True), Column("x", Integer), Column("y", Integer), )
gltn/stdm
[ 26, 29, 26, 55, 1401777923 ]
def insert_data(cls, connection): connection.execute( cls.tables.some_table.insert(), [ {"id": 1, "x": 1, "y": 2}, {"id": 2, "x": 2, "y": 3}, {"id": 3, "x": 3, "y": 4}, {"id": 4, "x": 4, "y": 5}, ], )
gltn/stdm
[ 26, 29, 26, 55, 1401777923 ]
def test_simple_limit(self): table = self.tables.some_table self._assert_result( select([table]).order_by(table.c.id).limit(2), [(1, 1, 2), (2, 2, 3)], )
gltn/stdm
[ 26, 29, 26, 55, 1401777923 ]
def test_simple_offset(self): table = self.tables.some_table self._assert_result( select([table]).order_by(table.c.id).offset(2), [(3, 3, 4), (4, 4, 5)], )
gltn/stdm
[ 26, 29, 26, 55, 1401777923 ]
def test_simple_limit_offset(self): table = self.tables.some_table self._assert_result( select([table]).order_by(table.c.id).limit(2).offset(1), [(2, 2, 3), (3, 3, 4)], )
gltn/stdm
[ 26, 29, 26, 55, 1401777923 ]
def test_limit_offset_nobinds(self): """test that 'literal binds' mode works - no bound params.""" table = self.tables.some_table stmt = select([table]).order_by(table.c.id).limit(2).offset(1) sql = stmt.compile( dialect=config.db.dialect, compile_kwargs={"literal_binds": True} ) sql = str(sql) self._assert_result(sql, [(2, 2, 3), (3, 3, 4)])
gltn/stdm
[ 26, 29, 26, 55, 1401777923 ]
def test_bound_limit(self): table = self.tables.some_table self._assert_result( select([table]).order_by(table.c.id).limit(bindparam("l")), [(1, 1, 2), (2, 2, 3)], params={"l": 2}, )
gltn/stdm
[ 26, 29, 26, 55, 1401777923 ]
def test_bound_offset(self): table = self.tables.some_table self._assert_result( select([table]).order_by(table.c.id).offset(bindparam("o")), [(3, 3, 4), (4, 4, 5)], params={"o": 2}, )
gltn/stdm
[ 26, 29, 26, 55, 1401777923 ]
def test_bound_limit_offset(self): table = self.tables.some_table self._assert_result( select([table]) .order_by(table.c.id) .limit(bindparam("l")) .offset(bindparam("o")), [(2, 2, 3), (3, 3, 4)], params={"l": 2, "o": 1}, )
gltn/stdm
[ 26, 29, 26, 55, 1401777923 ]
def define_tables(cls, metadata): Table( "some_table", metadata, Column("id", Integer, primary_key=True), Column("x", Integer), Column("y", Integer), )
gltn/stdm
[ 26, 29, 26, 55, 1401777923 ]
def insert_data(cls, connection): connection.execute( cls.tables.some_table.insert(), [ {"id": 1, "x": 1, "y": 2}, {"id": 2, "x": 2, "y": 3}, {"id": 3, "x": 3, "y": 4}, {"id": 4, "x": 4, "y": 5}, ], )
gltn/stdm
[ 26, 29, 26, 55, 1401777923 ]
def test_plain_union(self): table = self.tables.some_table s1 = select([table]).where(table.c.id == 2) s2 = select([table]).where(table.c.id == 3) u1 = union(s1, s2) self._assert_result(u1.order_by(u1.c.id), [(2, 2, 3), (3, 3, 4)])
gltn/stdm
[ 26, 29, 26, 55, 1401777923 ]
def test_limit_offset_selectable_in_unions(self): table = self.tables.some_table s1 = ( select([table]) .where(table.c.id == 2) .limit(1) .order_by(table.c.id) ) s2 = ( select([table]) .where(table.c.id == 3) .limit(1) .order_by(table.c.id) ) u1 = union(s1, s2).limit(2) self._assert_result(u1.order_by(u1.c.id), [(2, 2, 3), (3, 3, 4)])
gltn/stdm
[ 26, 29, 26, 55, 1401777923 ]
def test_order_by_selectable_in_unions(self): table = self.tables.some_table s1 = select([table]).where(table.c.id == 2).order_by(table.c.id) s2 = select([table]).where(table.c.id == 3).order_by(table.c.id) u1 = union(s1, s2).limit(2) self._assert_result(u1.order_by(u1.c.id), [(2, 2, 3), (3, 3, 4)])
gltn/stdm
[ 26, 29, 26, 55, 1401777923 ]
def test_limit_offset_in_unions_from_alias(self): table = self.tables.some_table s1 = ( select([table]) .where(table.c.id == 2) .limit(1) .order_by(table.c.id) ) s2 = ( select([table]) .where(table.c.id == 3) .limit(1) .order_by(table.c.id) ) # this necessarily has double parens u1 = union(s1, s2).alias() self._assert_result( u1.select().limit(2).order_by(u1.c.id), [(2, 2, 3), (3, 3, 4)] )
gltn/stdm
[ 26, 29, 26, 55, 1401777923 ]
def define_tables(cls, metadata): Table( "some_table", metadata, Column("id", Integer, primary_key=True), Column("x", Integer), Column("y", Integer), Column("z", String(50)), )
gltn/stdm
[ 26, 29, 26, 55, 1401777923 ]
def insert_data(cls, connection): connection.execute( cls.tables.some_table.insert(), [ {"id": 1, "x": 1, "y": 2, "z": "z1"}, {"id": 2, "x": 2, "y": 3, "z": "z2"}, {"id": 3, "x": 3, "y": 4, "z": "z3"}, {"id": 4, "x": 4, "y": 5, "z": "z4"}, ], )
gltn/stdm
[ 26, 29, 26, 55, 1401777923 ]
def test_multiple_empty_sets(self): # test that any anonymous aliasing used by the dialect # is fine with duplicates table = self.tables.some_table stmt = ( select([table.c.id]) .where(table.c.x.in_(bindparam("q", expanding=True))) .where(table.c.y.in_(bindparam("p", expanding=True))) .order_by(table.c.id) ) self._assert_result(stmt, [], params={"q": [], "p": []})
gltn/stdm
[ 26, 29, 26, 55, 1401777923 ]