code stringlengths 52 7.75k | docs stringlengths 1 5.85k |
|---|---|
def parse_duration(duration):
duration = str(duration).upper().strip()
elements = ELEMENTS.copy()
for pattern in (SIMPLE_DURATION, COMBINED_DURATION):
if pattern.match(duration):
found = pattern.match(duration).groupdict()
del found['time']
elements.update... | Attepmts to parse an ISO8601 formatted ``duration``.
Returns a ``datetime.timedelta`` object. |
def skin_details(skin_id, lang="en"):
params = {"skin_id": skin_id, "lang": lang}
cache_name = "skin_details.%(skin_id)s.%(lang)s.json" % params
return get_cached("skin_details.json", cache_name, params=params) | This resource returns details about a single skin.
:param skin_id: The skin to query for.
:param lang: The language to display the texts in.
The response is an object with at least the following properties. Note that
the availability of some properties depends on the type of item the skin
applies ... |
def bubble_to_dot(bblfile:str, dotfile:str=None, render:bool=False,
oriented:bool=False):
tree = BubbleTree.from_bubble_file(bblfile, oriented=bool(oriented))
return tree_to_dot(tree, dotfile, render=render) | Write in dotfile a graph equivalent to those depicted in bubble file |
def bubble_to_gexf(bblfile:str, gexffile:str=None, oriented:bool=False):
tree = BubbleTree.from_bubble_file(bblfile, oriented=bool(oriented))
gexf_converter.tree_to_file(tree, gexffile)
return gexffile | Write in bblfile a graph equivalent to those depicted in bubble file |
def bubble_to_js(bblfile:str, jsdir:str=None, oriented:bool=False, **style):
js_converter.bubble_to_dir(bblfile, jsdir, oriented=bool(oriented), **style)
return jsdir | Write in jsdir a graph equivalent to those depicted in bubble file |
def tree_to_dot(tree:BubbleTree, dotfile:str=None, render:bool=False):
graph = tree_to_graph(tree)
path = None
if dotfile: # first save the dot file.
path = graph.save(dotfile)
if render: # secondly, show it.
# As the dot file is known by the Graph object,
# it will be pla... | Write in dotfile a graph equivalent to those depicted in bubble file
See http://graphviz.readthedocs.io/en/latest/examples.html#cluster-py
for graphviz API |
def fill(self, term_dict, terms):
# type: (Dict[int, Set[Type[Rule]]], Any) -> None
for i in range(len(terms)):
t = terms[i]
self._field[0][i] += term_dict[hash(t)] | Fill first row of the structure witch nonterminal directly rewritable to terminal.
:param term_dict: Dictionary of rules directly rewritable to terminal.
Key is hash of terminal, value is set of rules with key terminal at the right side.
:param terms: Input sequence of terminal. |
def rules(self, x, y):
# type: (int, int) -> List[Type[Rule]]
return [r for r in self._field[y][x]] | Get rules at specific position in the structure.
:param x: X coordinate
:param y: Y coordinate
:return: List of rules |
def positions(self, x, y):
# type: (int, int) -> List[(Point, Point)]
return [(Point(x, v), Point(x + 1 + v, y - 1 - v)) for v in range(y)] | Get all positions, that can be combined to get word parsed at specified position.
:param x: X coordinate.
:param y: Y coordinate.
:return: List of tuples with two Point instances. |
def put(self, x, y, rules):
# type: (int, int, List[PlaceItem]) -> None
self._field[y][x] = rules | Set possible rules at specific position.
:param x: X coordinate.
:param y: Y coordinate.
:param rules: Value to set. |
def froze_it(cls):
cls._frozen = False
def frozensetattr(self, key, value):
if self._frozen and not hasattr(self, key):
raise AttributeError("Attribute '{}' of class '{}' does not exist!"
.format(key, cls.__name__))
else:
object.__setattr_... | Decorator to prevent from creating attributes in the object ouside __init__().
This decorator must be applied to the final class (doesn't work if a
decorated class is inherited).
Yoann's answer at http://stackoverflow.com/questions/3603502 |
def one_liner_str(self):
assert self.less_attrs is not None, "Forgot to set attrs class variable"
s_format = "{}={}"
s = "; ".join([s_format.format(x, self.__getattribute__(x)) for x in self.less_attrs])
return s | Returns string (supposed to be) shorter than str() and not contain newline |
def to_dict(self):
ret = OrderedDict()
for attrname in self.attrs:
ret[attrname] = self.__getattribute__(attrname)
return ret | Returns OrderedDict whose keys are self.attrs |
def to_list(self):
ret = OrderedDict()
for attrname in self.attrs:
ret[attrname] = self.__getattribute__(attrname)
return ret | Returns list containing values of attributes listed in self.attrs |
def uniq(pipe):
''' this works like bash's uniq command where the generator only iterates
if the next value is not the previous '''
pipe = iter(pipe)
previous = next(pipe)
yield previous
for i in pipe:
if i is not previous:
previous = i
yield f uniq(pipe):
... | this works like bash's uniq command where the generator only iterates
if the next value is not the previous |
def chunks_generator(iterable, count_items_in_chunk):
iterator = iter(iterable)
for first in iterator: # stops when iterator is depleted
def chunk(): # construct generator for next chunk
yield first # yield element from for loop
for more in islice(iterator, count_items_in... | Очень внимательно! Не дает обходить дважды
:param iterable:
:param count_items_in_chunk:
:return: |
def chunks(list_, count_items_in_chunk):
for i in range(0, len(list_), count_items_in_chunk):
yield list_[i:i + count_items_in_chunk] | разбить list (l) на куски по n элементов
:param list_:
:param count_items_in_chunk:
:return: |
def pretty_json(obj):
return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False) | Представить объект в вище json красиво отформатированной строки
:param obj:
:return: |
def decode_jwt(input_text, secure_key):
if input_text is None:
return None
encoded = (input_text.split(":")[1]).encode('utf-8')
decoded = jwt.decode(encoded, secure_key)
return decoded['sub'] | Раскодирование строки на основе ключа
:param input_text: исходная строка
:param secure_key: секретный ключ
:return: |
def send_request(url, method, data,
args, params, headers, cookies, timeout, is_json, verify_cert):
## Parse url args
for p in args:
url = url.replace(':' + p, str(args[p]))
try:
if data:
if is_json:
headers['Content-Type'] = 'application/json'
data = json.dumps(data)
request = requests.Reque... | Forge and send HTTP request. |
def neighbors(self) -> List['Node']:
self._load_neighbors()
return [edge.source if edge.source != self else edge.target
for edge in self._neighbors.values()] | The list of neighbors of the node. |
def add_neighbor(self, edge: "Edge") -> None:
if edge is None or (edge.source != self and edge.target != self):
return
if edge.source == self:
other: Node = edge.target
elif edge.target == self:
other: Node = edge.source
else:
... | Adds a new neighbor to the node.
Arguments:
edge (Edge): The edge that would connect this node with its neighbor. |
def _load_neighbors(self) -> None:
if not self.are_neighbors_cached:
self._load_neighbors_from_external_source()
db: GraphDatabaseInterface = self._graph.database
db_node: DBNode = db.Node.find_by_name(self.name)
db_node.are_neighbors_cached = True
... | Loads all neighbors of the node from the local database and
from the external data source if needed. |
def _load_neighbors_from_database(self) -> None:
self._are_neighbors_loaded = True
graph: Graph = self._graph
neighbors: List[DBNode] = graph.database.Node.find_by_name(self.name).neighbors
nodes: NodeList = graph.nodes
for db_node in neighbors:
gr... | Loads the neighbors of the node from the local database. |
def key(self) -> Tuple[int, int]:
return self._source.index, self._target.index | The unique identifier of the edge consisting of the indexes of its
source and target nodes. |
def add_node_by_name(self, node_name: str, external_id: Optional[str] = None) -> None:
if node_name is None:
return
node_name = node_name.strip()
if len(node_name) == 0:
return
node: Node = self.get_node_by_name(node_name, external_id=external_... | Adds a new node to the graph if it doesn't exist.
Arguments:
node_name (str): The name of the node to add.
external_id (Optional[str]): The external ID of the node. |
def get_node(self, index: int) -> Optional[Node]:
return self._nodes.get(index) | Returns the node with the given index if such a node currently exists in the node list.
Arguments:
index (int): The index of the queried node.
Returns:
The node with the given index if such a node currently exists in the node list,
`None` otherwise. |
def _internal_add_node(self,
node_name: str,
external_id: Optional[str] = None,
are_neighbors_cached: bool = False,
add_to_cache: bool = False) -> None:
index: int = len(self)
node... | Adds a node with the given name to the graph without checking whether it already exists or not.
Arguments:
node_name (str): The name of the node to add.
external_id (Optional[str]): The external ID of the node.
are_neighbors_cached (bool): Whether the neighbors of the n... |
def edge_list(self) -> List[Edge]:
return [edge for edge in sorted(self._edges.values(), key=attrgetter("key"))] | The ordered list of edges in the container. |
def add_edge(self,
source: Node,
target: Node,
weight: float = 1,
save_to_cache: bool = True) -> None:
if not isinstance(source, Node):
raise TypeError("Invalid source: expected Node instance, got {}.".format(source)... | Adds an edge to the edge list that will connect the specified nodes.
Arguments:
source (Node): The source node of the edge.
target (Node): The target node of the edge.
weight (float): The weight of the created edge.
save_to_cache (bool): Whether the edge sh... |
def get_edge(self, source: Node, target: Node) -> Optional[Edge]:
return self.get_edge_by_index(source.index, target.index) | Returns the edge connection the given nodes if such an edge exists.
Arguments:
source (Node): One of the endpoints of the queried edge.
target (Node): The other endpoint of the queried edge.
Returns:
Returns the edge connection the given nodes
or... |
def get_edge_by_index(self, source_index: int, target_index: int) -> Optional[Edge]:
edge = self._edges.get((source_index, target_index))
if edge is not None:
return edge
return self._edges.get((target_index, source_index)) | Returns the edge connecting the nodes with the specified indices if such an edge exists.
Arguments:
source_index (int): The index of one of the endpoints of queried edge.
target_index (int): The index of the other endpoint of the queried edge.
Returns:
The ed... |
def get_edge_by_name(self, source_name: str, target_name: str) -> Optional[Edge]:
nodes: NodeList = self._graph.nodes
source: Optional[Node] = nodes.get_node_by_name(source_name)
if source is None:
return None
target: Optional[Node] = nodes.get_node_by_name(tar... | Returns the edge connecting the nodes with the specified names if such an edge exists.
Arguments:
source_name (str): The name of one of the endpoints of queried edge.
target_name (str): The name of the other endpoint of the queried edge.
Returns:
The edge con... |
def add_edge(self, source: Node,
target: Node,
weight: float = 1,
save_to_cache: bool = True) -> None:
if self._edges.get_edge(source, target) is not None:
return
self._edges.add_edge(
source=source,
... | Adds an edge between the specified nodes of the graph.
Arguments:
source (Node): The source node of the edge to add.
target (Node): The target node of the edge to add.
weight (float): The weight of the edge.
save_to_cache (bool): Whether the edge should be ... |
def add_edge_by_index(self, source_index: int, target_index: int,
weight: float, save_to_cache: bool = True) -> None:
source: Node = self._nodes.get_node(source_index)
target: Node = self._nodes.get_node(target_index)
if source is None or target is None:
... | Adds an edge between the nodes with the specified indices to the graph.
Arguments:
source_index (int): The index of the source node of the edge to add.
target_index (int): The index of the target node of the edge to add.
weight (float): The weight of the edge.
... |
def add_node(self, node_name: str, external_id: Optional[str] = None) -> None:
self._nodes.add_node_by_name(node_name, external_id) | Adds the node with the given name to the graph.
Arguments:
node_name (str): The name of the node to add to the graph.
external_id (Optional[str]): The external ID of the node. |
def get_authentic_node_name(self, node_name: str) -> Optional[str]:
node: Node = self._nodes.get_node_by_name(node_name)
return node.name if node is not None else None | Returns the exact, authentic node name for the given node name if a node corresponding to
the given name exists in the graph (maybe not locally yet) or `None` otherwise.
By default, this method checks whether a node with the given name exists locally in the
graph and return `node_name` if i... |
def beforeSummaryReport(self, event):
'''Output profiling results'''
self.prof.disable()
stats = pstats.Stats(self.prof, stream=event.stream).sort_stats(
self.sort)
event.stream.writeln(nose2.util.ln('Profiling results'))
stats.print_stats()
if self.pfile:
... | Output profiling results |
def separate(text):
'''Takes text and separates it into a list of words'''
alphabet = 'abcdefghijklmnopqrstuvwxyz'
words = text.split()
standardwords = []
for word in words:
newstr = ''
for char in word:
if char in alphabet or char in alphabet.upper():
news... | Takes text and separates it into a list of words |
def eliminate_repeats(text):
'''Returns a list of words that occur in the text. Eliminates stopwords.'''
bannedwords = read_file('stopwords.txt')
alphabet = 'abcdefghijklmnopqrstuvwxyz'
words = text.split()
standardwords = []
for word in words:
newstr = ''
for char in word:
... | Returns a list of words that occur in the text. Eliminates stopwords. |
def wordcount(text):
'''Returns the count of the words in a file.'''
bannedwords = read_file('stopwords.txt')
wordcount = {}
separated = separate(text)
for word in separated:
if word not in bannedwords:
if not wordcount.has_key(word):
wordcount[word] = 1
... | Returns the count of the words in a file. |
def tuplecount(text):
'''Changes a dictionary into a list of tuples.'''
worddict = wordcount(text)
countlist = []
for key in worddict.keys():
countlist.append((key,worddict[key]))
countlist = list(reversed(sorted(countlist,key = lambda x: x[1])))
return countlisf tuplecount(text):
''... | Changes a dictionary into a list of tuples. |
def add_log_error(self, x, flag_also_show=False, E=None):
self.parent_form.add_log_error(x, flag_also_show, E) | Delegates to parent form |
def add_log(self, x, flag_also_show=False):
self.parent_form.add_log(x, flag_also_show) | Delegates to parent form |
def get_file_md5(filename):
if os.path.exists(filename):
blocksize = 65536
try:
hasher = hashlib.md5()
except BaseException:
hasher = hashlib.new('md5', usedForSecurity=False)
with open(filename, 'rb') as afile:
buf = afile.read(blocksize)
... | Get a file's MD5 |
def get_md5(string):
try:
hasher = hashlib.md5()
except BaseException:
hasher = hashlib.new('md5', usedForSecurity=False)
hasher.update(string)
return hasher.hexdigest() | Get a string's MD5 |
def deploy_signature(source, dest, user=None, group=None):
move(source, dest)
os.chmod(dest, 0644)
if user and group:
try:
uid = pwd.getpwnam(user).pw_uid
gid = grp.getgrnam(group).gr_gid
os.chown(dest, uid, gid)
except (KeyError, OSError):
... | Deploy a signature fole |
def get_local_version(sigdir, sig):
version = None
filename = os.path.join(sigdir, '%s.cvd' % sig)
if os.path.exists(filename):
cmd = ['sigtool', '-i', filename]
sigtool = Popen(cmd, stdout=PIPE, stderr=PIPE)
while True:
line = sigtool.stdout.readline()
i... | Get the local version of a signature |
def verify_sigfile(sigdir, sig):
cmd = ['sigtool', '-i', '%s/%s.cvd' % (sigdir, sig)]
sigtool = Popen(cmd, stdout=PIPE, stderr=PIPE)
ret_val = sigtool.wait()
return ret_val == 0 | Verify a signature file |
def check_download(obj, *args, **kwargs):
version = args[0]
workdir = args[1]
signame = args[2]
if version:
local_version = get_local_version(workdir, signame)
if not verify_sigfile(workdir, signame) or version != local_version:
error("[-] \033[91mFailed to verify signat... | Verify a download |
def download_sig(opts, sig, version=None):
code = None
downloaded = False
useagent = 'ClamAV/0.101.1 (OS: linux-gnu, ARCH: x86_64, CPU: x86_64)'
manager = PoolManager(
headers=make_headers(user_agent=useagent),
cert_reqs='CERT_REQUIRED',
ca_certs=certifi.where(),
tim... | Download signature from hostname |
def get_record(opts):
count = 1
for passno in range(1, 5):
count = passno
info("[+] \033[92mQuerying TXT record:\033[0m %s pass: %s" %
(opts.txtrecord, passno))
record = get_txt_record(opts.txtrecord)
if record:
info("=> Query returned: %s" % record)... | Get record |
def copy_sig(sig, opts, isdiff):
info("[+] \033[92mDeploying signature:\033[0m %s" % sig)
if isdiff:
sourcefile = os.path.join(opts.workdir, '%s.cdiff' % sig)
destfile = os.path.join(opts.mirrordir, '%s.cdiff' % sig)
else:
sourcefile = os.path.join(opts.workdir, '%s.cvd' % sig)
... | Deploy a sig |
def update_sig(queue):
while True:
options, sign, vers = queue.get()
info("[+] \033[92mChecking signature version:\033[0m %s" % sign)
localver = get_local_version(options.mirrordir, sign)
remotever = vers[sign]
if localver is None or (localver and int(localver) < int(rem... | update signature |
def update_diff(opts, sig):
for _ in range(1, 6):
info("[+] \033[92mDownloading cdiff:\033[0m %s" % sig)
status, code = download_sig(opts, sig)
if status:
info("=> Downloaded cdiff: %s" % sig)
copy_sig(sig, opts, 1)
else:
if code == 404:
... | Update diff |
def create_dns_file(opts, record):
info("[+] \033[92mUpdating dns.txt file\033[0m")
filename = os.path.join(opts.mirrordir, 'dns.txt')
localmd5 = get_file_md5(filename)
remotemd5 = get_md5(record)
if localmd5 != remotemd5:
create_file(filename, record)
info("=> dns.txt file upda... | Create the DNS record file |
def download_diffs(queue):
while True:
options, signature_type, localver, remotever = queue.get()
for num in range(int(localver), int(remotever) + 1):
sig_diff = '%s-%d' % (signature_type, num)
filename = os.path.join(options.mirrordir, '%s.cdiff' % sig_diff)
... | Download the cdiff files |
def work(options):
# pylint: disable=too-many-locals
record = get_record(options)
_, mainv, dailyv, _, _, _, safebrowsingv, bytecodev = record.split(':')
versions = {'main': mainv, 'daily': dailyv,
'safebrowsing': safebrowsingv,
'bytecode': bytecodev}
dqueue = Qu... | The work functions |
def main():
parser = OptionParser()
parser.add_option('-a', '--hostname',
help='ClamAV source server hostname',
dest='hostname',
type='str',
default='db.de.clamav.net')
parser.add_option('-r', '--text-record',
... | Main entry point |
def copy_resource(src, dest):
package_name = "yass"
dest = (dest + "/" + os.path.basename(src)).rstrip("/")
if pkg_resources.resource_isdir(package_name, src):
if not os.path.isdir(dest):
os.makedirs(dest)
for res in pkg_resources.resource_listdir(__name__, src):
... | To copy package data to destination |
def publish(endpoint, purge_files, rebuild_manifest, skip_upload):
print("Publishing site to %s ..." % endpoint.upper())
yass = Yass(CWD)
target = endpoint.lower()
sitename = yass.sitename
if not sitename:
raise ValueError("Missing site name")
endpoint = yass.config.get("hosting.... | Publish the site |
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(
... | Setup site domain to route to static site |
def create_site(sitename):
sitepath = os.path.join(CWD, sitename)
if os.path.isdir(sitepath):
print("Site directory '%s' exists already!" % sitename)
else:
print("Creating site: %s..." % sitename)
os.makedirs(sitepath)
copy_resource("skel/", sitepath)
stamp_yass_... | Create a new site directory and init Yass |
def init():
yass_conf = os.path.join(CWD, "yass.yml")
if os.path.isfile(yass_conf):
print("::ALERT::")
print("It seems like Yass is already initialized here.")
print("If it's a mistake, delete 'yass.yml' in this directory")
else:
print("Init Yass in %s ..." % CWD)
... | Initialize Yass in the current directory |
def create_page(pagename):
page = pagename.lstrip("/").rstrip("/")
_, _ext = os.path.splitext(pagename)
# If the file doesn't have an extension, we'll just create one
if not _ext or _ext == "":
page += ".jade"
if not page.endswith(PAGE_FORMAT):
error("Can't create '%s'" % page... | Create a new page Omit the extension, it will create it as .jade file |
def serve(port, no_livereload, open_url):
engine = Yass(CWD)
if not port:
port = engine.config.get("local_server.port", 8000)
if no_livereload is None:
no_livereload = True if engine.config.get("local_server.livereload") is False else False
if open_url is None:
open_url = F... | Serve the site |
def get_map_location(self):
map_data = self.get_map()
(bounds_e, bounds_n), (bounds_w, bounds_s) = map_data["continent_rect"]
(map_e, map_n), (map_w, map_s) = map_data["map_rect"]
assert bounds_w < bounds_e
assert bounds_n < bounds_s
assert map_w < map_e
... | Get the location of the player, converted to world coordinates.
:return: a tuple (x, y, z). |
def CreateVertices(self, points):
gr = digraph()
for z, x, Q in points:
node = (z, x, Q)
gr.add_nodes([node])
return gr | Returns a dictionary object with keys that are 2tuples
represnting a point. |
def CreateDirectedEdges(self, points, gr, layer_width):
for z0, x0, Q0 in points:
for z1, x1, Q1 in points:
dz = z1 - z0 # no fabs because we check arrow direction
if dz > 0.0: # make sure arrow in right direction
if dz - layer_width < d... | Take each key (ie. point) in the graph and for that point
create an edge to every point downstream of it where the weight
of the edge is the tuple (distance, angle) |
def GetFarthestNode(self, gr, node):
# Remember: weights are negative
distance = minmax.shortest_path_bellman_ford(gr, node)[1]
# Find the farthest node, which is end of track
min_key = None
for key, value in distance.iteritems():
if min_key is None or value... | node is start node |
def on_success(self, fn, *args, **kwargs):
self._callbacks.append((fn, args, kwargs))
result = self._resulted_in
if result is not _NOTHING_YET:
self._succeed(result=result) | Call the given callback if or when the connected deferred succeeds. |
def _succeed(self, result):
for fn, args, kwargs in self._callbacks:
fn(result, *args, **kwargs)
self._resulted_in = result | Fire the success chain. |
def random_name(num_surnames=2):
a = []
# Prefix
if random.random() < _PROB_PREF:
a.append(_prefixes[random.randint(0, len(_prefixes) - 1)])
# Forename
a.append(_forenames[random.randint(0, len(_forenames) - 1)])
# Surnames
for i in range(num_surnames):
a... | Returns a random person name
Arguments:
num_surnames -- number of surnames |
def create_free_shipping_coupon(cls, free_shipping_coupon, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._create_free_shipping_coupon_with_http_info(free_shipping_coupon, **kwargs)
else:
(data) = cls._create_free_shipping_c... | Create FreeShippingCoupon
Create a new FreeShippingCoupon
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_free_shipping_coupon(free_shipping_coupon, async=True)
>>> result = thread.get(... |
def delete_free_shipping_coupon_by_id(cls, free_shipping_coupon_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._delete_free_shipping_coupon_by_id_with_http_info(free_shipping_coupon_id, **kwargs)
else:
(data) = cls._dele... | Delete FreeShippingCoupon
Delete an instance of FreeShippingCoupon by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_free_shipping_coupon_by_id(free_shipping_coupon_id, async=True)
... |
def get_free_shipping_coupon_by_id(cls, free_shipping_coupon_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._get_free_shipping_coupon_by_id_with_http_info(free_shipping_coupon_id, **kwargs)
else:
(data) = cls._get_free_s... | Find FreeShippingCoupon
Return single instance of FreeShippingCoupon by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_free_shipping_coupon_by_id(free_shipping_coupon_id, async=True)
... |
def list_all_free_shipping_coupons(cls, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._list_all_free_shipping_coupons_with_http_info(**kwargs)
else:
(data) = cls._list_all_free_shipping_coupons_with_http_info(**kwargs)
... | List FreeShippingCoupons
Return a list of FreeShippingCoupons
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_free_shipping_coupons(async=True)
>>> result = thread.get()
:par... |
def replace_free_shipping_coupon_by_id(cls, free_shipping_coupon_id, free_shipping_coupon, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._replace_free_shipping_coupon_by_id_with_http_info(free_shipping_coupon_id, free_shipping_coupon, **kwargs... | Replace FreeShippingCoupon
Replace all attributes of FreeShippingCoupon
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replace_free_shipping_coupon_by_id(free_shipping_coupon_id, free_shipping_coupon... |
def update_free_shipping_coupon_by_id(cls, free_shipping_coupon_id, free_shipping_coupon, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._update_free_shipping_coupon_by_id_with_http_info(free_shipping_coupon_id, free_shipping_coupon, **kwargs)
... | Update FreeShippingCoupon
Update attributes of FreeShippingCoupon
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_free_shipping_coupon_by_id(free_shipping_coupon_id, free_shipping_coupon, async... |
def fetch_config(filename):
# This trick gets the directory of *this* file Configuration.py thus
# allowing to find the schema files relative to this file.
dir_name = get_source_dir()
# Append json
filename = os.path.join('json', filename)
fileobj = open(os.path.join(dir_name, filename)... | Fetch the Configuration schema information
Finds the schema file, loads the file and reads the JSON, then converts to a dictionary that is returned |
def populate_args_level(schema, parser):
for key, value in schema['properties'].iteritems():
if key == 'name':
continue
arg = '--%s' % key
desc = value['description']
if 'type' in value:
if value['type'] == 'string':
if 'enum' in value:
... | Use a schema to populate a command line argument parser |
def set_json(self, config_json):
if self.configuration_dict is not None:
raise RuntimeError("Can only set configuration once", self.configuration_dict)
schema = fetch_config('ConfigurationSchema.json')
validictory.validate(config_json, schema)
config_json['name'] ... | Permanently set the JSON configuration
Unable to call twice. |
def bulk_send(self, topic, kmsgs, timeout=60):
try:
for kmsg in kmsgs:
self.client.send(
topic, self._onmessage(kmsg).dumps().encode("UTF-8")
)
self.client.flush(timeout=timeout)
return Result(stdout="{} message(s)... | Send a batch of messages
:param str topic: a kafka topic
:param ksr.transport.Message kmsgs: Messages to serialize
:param int timeout: Timeout in seconds
:return: Execution result
:rtype: kser.result.Result |
def send(self, topic, kmsg, timeout=60):
result = Result(uuid=kmsg.uuid)
try:
self.client.produce(
topic, self._onmessage(kmsg).dumps().encode("UTF-8")
)
result.stdout = "Message {}[{}] sent".format(
kmsg.entrypoint, kmsg.uuid
... | Send the message into the given topic
:param str topic: a kafka topic
:param ksr.transport.Message kmsg: Message to serialize
:param int timeout: Timeout in seconds (not used in proto producer)
:return: Execution result
:rtype: kser.result.Result |
def guess_extension(amimetype, normalize=False):
ext = _mimes.guess_extension(amimetype)
if ext and normalize:
# Normalize some common magic mis-interpreation
ext = {'.asc': '.txt', '.obj': '.bin'}.get(ext, ext)
from invenio.legacy.bibdocfile.api_normalizer import normalize_format
... | Tries to guess extension for a mimetype.
@param amimetype: name of a mimetype
@time amimetype: string
@return: the extension
@rtype: string |
def get_magic_guesses(fullpath):
if CFG_HAS_MAGIC == 1:
magic_cookies = _get_magic_cookies()
magic_result = []
for key in magic_cookies.keys():
magic_result.append(magic_cookies[key].file(fullpath))
return tuple(magic_result)
elif CFG_HAS_MAGIC == 2:
magi... | Return all the possible guesses from the magic library about
the content of the file.
@param fullpath: location of the file
@type fullpath: string
@return: guesses about content of the file
@rtype: tuple |
def mimes(self):
_mimes = MimeTypes(strict=False)
_mimes.suffix_map.update({'.tbz2': '.tar.bz2'})
_mimes.encodings_map.update({'.bz2': 'bzip2'})
if cfg['CFG_BIBDOCFILE_ADDITIONAL_KNOWN_MIMETYPES']:
for key, value in iteritems(
cfg['CFG_BIBDOCFILE... | Returns extended MimeTypes. |
def extensions(self):
_tmp_extensions = self.mimes.encodings_map.keys() + \
self.mimes.suffix_map.keys() + \
self.mimes.types_map[1].keys() + \
cfg['CFG_BIBDOCFILE_ADDITIONAL_KNOWN_FILE_EXTENSIONS']
extensions = []
for ext in _tmp_extensions:
... | Generate the regular expression to match all the known extensions.
@return: the regular expression.
@rtype: regular expression object |
def __deserialize(self, data, klass):
if data is None:
return None
if type(klass) == str:
from tradenity.resources.paging import Page
if klass.startswith('page['):
sub_kls = re.match('page\[(.*)\]', klass).group(1)
return Page... | Deserializes dict, list, str into an object.
:param data: dict, list or str.
:param klass: class literal, or string of class name.
:return: object. |
def update_params_for_auth(self, headers, querys, auth_settings):
if self.auth_token_holder.token is not None:
headers[Configuration.AUTH_TOKEN_HEADER_NAME] = self.auth_token_holder.token
else:
headers['Authorization'] = self.configuration.get_basic_auth_token() | Updates header and query params based on authentication setting.
:param headers: Header parameters dict to be updated.
:param querys: Query parameters tuple list to be updated.
:param auth_settings: Authentication setting identifiers list. |
def start(self, service):
try:
map(self.start_class, service.depends)
if service.is_running():
return
if service in self.failed:
log.warning("%s previously failed to start", service)
return
service.start()
... | Start the service, catching and logging exceptions |
def start_class(self, class_):
matches = filter(lambda svc: isinstance(svc, class_), self)
if not matches:
svc = class_()
self.register(svc)
matches = [svc]
map(self.start, matches)
return matches | Start all services of a given class. If this manager doesn't already
have a service of that class, it constructs one and starts it. |
def stop_class(self, class_):
"Stop all services of a given class"
matches = filter(lambda svc: isinstance(svc, class_), self)
map(self.stop, matchesf stop_class(self, class_):
"Stop all services of a given class"
matches = filter(lambda svc: isinstance(svc, class_), self)
... | Stop all services of a given class |
def log_root(self):
var_log = (
os.path.join(sys.prefix, 'var', 'log')
.replace('/usr/var', '/var')
)
if not os.path.isdir(var_log):
os.makedirs(var_log)
return var_log | Find a directory suitable for writing log files. It uses sys.prefix
to use a path relative to the root. If sys.prefix is /usr, it's the
system Python, so use /var/log. |
def _get_more_data(self, file, timeout):
timeout = datetime.timedelta(seconds=timeout)
timer = Stopwatch()
while timer.split() < timeout:
data = file.read()
if data:
return data
raise RuntimeError("Timeout") | Return data from the file, if available. If no data is received
by the timeout, then raise RuntimeError. |
def _run_env(self):
env = dict(os.environ)
env.update(
getattr(self, 'env', {}),
PYTHONUSERBASE=self.env_path,
PIP_USER="1",
)
self._disable_venv(env)
return env | Augment the current environment providing the PYTHONUSERBASE. |
def _disable_venv(self, env):
venv = env.pop('VIRTUAL_ENV', None)
if venv:
venv_path, sep, env['PATH'] = env['PATH'].partition(os.pathsep) | Disable virtualenv and venv in the environment. |
def create_env(self):
root = path.Path(os.environ.get('SERVICES_ROOT', 'services'))
self.env_path = (root / self.name).abspath()
cmd = [
self.python,
'-c', 'import site; print(site.getusersitepackages())',
]
out = subprocess.check_output(cmd, env=... | Create a PEP-370 environment |
def create_states_geo_zone(cls, states_geo_zone, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._create_states_geo_zone_with_http_info(states_geo_zone, **kwargs)
else:
(data) = cls._create_states_geo_zone_with_http_info(stat... | Create StatesGeoZone
Create a new StatesGeoZone
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_states_geo_zone(states_geo_zone, async=True)
>>> result = thread.get()
:param as... |
def delete_states_geo_zone_by_id(cls, states_geo_zone_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._delete_states_geo_zone_by_id_with_http_info(states_geo_zone_id, **kwargs)
else:
(data) = cls._delete_states_geo_zone_b... | Delete StatesGeoZone
Delete an instance of StatesGeoZone by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_states_geo_zone_by_id(states_geo_zone_id, async=True)
>>> result = th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.