_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q268600 | _exc_to_net | test | def _exc_to_net(param1, success):
""" translate http code to net code. if accertion failed, set net code to 314 """
if len(param1) <= 3:
# FIXME: we're unable to use better logic here, because we should support non-http codes
# but, we should look for core.util.HTTP or some other common logic
... | python | {
"resource": ""
} |
q268601 | _exc_to_http | test | def _exc_to_http(param1):
""" translate exception str to http code"""
if len(param1) <= 3:
try:
int(param1)
except BaseException:
logger.error(
"JMeter wrote some strange data into codes column: %s", param1)
else:
return int(param1)
... | python | {
"resource": ""
} |
q268602 | PhantomConfig.read_config | test | def read_config(self):
""" Read phantom tool specific options """
self.threads = self.cfg["threads"] or str(int(multiprocessing.cpu_count() / 2) + 1)
self.phantom_modules_path = self.cfg["phantom_modules_path"]
self.additional_libs = ' '.join(self.cfg["additional_libs"])
... | python | {
"resource": ""
} |
q268603 | PhantomConfig.compose_config | test | def compose_config(self):
""" Generate phantom tool run config """
streams_config = ''
stat_benchmarks = ''
for stream in self.streams:
streams_config += stream.compose_config()
if not stream.is_main:
stat_benchmarks += " " + "benchma... | python | {
"resource": ""
} |
q268604 | PhantomConfig.get_info | test | def get_info(self):
""" get merged info about phantom conf """
result = copy.copy(self.streams[0])
result.stat_log = self.stat_log
result.steps = []
result.ammo_file = ''
result.rps_schedule = None
result.ammo_count = 0
result.duration = 0
result.... | python | {
"resource": ""
} |
q268605 | StreamConfig.compose_config | test | def compose_config(self):
""" compose benchmark block """
# step file
self.stepper_wrapper.prepare_stepper()
self.stpd = self.stepper_wrapper.stpd
if self.stepper_wrapper.instances:
self.instances = self.stepper_wrapper.instances
if not self.stpd:
... | python | {
"resource": ""
} |
q268606 | log_stdout_stderr | test | def log_stdout_stderr(log, stdout, stderr, comment=""):
"""
This function polls stdout and stderr streams and writes their contents
to log
"""
readable = select.select([stdout], [], [], 0)[0]
if stderr:
exceptional = select.select([stderr], [], [], 0)[0]
else:
exceptional = [... | python | {
"resource": ""
} |
q268607 | expand_time | test | def expand_time(str_time, default_unit='s', multiplier=1):
"""
helper for above functions
"""
parser = re.compile(r'(\d+)([a-zA-Z]*)')
parts = parser.findall(str_time)
result = 0.0
for value, unit in parts:
value = int(value)
unit = unit.lower()
if unit == '':
... | python | {
"resource": ""
} |
q268608 | StepperWrapper.read_config | test | def read_config(self):
''' stepper part of reading options '''
self.log.info("Configuring StepperWrapper...")
self.ammo_file = self.get_option(self.OPTION_AMMOFILE)
self.ammo_type = self.get_option('ammo_type')
if self.ammo_file:
self.ammo_file = os.path.expanduser(se... | python | {
"resource": ""
} |
q268609 | StepperWrapper.prepare_stepper | test | def prepare_stepper(self):
''' Generate test data if necessary '''
def publish_info(stepper_info):
info.status.publish('loadscheme', stepper_info.loadscheme)
info.status.publish('loop_count', stepper_info.loop_count)
info.status.publish('steps', stepper_info.steps)
... | python | {
"resource": ""
} |
q268610 | StepperWrapper.__get_stpd_filename | test | def __get_stpd_filename(self):
''' Choose the name for stepped data file '''
if self.use_caching:
sep = "|"
hasher = hashlib.md5()
hashed_str = "cache version 6" + sep + \
';'.join(self.load_profile.schedule) + sep + str(self.loop_limit)
ha... | python | {
"resource": ""
} |
q268611 | StepperWrapper.__read_cached_options | test | def __read_cached_options(self):
'''
Read stepper info from json
'''
self.log.debug("Reading cached stepper info: %s", self.__si_filename())
with open(self.__si_filename(), 'r') as si_file:
si = info.StepperInfo(**json.load(si_file))
return si | python | {
"resource": ""
} |
q268612 | StepperWrapper.__write_cached_options | test | def __write_cached_options(self, si):
'''
Write stepper info to json
'''
self.log.debug("Saving stepper info: %s", self.__si_filename())
with open(self.__si_filename(), 'w') as si_file:
json.dump(si._asdict(), si_file, indent=4) | python | {
"resource": ""
} |
q268613 | StepperWrapper.__make_stpd_file | test | def __make_stpd_file(self):
''' stpd generation using Stepper class '''
self.log.info("Making stpd-file: %s", self.stpd)
stepper = Stepper(
self.core,
rps_schedule=self.load_profile.schedule if self.load_profile.is_rps() else None,
http_ver=self.http_ver,
... | python | {
"resource": ""
} |
q268614 | create | test | def create(rps_schedule):
"""
Create Load Plan as defined in schedule. Publish info about its duration.
"""
if len(rps_schedule) > 1:
lp = Composite(
[StepFactory.produce(step_config) for step_config in rps_schedule])
else:
lp = StepFactory.produce(rps_schedule[0])
in... | python | {
"resource": ""
} |
q268615 | Line.rps_at | test | def rps_at(self, t):
'''Return rps for second t'''
if 0 <= t <= self.duration:
return self.minrps + \
float(self.maxrps - self.minrps) * t / self.duration
else:
return 0 | python | {
"resource": ""
} |
q268616 | Plugin.execute | test | def execute(self, cmd):
"""
Execute and check exit code
"""
self.log.info("Executing: %s", cmd)
retcode = execute(
cmd, shell=True, poll_period=0.1, catch_out=self.catch_out)[0]
if retcode:
raise RuntimeError("Subprocess returned %s" % retcode)
... | python | {
"resource": ""
} |
q268617 | Decoder.decode_monitoring | test | def decode_monitoring(self, data):
"""
The reason why we have two separate methods for monitoring
and aggregates is a strong difference in incoming data.
"""
points = list()
for second_data in data:
for host, host_data in second_data["data"].iteritems():
... | python | {
"resource": ""
} |
q268618 | Decoder.__make_points_for_label | test | def __make_points_for_label(self, ts, data, label, prefix, gun_stats):
"""x
Make a set of points for `this` label
overall_quantiles, overall_meta, net_codes, proto_codes, histograms
"""
label_points = list()
label_points.extend(
(
# overall q... | python | {
"resource": ""
} |
q268619 | AbstractPlugin.publish | test | def publish(self, key, value):
"""publish value to status"""
self.log.debug(
"Publishing status: %s/%s: %s", self.__class__.__name__, key, value)
self.core.publish(self.__class__.__name__, key, value) | python | {
"resource": ""
} |
q268620 | AbstractCriterion.count_matched_codes | test | def count_matched_codes(codes_regex, codes_dict):
""" helper to aggregate codes by mask """
total = 0
for code, count in codes_dict.items():
if codes_regex.match(str(code)):
total += count
return total | python | {
"resource": ""
} |
q268621 | BFGBase.stop | test | def stop(self):
"""
Say the workers to finish their jobs and quit.
"""
self.quit.set()
# yapf:disable
while sorted([
self.pool[i].is_alive()
for i in xrange(len(self.pool))])[-1]:
time.sleep(1)
# yapf:enable
try:... | python | {
"resource": ""
} |
q268622 | BFGBase._feed | test | def _feed(self):
"""
A feeder that runs in distinct thread in main process.
"""
self.plan = StpdReader(self.stpd_filename)
if self.cached_stpd:
self.plan = list(self.plan)
for task in self.plan:
if self.quit.is_set():
logger.info("S... | python | {
"resource": ""
} |
q268623 | ApiWorker.init_logging | test | def init_logging(self, log_filename="tank.log"):
""" Set up logging """
logger = logging.getLogger('')
self.log_filename = log_filename
self.core.add_artifact_file(self.log_filename)
file_handler = logging.FileHandler(self.log_filename)
file_handler.setLevel(logging.DEBU... | python | {
"resource": ""
} |
q268624 | ApiWorker.__add_user_options | test | def __add_user_options(self):
""" override config options with user specified options"""
if self.options.get('user_options', None):
self.core.apply_shorthand_options(self.options['user_options']) | python | {
"resource": ""
} |
q268625 | ApiWorker.configure | test | def configure(self, options):
""" Make preparations before running Tank """
self.options = options
if self.options.get('lock_dir', None):
self.core.set_option(self.core.SECTION, "lock_dir", self.options['lock_dir'])
if self.options.get('ignore_lock', None):
self.c... | python | {
"resource": ""
} |
q268626 | ApiWorker.__graceful_shutdown | test | def __graceful_shutdown(self):
""" call shutdown routines """
retcode = 1
self.log.info("Trying to shutdown gracefully...")
retcode = self.core.plugins_end_test(retcode)
retcode = self.core.plugins_post_process(retcode)
self.log.info("Done graceful shutdown")
retu... | python | {
"resource": ""
} |
q268627 | TankAggregator._collect_data | test | def _collect_data(self, end=False):
"""
Collect data, cache it and send to listeners
"""
data = get_nowait_from_queue(self.results)
stats = get_nowait_from_queue(self.stats_results)
logger.debug("Data timestamps: %s" % [d.get('ts') for d in data])
logger.debug("St... | python | {
"resource": ""
} |
q268628 | TankAggregator.__notify_listeners | test | def __notify_listeners(self, data, stats):
""" notify all listeners about aggregate data and stats """
for listener in self.listeners:
listener.on_aggregated_data(data, stats) | python | {
"resource": ""
} |
q268629 | get_marker | test | def get_marker(marker_type, enum_ammo=False):
'''
Returns a marker function of the requested marker_type
>>> marker = get_marker('uniq')(__test_missile)
>>> type(marker)
<type 'str'>
>>> len(marker)
32
>>> get_marker('uri')(__test_missile)
'_example_search_hello_help_us'
>>> m... | python | {
"resource": ""
} |
q268630 | parse_duration | test | def parse_duration(duration):
'''
Parse duration string, such as '3h2m3s' into milliseconds
>>> parse_duration('3h2m3s')
10923000
>>> parse_duration('0.3s')
300
>>> parse_duration('5')
5000
'''
_re_token = re.compile("([0-9.]+)([dhms]?)")
def parse_token(time, multiplier)... | python | {
"resource": ""
} |
q268631 | LocalhostClient.start | test | def start(self):
"""Start local agent"""
logger.info('Starting agent on localhost')
args = self.python.split() + [
os.path.join(
self.workdir,
self.AGENT_FILENAME),
'--telegraf',
self.path['TELEGRAF_LOCAL_PATH'],
'--... | python | {
"resource": ""
} |
q268632 | SSHClient.start | test | def start(self):
"""Start remote agent"""
logger.info('Starting agent: %s', self.host)
command = "{python} {agent_path} --telegraf {telegraf_path} --host {host} {kill_old}".format(
python=self.python,
agent_path=os.path.join(
self.path['AGENT_REMOTE_FOLDER... | python | {
"resource": ""
} |
q268633 | Plugin.__discover_jmeter_udp_port | test | def __discover_jmeter_udp_port(self):
"""Searching for line in jmeter.log such as
Waiting for possible shutdown message on port 4445
"""
r = re.compile(self.DISCOVER_PORT_PATTERN)
with open(self.process_stderr.name, 'r') as f:
cnt = 0
while self.process.pi... | python | {
"resource": ""
} |
q268634 | Plugin.__add_jmeter_components | test | def __add_jmeter_components(self, jmx, jtl, variables):
""" Genius idea by Alexey Lavrenyuk """
logger.debug("Original JMX: %s", os.path.realpath(jmx))
with open(jmx, 'r') as src_jmx:
source_lines = src_jmx.readlines()
try:
# In new Jmeter version (3.2 as example... | python | {
"resource": ""
} |
q268635 | Plugin.__terminate | test | def __terminate(self):
"""Gracefull termination of running process"""
if self.__stderr_file:
self.__stderr_file.close()
if not self.__process:
return
waitfor = time.time() + _PROCESS_KILL_TIMEOUT
while time.time() < waitfor:
try:
... | python | {
"resource": ""
} |
q268636 | _FileStatsReader._read_data | test | def _read_data(self, lines):
"""
Parse lines and return stats
"""
results = []
for line in lines:
timestamp, rps, instances = line.split("\t")
curr_ts = int(float(timestamp)) # We allow floats here, but tank expects only seconds
if self.__las... | python | {
"resource": ""
} |
q268637 | Plugin.__create_criterion | test | def __create_criterion(self, criterion_str):
""" instantiate criterion from config string """
parsed = criterion_str.split("(")
type_str = parsed[0].strip().lower()
parsed[1] = parsed[1].split(")")[0].strip()
for criterion_class in self.custom_criterions:
if criterio... | python | {
"resource": ""
} |
q268638 | ConfigManager.getconfig | test | def getconfig(self, filename, target_hint):
"""Prepare config data."""
try:
tree = self.parse_xml(filename)
except IOError as exc:
logger.error("Error loading config: %s", exc)
raise RuntimeError("Can't read monitoring config %s" % filename)
hosts = tr... | python | {
"resource": ""
} |
q268639 | AgentConfig.create_startup_config | test | def create_startup_config(self):
""" Startup and shutdown commands config
Used by agent.py on the target
"""
cfg_path = "agent_startup_{}.cfg".format(self.host)
if os.path.isfile(cfg_path):
logger.info(
'Found agent startup config file in working dire... | python | {
"resource": ""
} |
q268640 | Plugin.__check_disk | test | def __check_disk(self):
''' raise exception on disk space exceeded '''
cmd = "sh -c \"df --no-sync -m -P -l -x fuse -x tmpfs -x devtmpfs -x davfs -x nfs "
cmd += self.core.artifacts_base_dir
cmd += " | tail -n 1 | awk '{print \$4}' \""
res = execute(cmd, True, 0.1, True)
... | python | {
"resource": ""
} |
q268641 | Plugin.__check_mem | test | def __check_mem(self):
''' raise exception on RAM exceeded '''
mem_free = psutil.virtual_memory().available / 2**20
self.log.debug("Memory free: %s/%s", mem_free, self.mem_limit)
if mem_free < self.mem_limit:
raise RuntimeError(
"Not enough resources: free mem... | python | {
"resource": ""
} |
q268642 | get_terminal_size | test | def get_terminal_size():
'''
Gets width and height of terminal viewport
'''
default_size = (30, 120)
env = os.environ
def ioctl_gwinsz(file_d):
'''
Helper to get console size
'''
try:
sizes = struct.unpack(
'hh', fcntl.ioctl(file_d, te... | python | {
"resource": ""
} |
q268643 | Screen.__get_right_line | test | def __get_right_line(self, widget_output):
''' Gets next line for right panel '''
right_line = ''
if widget_output:
right_line = widget_output.pop(0)
if len(right_line) > self.right_panel_width:
right_line_plain = self.markup.clean_markup(rig... | python | {
"resource": ""
} |
q268644 | Screen.__truncate | test | def __truncate(self, line_arr, max_width):
''' Cut tuple of line chunks according to it's wisible lenght '''
def is_space(chunk):
return all([True if i == ' ' else False for i in chunk])
def is_empty(chunks, markups):
result = []
for chunk in chunks:
... | python | {
"resource": ""
} |
q268645 | Screen.__render_left_panel | test | def __render_left_panel(self):
''' Render left blocks '''
self.log.debug("Rendering left blocks")
left_block = self.left_panel
left_block.render()
blank_space = self.left_panel_width - left_block.width
lines = []
pre_space = ' ' * int(blank_space / 2)
if ... | python | {
"resource": ""
} |
q268646 | Screen.render_screen | test | def render_screen(self):
''' Main method to render screen view '''
self.term_width, self.term_height = get_terminal_size()
self.log.debug(
"Terminal size: %sx%s", self.term_width, self.term_height)
self.right_panel_width = int(
(self.term_width - len... | python | {
"resource": ""
} |
q268647 | Screen.add_info_widget | test | def add_info_widget(self, widget):
'''
Add widget string to right panel of the screen
'''
index = widget.get_index()
while index in self.info_widgets.keys():
index += 1
self.info_widgets[widget.get_index()] = widget | python | {
"resource": ""
} |
q268648 | AbstractBlock.fill_rectangle | test | def fill_rectangle(self, prepared):
''' Right-pad lines of block to equal width '''
result = []
width = max([self.clean_len(line) for line in prepared])
for line in prepared:
spacer = ' ' * (width - self.clean_len(line))
result.append(line + (self.screen.markup.... | python | {
"resource": ""
} |
q268649 | AbstractBlock.clean_len | test | def clean_len(self, line):
''' Calculate wisible length of string '''
if isinstance(line, basestring):
return len(self.screen.markup.clean_markup(line))
elif isinstance(line, tuple) or isinstance(line, list):
markups = self.screen.markup.get_markup_vars()
le... | python | {
"resource": ""
} |
q268650 | create | test | def create(instances_schedule):
'''
Creates load plan timestamps generator
>>> from util import take
>>> take(7, LoadPlanBuilder().ramp(5, 4000).create())
[0, 1000, 2000, 3000, 4000, 0, 0]
>>> take(7, create(['ramp(5, 4s)']))
[0, 1000, 2000, 3000, 4000, 0, 0]
>>> take(12, create(['ra... | python | {
"resource": ""
} |
q268651 | TotalHTTPCodesCriterion.get_level_str | test | def get_level_str(self):
''' format level str '''
if self.is_relative:
level_str = str(self.level) + "%"
else:
level_str = self.level
return level_str | python | {
"resource": ""
} |
q268652 | Plugin.add_info_widget | test | def add_info_widget(self, widget):
''' add right panel widget '''
if not self.screen:
self.log.debug("No screen instance to add widget")
else:
self.screen.add_info_widget(widget) | python | {
"resource": ""
} |
q268653 | APIClient.__make_writer_request | test | def __make_writer_request(
self,
params=None,
json=None,
http_method="POST",
trace=False):
'''
Send request to writer service.
'''
request = requests.Request(
http_method,
self.writer_url,
par... | python | {
"resource": ""
} |
q268654 | TankCore.load_plugins | test | def load_plugins(self):
"""
Tells core to take plugin options and instantiate plugin classes
"""
logger.info("Loading plugins...")
for (plugin_name, plugin_path, plugin_cfg) in self.config.plugins:
logger.debug("Loading plugin %s from %s", plugin_name, plugin_path)
... | python | {
"resource": ""
} |
q268655 | TankCore.get_plugin_of_type | test | def get_plugin_of_type(self, plugin_class):
"""
Retrieve a plugin of desired class, KeyError raised otherwise
"""
logger.debug("Searching for plugin: %s", plugin_class)
matches = [plugin for plugin in self.plugins.values() if isinstance(plugin, plugin_class)]
if matches:
... | python | {
"resource": ""
} |
q268656 | TankCore.get_plugins_of_type | test | def get_plugins_of_type(self, plugin_class):
"""
Retrieve a list of plugins of desired class, KeyError raised otherwise
"""
logger.debug("Searching for plugins: %s", plugin_class)
matches = [plugin for plugin in self.plugins.values() if isinstance(plugin, plugin_class)]
i... | python | {
"resource": ""
} |
q268657 | TankCore.__collect_file | test | def __collect_file(self, filename, keep_original=False):
"""
Move or copy single file to artifacts dir
"""
dest = self.artifacts_dir + '/' + os.path.basename(filename)
logger.debug("Collecting file: %s to %s", filename, dest)
if not filename or not os.path.exists(filename... | python | {
"resource": ""
} |
q268658 | TankCore.add_artifact_file | test | def add_artifact_file(self, filename, keep_original=False):
"""
Add file to be stored as result artifact on post-process phase
"""
if filename:
logger.debug(
"Adding artifact file to collect (keep=%s): %s", keep_original,
filename)
... | python | {
"resource": ""
} |
q268659 | TankCore.mkstemp | test | def mkstemp(self, suffix, prefix, directory=None):
"""
Generate temp file name in artifacts base dir
and close temp file handle
"""
if not directory:
directory = self.artifacts_dir
fd, fname = tempfile.mkstemp(suffix, prefix, directory)
os.close(fd)
... | python | {
"resource": ""
} |
q268660 | ConfigManager.load_files | test | def load_files(self, configs):
""" Read configs set into storage """
logger.debug("Reading configs: %s", configs)
config_filenames = [resource.resource_filename(config) for config in configs]
try:
self.config.read(config_filenames)
except Exception as e... | python | {
"resource": ""
} |
q268661 | ConfigManager.flush | test | def flush(self, filename=None):
""" Flush current stat to file """
if not filename:
filename = self.file
if filename:
with open(filename, 'w') as handle:
self.config.write(handle) | python | {
"resource": ""
} |
q268662 | ConfigManager.get_options | test | def get_options(self, section, prefix=''):
""" Get options list with requested prefix """
res = []
try:
for option in self.config.options(section):
if not prefix or option.find(prefix) == 0:
res += [(
option[len(prefix):], s... | python | {
"resource": ""
} |
q268663 | ConfigManager.find_sections | test | def find_sections(self, prefix):
""" return sections with specified prefix """
res = []
for section in self.config.sections():
if section.startswith(prefix):
res.append(section)
return res | python | {
"resource": ""
} |
q268664 | PhantomStatsReader._decode_stat_data | test | def _decode_stat_data(self, chunk):
"""
Return all items found in this chunk
"""
for date_str, statistics in chunk.iteritems():
date_obj = datetime.datetime.strptime(
date_str.split(".")[0], '%Y-%m-%d %H:%M:%S')
chunk_date = int(time.mktime(date_ob... | python | {
"resource": ""
} |
q268665 | Plugin.get_info | test | def get_info(self):
""" returns info object """
if not self.cached_info:
if not self.phantom:
return None
self.cached_info = self.phantom.get_info()
return self.cached_info | python | {
"resource": ""
} |
q268666 | MonitoringCollector.prepare | test | def prepare(self):
"""Prepare for monitoring - install agents etc"""
# Parse config
agent_configs = []
if self.config:
agent_configs = self.config_manager.getconfig(
self.config, self.default_target)
# Creating agent for hosts
for config in a... | python | {
"resource": ""
} |
q268667 | MonitoringCollector.poll | test | def poll(self):
""" Poll agents for data
"""
start_time = time.time()
for agent in self.agents:
for collect in agent.reader:
# don't crush if trash or traceback came from agent to stdout
if not collect:
return 0
... | python | {
"resource": ""
} |
q268668 | MonitoringCollector.send_collected_data | test | def send_collected_data(self):
"""sends pending data set to listeners"""
data = self.__collected_data
self.__collected_data = []
for listener in self.listeners:
# deep copy to ensure each listener gets it's own copy
listener.monitoring_data(copy.deepcopy(data)) | python | {
"resource": ""
} |
q268669 | Plugin.__detect_configuration | test | def __detect_configuration(self):
"""
we need to be flexible in order to determine which plugin's configuration
specified and make appropriate configs to metrics collector
:return: SECTION name or None for defaults
"""
try:
is_telegraf = self.core.get_option(... | python | {
"resource": ""
} |
q268670 | MonitoringWidget.__handle_data_items | test | def __handle_data_items(self, host, data):
""" store metric in data tree and calc offset signs
sign < 0 is CYAN, means metric value is lower then previous,
sign > 1 is YELLOW, means metric value is higher then prevoius,
sign == 0 is WHITE, means initial or equal metric value
"""... | python | {
"resource": ""
} |
q268671 | MonitoringReader._decode_agents_data | test | def _decode_agents_data(self, block):
"""
decode agents jsons, count diffs
"""
collect = []
if block:
for chunk in block.split('\n'):
try:
if chunk:
prepared_results = {}
jsn = json.lo... | python | {
"resource": ""
} |
q268672 | StreamConn.subscribe | test | async def subscribe(self, channels):
'''Start subscribing channels.
If the necessary connection isn't open yet, it opens now.
'''
ws_channels = []
nats_channels = []
for c in channels:
if c.startswith(('Q.', 'T.', 'A.', 'AM.',)):
nats_channels.... | python | {
"resource": ""
} |
q268673 | StreamConn.run | test | def run(self, initial_channels=[]):
'''Run forever and block until exception is rasised.
initial_channels is the channels to start with.
'''
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(self.subscribe(initial_channels))
loop.run_forever()
... | python | {
"resource": ""
} |
q268674 | StreamConn.close | test | async def close(self):
'''Close any of open connections'''
if self._ws is not None:
await self._ws.close()
if self.polygon is not None:
await self.polygon.close() | python | {
"resource": ""
} |
q268675 | REST._one_request | test | def _one_request(self, method, url, opts, retry):
'''
Perform one request, possibly raising RetryException in the case
the response is 429. Otherwise, if error text contain "code" string,
then it decodes to json object and returns APIError.
Returns the body json in the 200 status... | python | {
"resource": ""
} |
q268676 | REST.submit_order | test | def submit_order(self, symbol, qty, side, type, time_in_force,
limit_price=None, stop_price=None, client_order_id=None):
'''Request a new order'''
params = {
'symbol': symbol,
'qty': qty,
'side': side,
'type': type,
'time_i... | python | {
"resource": ""
} |
q268677 | REST.get_order | test | def get_order(self, order_id):
'''Get an order'''
resp = self.get('/orders/{}'.format(order_id))
return Order(resp) | python | {
"resource": ""
} |
q268678 | REST.get_position | test | def get_position(self, symbol):
'''Get an open position'''
resp = self.get('/positions/{}'.format(symbol))
return Position(resp) | python | {
"resource": ""
} |
q268679 | REST.list_assets | test | def list_assets(self, status=None, asset_class=None):
'''Get a list of assets'''
params = {
'status': status,
'assert_class': asset_class,
}
resp = self.get('/assets', params)
return [Asset(o) for o in resp] | python | {
"resource": ""
} |
q268680 | REST.get_asset | test | def get_asset(self, symbol):
'''Get an asset'''
resp = self.get('/assets/{}'.format(symbol))
return Asset(resp) | python | {
"resource": ""
} |
q268681 | create_joining_subplan | test | def create_joining_subplan(
pipeline_def, solid, join_step_key, parallel_steps, parallel_step_output
):
'''
This captures a common pattern of fanning out a single value to N steps,
where each step has similar structure. The strict requirement here is that each step
must provide an output named the p... | python | {
"resource": ""
} |
q268682 | dict_param | test | def dict_param(obj, param_name, key_type=None, value_type=None):
'''Ensures argument obj is a native Python dictionary, raises an exception if not, and otherwise
returns obj.
'''
if not isinstance(obj, dict):
raise_with_traceback(_param_type_mismatch_exception(obj, dict, param_name))
if not... | python | {
"resource": ""
} |
q268683 | opt_dict_param | test | def opt_dict_param(obj, param_name, key_type=None, value_type=None, value_class=None):
'''Ensures argument obj is either a dictionary or None; if the latter, instantiates an empty
dictionary.
'''
if obj is not None and not isinstance(obj, dict):
raise_with_traceback(_param_type_mismatch_exceptio... | python | {
"resource": ""
} |
q268684 | construct_event_logger | test | def construct_event_logger(event_record_callback):
'''
Callback receives a stream of event_records
'''
check.callable_param(event_record_callback, 'event_record_callback')
return construct_single_handler_logger(
'event-logger',
DEBUG,
StructuredLoggerHandler(
lam... | python | {
"resource": ""
} |
q268685 | construct_json_event_logger | test | def construct_json_event_logger(json_path):
'''Record a stream of event records to json'''
check.str_param(json_path, 'json_path')
return construct_single_handler_logger(
"json-event-record-logger",
DEBUG,
JsonEventLoggerHandler(
json_path,
lambda record: cons... | python | {
"resource": ""
} |
q268686 | RCParser.from_file | test | def from_file(cls, path=None):
"""Read a config file and instantiate the RCParser.
Create new :class:`configparser.ConfigParser` for the given **path**
and instantiate the :class:`RCParser` with the ConfigParser as
:attr:`config` attribute.
If the **path** doesn't exist, raise ... | python | {
"resource": ""
} |
q268687 | RCParser.get_repository_config | test | def get_repository_config(self, repository):
"""Get config dictionary for the given repository.
If the repository section is not found in the config file,
return ``None``. If the file is invalid, raise
:exc:`configparser.Error`.
Otherwise return a dictionary with:
* `... | python | {
"resource": ""
} |
q268688 | format_config_for_graphql | test | def format_config_for_graphql(config):
'''This recursive descent thing formats a config dict for GraphQL.'''
def _format_config_subdict(config, current_indent=0):
check.dict_param(config, 'config', key_type=str)
printer = IndentingStringIoPrinter(indent_level=2, current_indent=current_indent)
... | python | {
"resource": ""
} |
q268689 | RepositoryDefinition.get_pipeline | test | def get_pipeline(self, name):
'''Get a pipeline by name. Only constructs that pipeline and caches it.
Args:
name (str): Name of the pipeline to retriever
Returns:
PipelineDefinition: Instance of PipelineDefinition with that name.
'''
check.str_param(name... | python | {
"resource": ""
} |
q268690 | RepositoryDefinition.get_all_pipelines | test | def get_all_pipelines(self):
'''Return all pipelines as a list
Returns:
List[PipelineDefinition]:
'''
pipelines = list(map(self.get_pipeline, self.pipeline_dict.keys()))
# This does uniqueness check
self._construct_solid_defs(pipelines)
return pipeli... | python | {
"resource": ""
} |
q268691 | get_next_event | test | def get_next_event(process, queue):
'''
This function polls the process until it returns a valid
item or returns PROCESS_DEAD_AND_QUEUE_EMPTY if it is in
a state where the process has terminated and the queue is empty
Warning: if the child process is in an infinite loop. This will
also infinite... | python | {
"resource": ""
} |
q268692 | execute_pipeline_through_queue | test | def execute_pipeline_through_queue(
repository_info,
pipeline_name,
solid_subset,
environment_dict,
run_id,
message_queue,
reexecution_config,
step_keys_to_execute,
):
"""
Execute pipeline using message queue as a transport
"""
message_queue.put(ProcessStartedSentinel(os... | python | {
"resource": ""
} |
q268693 | MultiprocessingExecutionManager.join | test | def join(self):
'''Waits until all there are no processes enqueued.'''
while True:
with self._processes_lock:
if not self._processes and self._processing_semaphore.locked():
return True
gevent.sleep(0.1) | python | {
"resource": ""
} |
q268694 | Field | test | def Field(
dagster_type,
default_value=FIELD_NO_DEFAULT_PROVIDED,
is_optional=INFER_OPTIONAL_COMPOSITE_FIELD,
is_secret=False,
description=None,
):
'''
The schema for configuration data that describes the type, optionality, defaults, and description.
Args:
dagster_type (DagsterT... | python | {
"resource": ""
} |
q268695 | _PlanBuilder.build | test | def build(self, pipeline_def, artifacts_persisted):
'''Builds the execution plan.
'''
# Construct dependency dictionary
deps = {step.key: set() for step in self.steps}
for step in self.steps:
for step_input in step.step_inputs:
deps[step.key].add(ste... | python | {
"resource": ""
} |
q268696 | ExecutionPlan.build | test | def build(pipeline_def, environment_config):
'''Here we build a new ExecutionPlan from a pipeline definition and the environment config.
To do this, we iterate through the pipeline's solids in topological order, and hand off the
execution steps for each solid to a companion _PlanBuilder object.... | python | {
"resource": ""
} |
q268697 | _build_sub_pipeline | test | def _build_sub_pipeline(pipeline_def, solid_names):
'''
Build a pipeline which is a subset of another pipeline.
Only includes the solids which are in solid_names.
'''
check.inst_param(pipeline_def, 'pipeline_def', PipelineDefinition)
check.list_param(solid_names, 'solid_names', of_type=str)
... | python | {
"resource": ""
} |
q268698 | PipelineDefinition.solid_named | test | def solid_named(self, name):
'''Return the solid named "name". Throws if it does not exist.
Args:
name (str): Name of solid
Returns:
SolidDefinition: SolidDefinition with correct name.
'''
check.str_param(name, 'name')
if name not in self._solid_... | python | {
"resource": ""
} |
q268699 | construct_publish_comands | test | def construct_publish_comands(additional_steps=None, nightly=False):
'''Get the shell commands we'll use to actually build and publish a package to PyPI.'''
publish_commands = (
['rm -rf dist']
+ (additional_steps if additional_steps else [])
+ [
'python setup.py sdist bdist_... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.