code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def setup_dns(endpoint):
print("Setting up DNS...")
yass = Yass(CWD)
target = endpoint.lower()
sitename = yass.sitename
if not sitename:
raise ValueError("Missing site name")
endpoint = yass.config.get("hosting.%s" % target)
if not endpoint:
raise ValueError(
"%s ... | Setup site domain to route to static site |
def unhide_selected():
hidden_state = current_representation().hidden_state
selection_state = current_representation().selection_state
res = {}
for k in selection_state:
visible = hidden_state[k].invert()
visible_and_selected = visible.add(selection_state[k])
res[k] = visible_and... | Unhide the selected objects |
def num_discarded(self):
if not self._data:
return 0
n = 0
while n < len(self._data):
if not isinstance(self._data[n], _TensorValueDiscarded):
break
n += 1
return n | Get the number of values discarded due to exceeding both limits. |
def finalize(self):
self.model().sigItemChanged.disconnect(self.repoTreeItemChanged)
selectionModel = self.selectionModel()
selectionModel.currentChanged.disconnect(self.currentItemChanged) | Disconnects signals and frees resources |
def _flatten_list(self, data):
'Flattens nested lists into strings.'
if data is None:
return ''
if isinstance(data, types.StringTypes):
return data
elif isinstance(data, (list, tuple)):
return '\n'.join(self._flatten_list(x) for x in data) | Flattens nested lists into strings. |
def build(self, n, vec):
for i in range(-self.maxDisplacement, self.maxDisplacement+1):
next = vec + [i]
if n == 1:
print '{:>5}\t'.format(next), " = ",
printSequence(self.encodeMotorInput(next))
else:
self.build(n-1, next) | Recursive function to help print motor coding scheme. |
def eval(e, amplitude, e_0, alpha):
xx = e / e_0
return amplitude * xx ** (-alpha) | One dimensional power law model function |
def _classify_move_register(self, regs_init, regs_fini, mem_fini, written_regs, read_regs):
matches = []
regs_init_inv = self._invert_dictionary(regs_init)
for dst_reg, dst_val in regs_fini.items():
if dst_reg not in written_regs:
continue
for src_reg in r... | Classify move-register gadgets. |
def _get_url_hashes(path):
urls = _read_text_file(path)
def url_hash(u):
h = hashlib.sha1()
try:
u = u.encode('utf-8')
except UnicodeDecodeError:
logging.error('Cannot hash url: %s', u)
h.update(u)
return h.hexdigest()
return {url_hash(u): True for u in urls} | Get hashes of urls in file. |
def save_objective_bank(self, objective_bank_form, *args, **kwargs):
if objective_bank_form.is_for_update():
return self.update_objective_bank(objective_bank_form, *args, **kwargs)
else:
return self.create_objective_bank(objective_bank_form, *args, **kwargs) | Pass through to provider ObjectiveBankAdminSession.update_objective_bank |
def keys_with_value(dictionary, value):
"Returns a subset of keys from the dict with the value supplied."
subset = [key for key in dictionary if dictionary[key] == value]
return subset | Returns a subset of keys from the dict with the value supplied. |
def freeze(self):
self.app.disable()
self.clear.disable()
self.nod.disable()
self.led.disable()
self.dummy.disable()
self.readSpeed.disable()
self.expose.disable()
self.number.disable()
self.wframe.disable(everything=True)
self.nmult.disabl... | Freeze all settings so they cannot be altered |
def cleanup(self):
self._processing_stop = True
self._wakeup_processing_thread()
self._processing_stopped_event.wait(3) | Stop backgroud thread and cleanup resources |
def select(self, names):
return PolicyCollection(
[p for p in self.policies if p.name in names], self.options) | return the named subset of policies |
def builds(self, request, pk=None):
builds = self.get_object().builds.prefetch_related('test_runs').order_by('-datetime')
page = self.paginate_queryset(builds)
serializer = BuildSerializer(page, many=True, context={'request': request})
return self.get_paginated_response(serializer.data) | List of builds for the current project. |
def _check_satisfy_constraints(self, label, xmin, ymin, xmax, ymax, width, height):
if (xmax - xmin) * (ymax - ymin) < 2:
return False
x1 = float(xmin) / width
y1 = float(ymin) / height
x2 = float(xmax) / width
y2 = float(ymax) / height
object_areas = self._ca... | Check if constrains are satisfied |
def load_pickle(filename):
try:
if pd:
return pd.read_pickle(filename), None
else:
with open(filename, 'rb') as fid:
data = pickle.load(fid)
return data, None
except Exception as err:
return None, str(err) | Load a pickle file as a dictionary |
def _trim_files(files, trim_output):
count = 100
if not isinstance(trim_output, bool):
count = trim_output
if not(isinstance(trim_output, bool) and trim_output is False) and len(files) > count:
files = files[:count]
files.append("List trimmed after {0} files.".format(count))
retu... | Trim the file list for output. |
def _parse_script(list, line, line_iter):
ifIdx = 0
while (True):
line = next(line_iter)
if line.startswith("fi"):
if ifIdx == 0:
return
ifIdx -= 1
elif line.startswith("if"):
ifIdx += 1 | Eliminate any bash script contained in the grub v2 configuration |
def bind_addr(self, value):
if isinstance(value, tuple) and value[0] in ('', None):
raise ValueError(
"Host values of '' or None are not allowed. "
"Use '0.0.0.0' (IPv4) or '::' (IPv6) instead "
'to listen on all active interfaces.',
)
... | Set the interface on which to listen for connections. |
def on_terminate(func):
def exit_function(*args):
func()
exit(0)
signal.signal(signal.SIGTERM, exit_function) | Register a signal handler to execute when Maltego forcibly terminates the transform. |
def add_ingredients(self):
for ingredient in self.recipe._cauldron.values():
if hasattr(ingredient.meta, 'anonymizer'):
anonymizer = ingredient.meta.anonymizer
if isinstance(anonymizer, basestring):
kwargs = {}
anonymizer_locale... | Put the anonymizers in the last position of formatters |
def interact(self):
lines = ""
for line in self.read():
lines += line
try:
self.eval(lines)
except ValueError:
pass
except KeyboardInterrupt as e:
raise e
except:
self.terminal.err... | Get a command from the user and respond to it. |
async def settings(dev: Device):
settings_tree = await dev.get_settings()
for module in settings_tree:
await traverse_settings(dev, module.usage, module.settings) | Print out all possible settings. |
def ms_cutlo(self, viewer, event, data_x, data_y):
if not self.cancut:
return True
x, y = self.get_win_xy(viewer)
if event.state == 'move':
self._cutlow_xy(viewer, x, y)
elif event.state == 'down':
self._start_x, self._start_y = x, y
self._... | An interactive way to set the low cut level. |
def ext_pillar(hyper_id, pillar, name, key):
vk = salt.utils.virt.VirtKey(hyper_id, name, __opts__)
ok = vk.accept(key)
pillar['virtkey'] = {name: ok}
return {} | Accept the key for the VM on the hyper, if authorized. |
def upgrade(self, flag):
for pkg in self.binary:
try:
subprocess.call("upgradepkg {0} {1}".format(flag, pkg),
shell=True)
check = pkg[:-4].split("/")[-1]
if os.path.isfile(self.meta.pkg_path + check):
... | Upgrade Slackware binary packages with new |
def register_value_proxy(namespace, value_proxy, help_text):
namespace.register_proxy(value_proxy)
config.config_help.add(
value_proxy.config_key, value_proxy.validator, value_proxy.default,
namespace.get_name(), help_text) | Register a value proxy with the namespace, and add the help_text. |
def OnMouse(self, event):
self.SetGridCursor(event.Row, event.Col)
self.EnableCellEditControl(True)
event.Skip() | Reduces clicks to enter an edit control |
def oauth_logout_handler(sender_app, user=None):
oauth = current_app.extensions['oauthlib.client']
for remote in oauth.remote_apps.values():
token_delete(remote)
db.session.commit() | Remove all access tokens from session on logout. |
def saveLogs(self, filename) :
f = open(filename, 'wb')
cPickle.dump(self.logs, f)
f.close() | dumps logs into a nice pickle |
def __call_stream(self, uri, params=None, method="get"):
try:
resp = self.__get_response(uri, params, method, True)
assert resp.ok
except AssertionError:
raise BadRequest(resp.status_code)
except Exception as e:
log.error("Bad response: {}".format(... | Returns an stream response |
def cena_tau(imt, mag, params):
if imt.name == "PGV":
C = params["PGV"]
else:
C = params["SA"]
if mag > 6.5:
return C["tau3"]
elif (mag > 5.5) and (mag <= 6.5):
return ITPL(mag, C["tau3"], C["tau2"], 5.5, 1.0)
elif (mag > 5.0) and (mag <= 5.5):
return ITPL(mag... | Returns the inter-event standard deviation, tau, for the CENA case |
def gather_facts_list(self, file):
facts = []
contents = utils.file_to_string(os.path.join(self.paths["role"],
file))
contents = re.sub(r"\s+", "", contents)
matches = self.regex_facts.findall(contents)
for match in matches:
fac... | Return a list of facts. |
def WSGIHandler(self):
sdm = werkzeug_wsgi.SharedDataMiddleware(self, {
"/": config.CONFIG["AdminUI.document_root"],
})
return werkzeug_wsgi.DispatcherMiddleware(self, {
"/static": sdm,
}) | Returns GRR's WSGI handler. |
def add_context(
self,
name,
cluster_name=None,
user_name=None,
namespace_name=None,
**attrs
):
if self.context_exists(name):
raise KubeConfError("context with the given name already exists.")
contexts = self.get_contexts()
new_... | Add a context to config. |
def _extract_rev(self, line1, line2):
try:
if line1.startswith('--- ') and line2.startswith('+++ '):
l1 = line1[4:].split(None, 1)
old_filename = l1[0].lstrip('a/') if len(l1) >= 1 else None
old_rev = l1[1] if len(l1) == 2 else 'old'
l2... | Extract the filename and revision hint from a line. |
def _thread_init(cls):
if not hasattr(cls._local, '_in_order_futures'):
cls._local._in_order_futures = set()
cls._local._activated = False | Ensure thread local is initialized. |
def build_model_from_xy(self, x_values, y_values):
self.init_ace(x_values, y_values)
self.run_ace()
self.build_interpolators() | Construct the model and perform regressions based on x, y data. |
def form_valid(self, form):
form.send_email(to=self.to_addr)
return super(EmailView, self).form_valid(form) | Praise be, someone has spammed us. |
def home(request):
polls = []
for row in curDB.execute('SELECT id, title FROM Poll ORDER BY title'):
polls.append({'id': row[0], 'name': row[1]})
return {'polls': polls} | Show the home page. Send the list of polls |
def stop_all_tensorboards():
for process in Process.instances:
print("Process '%s', running %d" % (process.command[0],
process.is_running()))
if process.is_running() and process.command[0] == "tensorboard":
process.terminate() | Terminate all TensorBoard instances. |
def tilequeue_stuck_tiles(cfg, peripherals):
store = _make_store(cfg)
format = lookup_format_by_extension('zip')
layer = 'all'
assert peripherals.toi, 'Missing toi'
toi = peripherals.toi.fetch_tiles_of_interest()
for coord in store.list_tiles(format, layer):
coord_int = coord_marshall_in... | Check which files exist on s3 but are not in toi. |
def addDataset(self):
self._openRepo()
dataset = datasets.Dataset(self._args.datasetName)
dataset.setDescription(self._args.description)
dataset.setAttributes(json.loads(self._args.attributes))
self._updateRepo(self._repo.insertDataset, dataset) | Adds a new dataset into this repo. |
def template_thinning(self, inj_filter_rejector):
if not inj_filter_rejector.enabled or \
inj_filter_rejector.chirp_time_window is None:
return
injection_parameters = inj_filter_rejector.injection_params.table
fref = inj_filter_rejector.f_lower
threshold = inj... | Remove templates from bank that are far from all injections. |
def _get_env(self):
env = {}
for k, v in os.environ.items():
k = k.decode() if isinstance(k, bytes) else k
v = v.decode() if isinstance(v, bytes) else v
env[k] = v
return list(env.items()) | loads the environment variables as unicode if ascii |
def cleanup(self):
for actor in self.actors:
if actor.skip:
continue
actor.cleanup()
super(ActorHandler, self).cleanup() | Destructive finishing up after execution stopped. |
def fetch(table, cols="*", where=(), group="", order=(), limit=(), **kwargs):
return select(table, cols, where, group, order, limit, **kwargs).fetchall() | Convenience wrapper for database SELECT and fetch all. |
def _check_pkgin():
ppath = salt.utils.path.which('pkgin')
if ppath is None:
try:
localbase = __salt__['cmd.run'](
'pkg_info -Q LOCALBASE pkgin',
output_loglevel='trace'
)
if localbase is not None:
ppath = '{0}/bin/pkgin'... | Looks to see if pkgin is present on the system, return full path |
def update(self):
with self._lock:
devices = self._request_devices(MINUT_DEVICES_URL, 'devices')
if devices:
self._state = {
device['device_id']: device
for device in devices
}
_LOGGER.debug("Found de... | Update all devices from server. |
def tags(self, extra_params=None):
params = {
'per_page': settings.MAX_PER_PAGE,
}
if extra_params:
params.update(extra_params)
return self.api._get_json(
Tag,
space=self,
rel_path=self.space._build_rel_path(
'ti... | All Tags in this Ticket |
def bulk_history_create(self, objs, batch_size=None):
historical_instances = [
self.model(
history_date=getattr(instance, "_history_date", now()),
history_user=getattr(instance, "_history_user", None),
history_change_reason=getattr(instance, "changeRea... | Bulk create the history for the objects specified by objs |
def from_wc(cls, wc):
return cls(wcdict=wc.dict, scale=wc.scale, eft=wc.eft, basis=wc.basis) | Return a `Wilson` instance initialized by a `wcxf.WC` instance |
def drain(self):
data = self._stream.getvalue()
if len(data):
yield from self._protocol.send(data)
self._stream = io.BytesIO(b'') | Let the write buffer of the underlying transport a chance to be flushed. |
def defaultMachine(use_rpm_default=True):
if use_rpm_default:
try:
rmachine = subprocess.check_output(['rpm', '--eval=%_target_cpu'], shell=False).rstrip()
rmachine = SCons.Util.to_str(rmachine)
except Exception as e:
return defaultMachine(False)
else:
... | Return the canonicalized machine name. |
def cache(self, con):
try:
if self._reset == 2:
con.reset()
else:
if self._reset or con._transaction:
try:
con.rollback()
except Exception:
pass
self._cache... | Put a connection back into the pool cache. |
def exchange_code_for_token(self, authorization_code):
if authorization_code not in self.authorization_codes:
raise InvalidAuthorizationCode('{} unknown'.format(authorization_code))
authz_info = self.authorization_codes[authorization_code]
if authz_info['used']:
logger.de... | Exchanges an authorization code for an access token. |
def scan_path(executable="mongod"):
for path in os.environ.get("PATH", "").split(":"):
path = os.path.abspath(path)
executable_path = os.path.join(path, executable)
if os.path.exists(executable_path):
return executable_path | Scan the path for a binary. |
def polygon_from_points(points):
polygon = []
for pair in points.split(" "):
x_y = pair.split(",")
polygon.append([float(x_y[0]), float(x_y[1])])
return polygon | Constructs a numpy-compatible polygon from a page representation. |
def INIT_LIST_EXPR(self, cursor):
values = [self.parse_cursor(child)
for child in list(cursor.get_children())]
return values | Returns a list of literal values. |
def unregister_signal_handlers():
signal.signal(SIGNAL_STACKTRACE, signal.SIG_IGN)
signal.signal(SIGNAL_PDB, signal.SIG_IGN) | set signal handlers to default |
def reset(self):
self.scene = cocos.scene.Scene()
self.z = 0
palette = config.settings['view']['palette']
r, g, b = palette['bg']
self.scene.add(cocos.layer.ColorLayer(r, g, b, 255), z=self.z)
self.z += 1
message_layer = MessageLayer()
self.scene.add(messa... | Attach a new engine to director |
def redirect_stdout(self):
self.hijacked_stdout = sys.stdout
self.hijacked_stderr = sys.stderr
sys.stdout = open(self.hitch_dir.driverout(), "ab", 0)
sys.stderr = open(self.hitch_dir.drivererr(), "ab", 0) | Redirect stdout to file so that it can be tailed and aggregated with the other logs. |
def _MigrateArtifact(artifact):
name = Text(artifact.name)
try:
logging.info("Migating %s", name)
data_store.REL_DB.WriteArtifact(artifact)
logging.info(" Wrote %s", name)
except db.DuplicatedArtifactError:
logging.info(" Skipped %s, because artifact already exists.", name) | Migrate one Artifact from AFF4 to REL_DB. |
def scan_line(self, line, regex):
return bool(re.search(regex, line, flags=re.IGNORECASE)) | Checks if regex is in line, returns bool |
def pprint(self):
items = sorted(self.items())
return u"\n".join(u"%s=%s" % (k, v.pprint()) for k, v in items) | Return tag key=value pairs in a human-readable format. |
def _ufunc_wrapper(ufunc, name=None):
if not isinstance(ufunc, np.ufunc):
raise TypeError('{} is not a ufunc'.format(ufunc))
ufunc_name = ufunc.__name__
ma_ufunc = getattr(np.ma, ufunc_name, None)
if ufunc.nin == 2 and ufunc.nout == 1:
func = _dual_input_fn_wrapper('np.{}'.format(ufunc_n... | A function to generate the top level biggus ufunc wrappers. |
def parse(self, text):
tags, results = [], []
text = self.re_tag.sub(lambda m: self.sub_tag(m, tags, results), text)
if self.strict and tags:
markup = "%s%s%s" % (self.tag_sep[0], tags.pop(0), self.tag_sep[1])
raise MismatchedTag('opening tag "%s" has no corresponding clo... | Return a string with markup tags converted to ansi-escape sequences. |
def remove(self):
if self.rc_file:
self.rc_file.close()
if self.env_file:
self.env_file.close()
shutil.rmtree(self.root_dir) | Removes the sprinter directory, if it exists |
def count_cookies(self, domain):
cookies = self.cookie_jar._cookies
if domain in cookies:
return sum(
[len(cookie) for cookie in cookies[domain].values()]
)
else:
return 0 | Return the number of cookies for the given domain. |
def generate_subplots(self):
_, axes = plt.subplots(len(self.models), sharex=True, sharey=True)
return axes | Generates the subplots for the number of given models. |
def _count_extra_actions(self, game_image):
proportional = self._bonus_tools['extra_action_region']
t, l, b, r = proportional.region_in(game_image)
token_region = game_image[t:b, l:r]
game_h, game_w = game_image.shape[0:2]
token_h = int(round(game_h * 27.0 / 960))
token_w... | Count the number of extra actions for player in this turn. |
def make_response(obj):
if obj is None:
raise TypeError("Handler return value cannot be None.")
if isinstance(obj, Response):
return obj
return Response(200, body=obj) | Try to coerce an object into a Response object. |
def _rewrite_error_path(self, error, offset=0):
if error.is_logic_error:
self._rewrite_logic_error_path(error, offset)
elif error.is_group_error:
self._rewrite_group_error_path(error, offset) | Recursively rewrites the error path to correctly represent logic errors |
def draw_lines():
r = numpy.random.randn(200)
fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.plot(r)
ax.grid(True)
pyplot.savefig(lines_filename) | Draws a line between a set of random values |
def terminate(self, arg):
instance = self.get(arg)
with self.msg("Terminating %s (%s): " % (instance.name, instance.id)):
instance.rename("old-%s" % instance.name)
instance.terminate()
while instance.state != 'terminated':
time.sleep(5)
... | Terminate instance with given EC2 ID or nametag. |
def _read(self):
stream = self.path.read_text()
data = yaml.load(stream)
return data | Read the kube config file. |
def remove(community_id, record_id):
c = Community.get(community_id)
assert c is not None
c.remove_record(record_id)
db.session.commit()
RecordIndexer().index_by_id(record_id) | Remove a record from community. |
def concatenate_json(source_folder, destination_file):
matches = []
for root, dirnames, filenames in os.walk(source_folder):
for filename in fnmatch.filter(filenames, '*.json'):
matches.append(os.path.join(root, filename))
with open(destination_file, "wb") as f:
f.write("[\n")
... | Concatenate all the json files in a folder to one big JSON file. |
def _load_pil_image(self, filename):
self._channel_data = []
self._original_channel_data = []
im = Image.open(filename)
self._image = ImageOps.grayscale(im)
im.load()
file_data = np.asarray(im, float)
file_data = file_data / file_data.max()
if( len(file_da... | Load image using PIL. |
def main(search, query):
url = search.search(query)
print(url)
search.open_page(url) | main function that does the search |
def close(self):
try:
if not self._closed and not self._owned:
self._dispose()
finally:
self.detach() | Close this object and do any required clean-up actions. |
def _compute_site_scaling(self, C, vs30):
site_term = np.zeros(len(vs30), dtype=float)
site_term[vs30 < 760.0] = C["e"]
return site_term | Returns the site scaling term as a simple coefficient |
def _extract_axes(self, data, axes, **kwargs):
return [self._extract_axis(self, data, axis=i, **kwargs)
for i, a in enumerate(axes)] | Return a list of the axis indices. |
def new(
name,
bucket,
timeout,
memory,
description,
subnet_ids,
security_group_ids
):
config = {}
if timeout:
config['timeout'] = timeout
if memory:
config['memory'] = memory
if description:
config['description'] = description
if subnet_ids:
... | Create a new lambda project |
def show_osm_downloader(self):
from safe.gui.tools.osm_downloader_dialog import OsmDownloaderDialog
dialog = OsmDownloaderDialog(self.iface.mainWindow(), self.iface)
dialog.setAttribute(Qt.WA_DeleteOnClose, True)
dialog.show() | Show the OSM buildings downloader dialog. |
def hset(self, key, field, value):
return self.execute(b'HSET', key, field, value) | Set the string value of a hash field. |
def read_recipe(self, filename):
Global.LOGGER.debug(f"reading recipe {filename}")
if not os.path.isfile(filename):
Global.LOGGER.error(filename + " recipe not found, skipping")
return
config = configparser.ConfigParser(allow_no_value=True,
... | Read a recipe file from disk |
def uppercase_percent_encoding(text):
if '%' not in text:
return text
return re.sub(
r'%[a-f0-9][a-f0-9]',
lambda match: match.group(0).upper(),
text) | Uppercases percent-encoded sequences. |
def authenticate(self):
if self.apiKey:
return
loginResponse = self._curl_bitmex(
api="user/login",
postdict={'email': self.login, 'password': self.password, 'token': self.otpToken})
self.token = loginResponse['id']
self.session.headers.update({'access... | Set BitMEX authentication information. |
def subject(self):
if self.application_name and self.application_version:
return 'Crash Report - {name} (v{version})'.format(name=self.application_name,
version=self.application_version)
else:
return 'Crash Report' | Return a string to be used as the email subject line. |
def _format_summary_node(self, task_class):
modulename = task_class.__module__
classname = task_class.__name__
nodes = []
nodes.append(
self._format_class_nodes(task_class))
nodes.append(
self._format_config_nodes(modulename, classname)
)
m... | Format a section node containg a summary of a Task class's key APIs. |
def _get_output_cwl_keys(fnargs):
for d in utils.flatten(fnargs):
if isinstance(d, dict) and d.get("output_cwl_keys"):
return d["output_cwl_keys"]
raise ValueError("Did not find output_cwl_keys in %s" % (pprint.pformat(fnargs))) | Retrieve output_cwl_keys from potentially nested input arguments. |
def beginningPage(R):
p = R['PG']
if p.startswith('suppl '):
p = p[6:]
return p.split(' ')[0].split('-')[0].replace(';', '') | As pages may not be given as numbers this is the most accurate this function can be |
def agent_list(self, deep_sorted=False):
ag_list = []
for ag_name in self._agent_order:
ag_attr = getattr(self, ag_name)
if isinstance(ag_attr, Concept) or ag_attr is None:
ag_list.append(ag_attr)
elif isinstance(ag_attr, list):
if not ... | Get the canonicallized agent list. |
def read(config_values):
if not config_values:
raise RheaError('Cannot read config_value: `{}`'.format(config_values))
config_values = to_list(config_values)
config = {}
for config_value in config_values:
config_value = ConfigSpec.get_from(value=config_value)
config_value.check_t... | Reads an ordered list of configuration values and deep merge the values in reverse order. |
def resize_state_port_meta(state_m, factor, gaphas_editor=True):
if not gaphas_editor and isinstance(state_m, ContainerStateModel):
port_models = state_m.input_data_ports[:] + state_m.output_data_ports[:] + state_m.scoped_variables[:]
else:
port_models = state_m.input_data_ports[:] + state_m.out... | Resize data and logical ports relative positions |
def tarbell_switch(command, args):
with ensure_settings(command, args) as settings:
projects_path = settings.config.get("projects_path")
if not projects_path:
show_error("{0} does not exist".format(projects_path))
sys.exit()
project = args.get(0)
args.remove(p... | Switch to a project. |
def standardize_shapes(features, batch_size=None):
for fname in ["inputs", "targets"]:
if fname not in features:
continue
f = features[fname]
while len(f.get_shape()) < 4:
f = tf.expand_dims(f, axis=-1)
features[fname] = f
if batch_size:
for _, t in six.iteritems(features):
sha... | Set the right shapes for the features. |
def _merge_buckets(self, bucket_list: Set[DependenceBucket]) -> DependenceBucket:
variables = []
conditions = []
for bucket in bucket_list:
self.buckets.remove(bucket)
variables += bucket.variables
conditions += bucket.conditions
new_bucket = Dependenc... | Merges the buckets in bucket list |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.