code stringlengths 52 7.75k | docs stringlengths 1 5.85k |
|---|---|
def MultimodeCombine(pupils):
fluxes=[np.vdot(pupils[i],pupils[i]).real for i in range(len(pupils))]
coherentFluxes=[np.vdot(pupils[i],pupils[j])
for i in range(1,len(pupils))
for j in range(i)]
return fluxes,coherentFluxes | Return the instantaneous coherent fluxes and photometric fluxes for a
multiway multimode combiner (no spatial filtering) |
def to_unicode(s):
if not isinstance(s, TEXT):
if not isinstance(s, bytes):
raise TypeError('You are required to pass either unicode or '
'bytes here, not: %r (%s)' % (type(s), s))
try:
s = s.decode('utf-8')
except UnicodeDecodeError a... | Convert to unicode, raise exception with instructive error
message if s is not unicode, ascii, or utf-8. |
def to_postdata(self):
items = []
for k, v in sorted(self.items()): # predictable for testing
items.append((k.encode('utf-8'), to_utf8_optional_iterator(v)))
# tell urlencode to deal with sequence values and map them correctly
# to resulting querystring. for exampl... | Serialize as post data for a POST request. |
def to_url(self):
base_url = urlparse(self.url)
query = parse_qs(base_url.query)
for k, v in self.items():
query.setdefault(k, []).append(to_utf8_optional_iterator(v))
scheme = base_url.scheme
netloc = base_url.netloc
path = base_url.path
par... | Serialize as a URL for a GET request. |
def _split_header(header):
params = {}
parts = header.split(',')
for param in parts:
# Ignore realm parameter.
if param.lower().startswith('realm='):
continue
# Remove whitespace.
param = param.strip()
# Split k... | Turn Authorization: header into parameters. |
def fetch_request_token(self, oauth_request):
try:
# Get the request token for authorization.
token = self._get_token(oauth_request, 'request')
except Error:
# No token required for the initial token request.
version = self._get_version(oauth_requ... | Processes a request_token request and returns the
request token on success. |
def fetch_access_token(self, oauth_request):
version = self._get_version(oauth_request)
consumer = self._get_consumer(oauth_request)
try:
verifier = self._get_verifier(oauth_request)
except Error:
verifier = None
# Get the request token.
t... | Processes an access_token request and returns the
access token on success. |
def _get_token(self, oauth_request, token_type='access'):
token_field = oauth_request.get_parameter('oauth_token')
token = self.data_store.lookup_token(token_type, token_field)
if not token:
raise OAuthError('Invalid %s token: %s' % (token_type, token_field))
return ... | Try to find the token for the provided request token key. |
def clean_chars(value):
"Hack to remove non-ASCII data. Should convert to Unicode: code page 437?"
value = value.replace('\xb9', ' ')
value = value.replace('\xf8', ' ')
value = value.replace('\xab', ' ')
value = value.replace('\xa7', ' ')
value = value.replace('\xa8', ' ')
value = value.repl... | Hack to remove non-ASCII data. Should convert to Unicode: code page 437? |
def vals(self, x, *args, **kwargs):
x = np.atleast_1d(x)
return self._vals(x, *args, **kwargs) | [Docstring] |
def fit_lsq(self, x, y_obs, params_start=None):
# Set up variables
x = np.atleast_1d(x)
y_obs = np.atleast_1d(y_obs)
if not params_start:
params_start = np.ones(self.n_parameters)
# Error checking
if len(x) != len(y_obs):
raise ValueErro... | Fit curve by method of least squares.
Parameters
----------
x : iterable
Independent variable
y_obs : iterable
Dependent variable (values observed at x)
params_start : iterable
Optional start values for all parameters. Default 1.
Retu... |
def fit_lsq(self, df):
tdf = df.set_index('div')
return tdf.ix['1,1']['n_spp'], tdf.ix['1,1']['n_individs'] | Parameterize generic SAR curve from empirical data set
Parameters
----------
df : DataFrame
Result data frame from empirical SAR analysis
Notes
-----
Simply returns S0 and N0 from empirical SAR output, which are two fixed
parameters of METE SAR and E... |
def draw(self):
self.update_all()
self.vertex_list.draw(self.gl)
pyglet.gl.glLoadIdentity() | 使用draw方法将图形绘制在窗口里 |
def update_all(self):
self.update_points()
self.update_vertex_list()
self.update_anchor()
pyglet.gl.glLoadIdentity() # reset gl
pyglet.gl.glLineWidth(self.line_width)
pyglet.gl.glPointSize(self.point_size)
self.transform.update_gl()
# handle sh... | 在绘制之前,针对形变进行计算,通过设置openGL的属性来达到绘制出变形的图形 |
def update_vertex_list(self):
color = color_to_tuple(self.color, self.opacity)
length = len(self.points) // 2
self.vertex_list = pyglet.graphics.vertex_list(
length,
('v2f', self.points),
('c4B', color * length)) | 使用pyglet来绘制基本图形之前,转为pyglet识别的属性 |
def update_anchor(self):
t = self.transform
self.update_collision_rect()
if t.anchor_x_r and t.anchor_y_r:
t.anchor_x = self.min_x + (self.max_x - self.min_x) * t.anchor_x_r
t.anchor_y = self.min_y + (self.max_y - self.min_y) * t.anchor_y_r | 如果是使用set_anchor_rate来设定锚点,那么就需要不停的更新锚点的位置 |
def bulk_send(self, topic, kmsgs):
try:
self.client.do_request(
method="POST", path="/topic/{}".format(topic), data=[
dict(Value=k.MARSHMALLOW_SCHEMA.dump(k)) for k in kmsgs
]
)
return Result(stdout="{} message(s) ... | Send a batch of messages
:param str topic: a kafka topic
:param ksr.transport.Message kmsgs: Messages to serialize
:return: Execution result
:rtype: kser.result.Result |
def send(self, topic, kmsg):
try:
self.client.do_request(
method="POST", params=dict(format="raw"),
path="/topic/{}".format(topic),
data=kmsg.MARSHMALLOW_SCHEMA.dump(kmsg)
)
result = Result(
uuid=kmsg.uu... | Send the message into the given topic
:param str topic: a kafka topic
:param ksr.transport.Message kmsg: Message to serialize
:return: Execution result
:rtype: kser.result.Result |
def batch_update(self, command, rows):
request = {
"database": {
"alias": self.__options['dbAlias']
},
"batchUpdate": {
"command": command,
"rows": rows,
"shardKey": self.__options.get('shardKey'),
... | Для массовой вставки умеренных объемов 1-5к записей за вызов
:param command: SQL insert or updtae
:param rows: list of dict
:return: dict |
def update(self, command, params=None):
request = {
"database": {
"alias": self.__options['dbAlias']
},
"dbQuery": {
"command": command,
"parameters": params,
"shardKey": self.__options.get('shardKey'),
... | Запросы на INSERT, UPDATE, DELETE и пр. не возвращающие результата должны выполняться через этот метод
Исключение такие запросы с RETURNING для PostgreSQL
:param command: SQL запрос
:param params: Параметры для prepared statements
:rtype: object DataResult |
def one(self, command, params=None):
dr = self.query(command, params)
if dr['rows']:
return dr['rows'][0]
else:
return None | Возвращает первую строку ответа, полученного через query
> db.query('SELECT * FORM users WHERE id=:id', {"id":MY_USER_ID})
:param command: SQL запрос
:param params: Параметры для prepared statements
:rtype: dict |
def all(self, command, params=None):
dr = self.query(command, params)
return dr['rows'] | Возвращает строки ответа, полученного через query
> db.query('SELECT * FORM users WHERE id=:id', {"id":MY_USER_ID})
:param command: SQL запрос
:param params: Параметры для prepared statements
:rtype: list of dict |
def after_insert(mapper, connection, target):
record_after_update.send(CmtRECORDCOMMENT, recid=target.id_bibrec)
from .api import get_reply_order_cache_data
if target.in_reply_to_id_cmtRECORDCOMMENT > 0:
parent = CmtRECORDCOMMENT.query.get(
target.in_reply_to_id_cmtRECORDCOMMENT)
... | Update reply order cache and send record-after-update signal. |
def is_collapsed(self, id_user):
return CmtCOLLAPSED.query.filter(db.and_(
CmtCOLLAPSED.id_bibrec == self.id_bibrec,
CmtCOLLAPSED.id_cmtRECORDCOMMENT == self.id,
CmtCOLLAPSED.id_user == id_user)).count() > 0 | Return true if the comment is collapsed by user. |
def collapse(self, id_user):
c = CmtCOLLAPSED(id_bibrec=self.id_bibrec, id_cmtRECORDCOMMENT=self.id,
id_user=id_user)
db.session.add(c)
db.session.commit() | Collapse comment beloging to user. |
def expand(self, id_user):
CmtCOLLAPSED.query.filter(db.and_(
CmtCOLLAPSED.id_bibrec == self.id_bibrec,
CmtCOLLAPSED.id_cmtRECORDCOMMENT == self.id,
CmtCOLLAPSED.id_user == id_user)).delete(synchronize_session=False) | Expand comment beloging to user. |
def count(cls, *criteria, **filters):
return cls.query.filter(*criteria).filter_by(**filters).count() | Count how many comments. |
def get_version(version=None):
if version[4] > 0: # 0.2.1-alpha.1
return "%s.%s.%s-%s.%s" % (version[0], version[1], version[2], version[3], version[4])
elif version[3] != '': # 0.2.1-alpha
return "%s.%s.%s-%s" % (version[0], version[1], version[2], version[3])
elif version[2] > 0: ... | Returns a tuple of the django version. If version argument is non-empty,
then checks for correctness of the tuple provided. |
def list_all_refund_operations(cls, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._list_all_refund_operations_with_http_info(**kwargs)
else:
(data) = cls._list_all_refund_operations_with_http_info(**kwargs)
retu... | List RefundOperations
Return a list of RefundOperations
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_refund_operations(async=True)
>>> result = thread.get()
:param async b... |
def _push_packet(self, packet):
self._read_queue.append((decode(packet), packet))
if self._read_waiter is not None:
w, self._read_waiter = self._read_waiter, None
w.set_result(None) | Appends a packet to the internal read queue, or notifies
a waiting listener that a packet just came in. |
def _read_data(self):
while True:
try:
data = yield from self._socket.recv()
except asyncio.CancelledError:
break
except ConnectionClosed:
break
self._push_packet(data)
self._loop.call_soon(self.cl... | Reads data from the connection and adds it to _push_packet,
until the connection is closed or the task in cancelled. |
def wait_message(self):
if self._state != states['open']:
return False
if len(self._read_queue) > 0:
return True
assert self._read_waiter is None or self._read_waiter.cancelled(), \
"You may only use one wait_message() per connection."
self.... | Waits until a connection is available on the wire, or until
the connection is in a state that it can't accept messages.
It returns True if a message is available, False otherwise. |
def get_reservation_ports(session, reservation_id, model_name='Generic Traffic Generator Port'):
reservation_ports = []
reservation = session.GetReservationDetails(reservation_id).ReservationDescription
for resource in reservation.Resources:
if resource.ResourceModelName == model_name:
... | Get all Generic Traffic Generator Port in reservation.
:return: list of all Generic Traffic Generator Port resource objects in reservation |
def get_reservation_resources(session, reservation_id, *models):
models_resources = []
reservation = session.GetReservationDetails(reservation_id).ReservationDescription
for resource in reservation.Resources:
if resource.ResourceModelName in models:
models_resources.append(resource... | Get all resources of given models in reservation.
:param session: CloudShell session
:type session: cloudshell.api.cloudshell_api.CloudShellAPISession
:param reservation_id: active reservation ID
:param models: list of requested models
:return: list of all resources of models in reservation |
def change_issue_status(self, issue_id, status_id: str):
self.__metadb.update("""
update meta.issue set
issue_status_id=:status_id,
assignee_user_id=valera_user_id(),
last_user_id=valera_user_id()
where id = :issue_id
... | Смета статуса тикета
:param issue_id: int
:param status_id: int |
def get_current_container_id(read_from='/proc/self/cgroup'):
if not os.path.exists(read_from):
return
with open(read_from, 'r') as cgroup:
for line in cgroup:
if re.match('.*/[0-9a-f]{64}$', line.strip()):
return re.sub('.*/([0-9a-f]{64})$', '\\1', line.strip()... | Get the ID of the container the application is currently running in,
otherwise return `None` if not running in a container.
This is a best-effort guess, based on cgroups.
:param read_from: the cgroups file to read from (default: `/proc/self/cgroup`) |
def read_configuration(key, path=None, default=None, single_config=False, fallback_to_env=True):
if path and os.path.exists(path):
with open(path, 'r') as config_file:
if single_config:
return config_file.read()
for line in config_file:
if line.... | Read configuration from a file, Docker config or secret or from the environment variables.
:param key: the configuration key
:param path: the path of the configuration file (regular file or Docker config or secret)
:param default: the default value when not found elsewhere (default: `None`)
:param sing... |
def CleanString(s):
punc = (' ', '-', '\'', '.', '&', '&', '+', '@')
pieces = []
for part in s.split():
part = part.strip()
for p in punc:
part = part.replace(p, '_')
part = part.strip('_')
part = part.lower()
pieces.append(part)
return '_'.jo... | Cleans up string.
Doesn't catch everything, appears to sometimes allow double underscores
to occur as a result of replacements. |
def DedupVcardFilenames(vcard_dict):
remove_keys = []
add_pairs = []
for k, v in vcard_dict.items():
if not len(v) > 1:
continue
for idx, vcard in enumerate(v):
fname, ext = os.path.splitext(k)
fname = '{}-{}'.format(fname, idx + 1)
fname ... | Make sure every vCard in the dictionary has a unique filename. |
def WriteVcard(filename, vcard, fopen=codecs.open):
if os.access(filename, os.F_OK):
logger.warning('File exists at "{}", skipping.'.format(filename))
return False
try:
with fopen(filename, 'w', encoding='utf-8') as f:
logger.debug('Writing {}:\n{}'.format(filename, u(vc... | Writes a vCard into the given filename. |
def create_cash_on_delivery_payment(cls, cash_on_delivery_payment, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._create_cash_on_delivery_payment_with_http_info(cash_on_delivery_payment, **kwargs)
else:
(data) = cls._create... | Create CashOnDeliveryPayment
Create a new CashOnDeliveryPayment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_cash_on_delivery_payment(cash_on_delivery_payment, async=True)
>>> result... |
def delete_cash_on_delivery_payment_by_id(cls, cash_on_delivery_payment_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._delete_cash_on_delivery_payment_by_id_with_http_info(cash_on_delivery_payment_id, **kwargs)
else:
(d... | Delete CashOnDeliveryPayment
Delete an instance of CashOnDeliveryPayment 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_cash_on_delivery_payment_by_id(cash_on_delivery_payment_id, a... |
def get_cash_on_delivery_payment_by_id(cls, cash_on_delivery_payment_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._get_cash_on_delivery_payment_by_id_with_http_info(cash_on_delivery_payment_id, **kwargs)
else:
(data) =... | Find CashOnDeliveryPayment
Return single instance of CashOnDeliveryPayment 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_cash_on_delivery_payment_by_id(cash_on_delivery_payment_id, as... |
def list_all_cash_on_delivery_payments(cls, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._list_all_cash_on_delivery_payments_with_http_info(**kwargs)
else:
(data) = cls._list_all_cash_on_delivery_payments_with_http_info(**... | List CashOnDeliveryPayments
Return a list of CashOnDeliveryPayments
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_cash_on_delivery_payments(async=True)
>>> result = thread.get()
... |
def replace_cash_on_delivery_payment_by_id(cls, cash_on_delivery_payment_id, cash_on_delivery_payment, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._replace_cash_on_delivery_payment_by_id_with_http_info(cash_on_delivery_payment_id, cash_on_de... | Replace CashOnDeliveryPayment
Replace all attributes of CashOnDeliveryPayment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replace_cash_on_delivery_payment_by_id(cash_on_delivery_payment_id, cash_o... |
def update_cash_on_delivery_payment_by_id(cls, cash_on_delivery_payment_id, cash_on_delivery_payment, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._update_cash_on_delivery_payment_by_id_with_http_info(cash_on_delivery_payment_id, cash_on_deli... | Update CashOnDeliveryPayment
Update attributes of CashOnDeliveryPayment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_cash_on_delivery_payment_by_id(cash_on_delivery_payment_id, cash_on_deliv... |
def dial(self, target):
'''
connects to a node
:param url: string (optional) - resource in which to connect.
if not provided, will use default for the stage
:returns: provider, error
'''
if not target:
return None, "target network must be specified w... | connects to a node
:param url: string (optional) - resource in which to connect.
if not provided, will use default for the stage
:returns: provider, error |
async def listen(self, address, target):
'''
starts event listener for the contract
:return:
'''
if not address:
return None, "listening address not provided"
EZO.log.info(bright("hello ezo::listening to address: {}".format(blue(address))))
interval ... | starts event listener for the contract
:return: |
def send(ezo, name, method, data, target):
'''
runs a transaction on a contract method
:param ezo: ezo instance
:param name: name of the Contract
:param method: name of the contract method
:param data: formatted data to send to the contract method
:return:
... | runs a transaction on a contract method
:param ezo: ezo instance
:param name: name of the Contract
:param method: name of the contract method
:param data: formatted data to send to the contract method
:return: |
def get(name, ezo):
'''
get the latest compiled contract instance by contract name
:param name:
:param ezo:
:return:
'''
key = DB.pkey([EZO.CONTRACT, name])
cp, err = ezo.db.get(key)
if err:
return None, err
if not cp:
... | get the latest compiled contract instance by contract name
:param name:
:param ezo:
:return: |
def create_from_hash(hash, ezo):
'''
given the hash of a contract, returns a contract from the data store
:param hash: (string) hash of the contract source code
:param ezo: ezo instance
:return: contract instance, error
'''
cp, err = ezo.db.get("contracts", hash... | given the hash of a contract, returns a contract from the data store
:param hash: (string) hash of the contract source code
:param ezo: ezo instance
:return: contract instance, error |
def load(filepath):
'''
loads a contract file
:param filepath: (string) - contract filename
:return: source, err
'''
try:
with open(filepath, "r") as fh:
source = fh.read()
except Exception as e:
return None, e
ret... | loads a contract file
:param filepath: (string) - contract filename
:return: source, err |
def compile(source, ezo):
'''
compiles the source code
:param source: (string) - contract source code
:param ezo: - ezo reference for Contract object creation
:return: (list) compiled source
'''
try:
compiled = compile_source(source)
compi... | compiles the source code
:param source: (string) - contract source code
:param ezo: - ezo reference for Contract object creation
:return: (list) compiled source |
def get_address(name, hash, db, target=None):
'''
fetches the contract address of deployment
:param hash: the contract file hash
:return: (string) address of the contract
error, if any
'''
key = DB.pkey([EZO.DEPLOYED, name, target, hash])
d, er... | fetches the contract address of deployment
:param hash: the contract file hash
:return: (string) address of the contract
error, if any |
def put(contract_name, abi):
'''
save the contract's ABI
:param contract_name: string - name of the contract
:param abi: the contract's abi JSON file
:return: None, None if saved okay
None, error is an error
'''
if not Catalog.path:
... | save the contract's ABI
:param contract_name: string - name of the contract
:param abi: the contract's abi JSON file
:return: None, None if saved okay
None, error is an error |
def get(contract_name):
'''
return the contract's ABI, marshaled into python dict
:param contract_name: string - name of the contract to load
:return: ABI, None - if successful
None, error - if error
'''
if not Catalog.path:
return None, "pat... | return the contract's ABI, marshaled into python dict
:param contract_name: string - name of the contract to load
:return: ABI, None - if successful
None, error - if error |
def open(self):
'''
attempts to open the database. if it gets a locked message, it will wait one second and try
again. if it is still locked, it will return an error
:return: None, None if successful
None, error if error
'''
cycle = 2
count = 0
... | attempts to open the database. if it gets a locked message, it will wait one second and try
again. if it is still locked, it will return an error
:return: None, None if successful
None, error if error |
def transform_from_chomsky_normal_form(root):
# type: (Nonterminal) -> Nonterminal
# Transforms leaves
items = Traversing.post_order(root)
items = filter(lambda x: isinstance(x, (ChomskyTermRule, ChomskyTerminalReplaceRule)), items)
de = deque(items)
while de:
rule = de.popleft()
... | Transform the tree created by grammar in the Chomsky Normal Form to original rules.
:param root: Root of parsed tree.
:return: Modified tree. |
def create_return_operation(cls, return_operation, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._create_return_operation_with_http_info(return_operation, **kwargs)
else:
(data) = cls._create_return_operation_with_http_info... | Create ReturnOperation
Create a new ReturnOperation
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_return_operation(return_operation, async=True)
>>> result = thread.get()
:pa... |
def delete_return_operation_by_id(cls, return_operation_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._delete_return_operation_by_id_with_http_info(return_operation_id, **kwargs)
else:
(data) = cls._delete_return_operat... | Delete ReturnOperation
Delete an instance of ReturnOperation 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_return_operation_by_id(return_operation_id, async=True)
>>> resul... |
def get_return_operation_by_id(cls, return_operation_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._get_return_operation_by_id_with_http_info(return_operation_id, **kwargs)
else:
(data) = cls._get_return_operation_by_id... | Find ReturnOperation
Return single instance of ReturnOperation 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_return_operation_by_id(return_operation_id, async=True)
>>> result... |
def list_all_return_operations(cls, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._list_all_return_operations_with_http_info(**kwargs)
else:
(data) = cls._list_all_return_operations_with_http_info(**kwargs)
retu... | List ReturnOperations
Return a list of ReturnOperations
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_return_operations(async=True)
>>> result = thread.get()
:param async b... |
def replace_return_operation_by_id(cls, return_operation_id, return_operation, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._replace_return_operation_by_id_with_http_info(return_operation_id, return_operation, **kwargs)
else:
... | Replace ReturnOperation
Replace all attributes of ReturnOperation
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replace_return_operation_by_id(return_operation_id, return_operation, async=True)
... |
def update_return_operation_by_id(cls, return_operation_id, return_operation, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._update_return_operation_by_id_with_http_info(return_operation_id, return_operation, **kwargs)
else:
... | Update ReturnOperation
Update attributes of ReturnOperation
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_return_operation_by_id(return_operation_id, return_operation, async=True)
>>>... |
def console_logger(
level="WARNING"
):
################ > IMPORTS ################
## STANDARD LIB ##
import logging
import logging.config
## THIRD PARTY ##
import yaml
try:
yaml.warnings({'YAMLLoadWarning': False})
except:
pass
## LOCAL APPLICATION ##
... | *Setup and return a console logger*
**Key Arguments:**
- ``level`` -- the level of logging required
**Return:**
- ``logger`` -- the console logger
**Usage:**
.. code-block:: python
from fundamentals import logs
log = logs.console_logger(
l... |
def doRollover(self):
# Rotate the file first.
handlers.RotatingFileHandler.doRollover(self)
# Add group write to the current permissions.
currMode = os.stat(self.baseFilename).st_mode
os.chmod(self.baseFilename, currMode | stat.S_IWGRP |
stat.S_IRGRP |... | *Override base class method to make the new log file group writable.* |
def get_creators(self, attribute='creatorName'):
if 'creators' in self.xml:
if isinstance(self.xml['creators']['creator'], list):
return [c[attribute] for c in self.xml['creators']['creator']]
else:
return self.xml['creators']['creator'][attribute... | Get DataCite creators. |
def get_dates(self):
if 'dates' in self.xml:
if isinstance(self.xml['dates']['date'], dict):
return self.xml['dates']['date'].values()[0]
return self.xml['dates']['date']
return None | Get DataCite dates. |
def get_description(self, description_type='Abstract'):
if 'descriptions' in self.xml:
if isinstance(self.xml['descriptions']['description'], list):
for description in self.xml['descriptions']['description']:
if description_type in description:
... | Get DataCite description. |
def itemgetter(iterable, indexes):
''' same functionality as operator.itemgetter except, this one supports
both positive and negative indexing of generators as well '''
indexes = indexes if isinstance(indexes, tuple) else tuple(indexes)
assert all(isinstance(i, int) for i in indexes), 'indexes needs... | same functionality as operator.itemgetter except, this one supports
both positive and negative indexing of generators as well |
def refresh(self):
try:
# suport for RPiDisplay SSD1306 driver
self.Display.setImage( self._catchCurrentViewContent() )
except:
try:
# suport for Adafruit SSD1306 driver
self.Display.image( self._catchCurrentViewContent() )
... | !
\~english
Update current view content to display
Supported: JMRPiDisplay_SSD1306 and Adafruit SSD1306 driver
\~chinese
更新当前视图内容到显示屏
支持: JMRPiDisplay_SSD1306 和 Adafruit SSD1306 driver |
def google_register(username:str, email:str, full_name:str, google_id:int, bio:str, token:str=None):
auth_data_model = apps.get_model("users", "AuthData")
user_model = apps.get_model("users", "User")
try:
# Google user association exist?
auth_data = auth_data_model.objects.get(key="goo... | Register a new user from google.
This can raise `exc.IntegrityError` exceptions in
case of conflics found.
:returns: User |
def crystalfield(interaction=np.linspace(0, 20, 201), \
j_hund=np.linspace(0, 0.35, 71)):
slsp = Spinon(slaves=6, orbitals=3, hopping=[0.5]*6, \
populations=[1, 1, 1.5, 1.5, 1.5, 1.5])
zet = []
for hund_cu in j_hund:
zet.append(ssplt.solve_loop(slsp, interaction... | Aimed at reproducing the figure in paper
L. de'Medici, PRB 83,205112 (2011)
showing the phase diagram of a 3 band hubbard with one lifted band
fixed population 1:1.5,1.5 |
def show_feature(user, feature):
FeatureFlipper = get_feature_model()
return FeatureFlipper.objects.show_feature(user, feature) | Return True/False whether the assigned feature can be displayed. This is
primarily used in the template tag to determine whether to render the
content inside itself. |
def do_flipper(parser, token):
nodelist = parser.parse(('endflipper',))
tag_name, user_key, feature = token.split_contents()
parser.delete_first_token()
return FlipperNode(nodelist, user_key, feature) | The flipper tag takes two arguments: the user to look up and the feature
to compare against. |
def render(self, context):
user = self._get_value(self.user_key, context)
feature = self._get_value(self.feature, context)
if feature is None:
return ''
allowed = show_feature(user, feature)
return self.nodelist.render(context) if allowed else '' | Handle the actual rendering. |
def _get_value(self, key, context):
string_quotes = ('"', "'")
if key[0] in string_quotes and key[-1] in string_quotes:
return key[1:-1]
if key in string.digits:
return int(key)
return context.get(key, None) | Works out whether key is a value or if it's a variable referencing a
value in context and returns the correct value. |
def client(self, client_name, **params):
if client_name not in self.cfg.clients:
raise OAuthException('Unconfigured client: %s' % client_name)
if client_name not in ClientRegistry.clients:
raise OAuthException('Unsupported services: %s' % client_name)
params = ... | Initialize OAuth client from registry. |
def refresh(self, client_name, refresh_token, **params):
client = self.client(client_name, logger=self.app.logger)
return client.get_access_token(refresh_token, grant_type='refresh_token', **params) | Get refresh token.
:param client_name: A name one of configured clients
:param redirect_uri: An URI for authorization redirect
:returns: a coroutine |
def chain(*args):
has_iter = partial(hasattr, name='__iter__')
# check if a single iterable is being passed for
# the case that it's a generator of generators
if len(args) == 1 and hasattr(args[0], '__iter__'):
args = args[0]
for arg in args:
# if the arg is iterable
if... | itertools.chain, just better |
def get_all_celcius_commands():
p = subprocess.Popen(["crontab", "-l"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
return [x for x in out.split('\n') if 'CJOBID' in x] | Query cron for all celcius commands |
def create_option_set(cls, option_set, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._create_option_set_with_http_info(option_set, **kwargs)
else:
(data) = cls._create_option_set_with_http_info(option_set, **kwargs)
... | Create OptionSet
Create a new OptionSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_option_set(option_set, async=True)
>>> result = thread.get()
:param async bool
:... |
def delete_option_set_by_id(cls, option_set_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._delete_option_set_by_id_with_http_info(option_set_id, **kwargs)
else:
(data) = cls._delete_option_set_by_id_with_http_info(optio... | Delete OptionSet
Delete an instance of OptionSet 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_option_set_by_id(option_set_id, async=True)
>>> result = thread.get()
... |
def get_option_set_by_id(cls, option_set_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._get_option_set_by_id_with_http_info(option_set_id, **kwargs)
else:
(data) = cls._get_option_set_by_id_with_http_info(option_set_id,... | Find OptionSet
Return single instance of OptionSet 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_option_set_by_id(option_set_id, async=True)
>>> result = thread.get()
... |
def list_all_option_sets(cls, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._list_all_option_sets_with_http_info(**kwargs)
else:
(data) = cls._list_all_option_sets_with_http_info(**kwargs)
return data | List OptionSets
Return a list of OptionSets
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_option_sets(async=True)
>>> result = thread.get()
:param async bool
:param... |
def replace_option_set_by_id(cls, option_set_id, option_set, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._replace_option_set_by_id_with_http_info(option_set_id, option_set, **kwargs)
else:
(data) = cls._replace_option_set... | Replace OptionSet
Replace all attributes of OptionSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replace_option_set_by_id(option_set_id, option_set, async=True)
>>> result = thread.get()
... |
def update_option_set_by_id(cls, option_set_id, option_set, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._update_option_set_by_id_with_http_info(option_set_id, option_set, **kwargs)
else:
(data) = cls._update_option_set_by... | Update OptionSet
Update attributes of OptionSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_option_set_by_id(option_set_id, option_set, async=True)
>>> result = thread.get()
... |
def VcardFieldsEqual(field1, field2):
field1_vals = set([ str(f.value) for f in field1 ])
field2_vals = set([ str(f.value) for f in field2 ])
if field1_vals == field2_vals:
return True
else:
return False | Handle comparing vCard fields where inputs are lists of components.
Handle parameters? Are any used aside from 'TYPE'?
Note: force cast to string to compare sub-objects like Name and Address |
def VcardMergeListFields(field1, field2):
field_dict = {}
for f in field1 + field2:
field_dict[str(f)] = f
return list(field_dict.values()) | Handle merging list fields that may include some overlap. |
def SetVcardField(new_vcard, field_name, values):
for val in values:
new_field = new_vcard.add(field_name)
new_field.value = val.value
if val.params:
new_field.params = val.params
return new_vcard | Set vCard field values and parameters on a new vCard. |
def CopyVcardFields(new_vcard, auth_vcard, field_names):
for field in field_names:
value_list = auth_vcard.contents.get(field)
new_vcard = SetVcardField(new_vcard, field, value_list)
return new_vcard | Copy vCard field values from an authoritative vCard into a new one. |
def MergeVcards(vcard1, vcard2):
new_vcard = vobject.vCard()
vcard1_fields = set(vcard1.contents.keys())
vcard2_fields = set(vcard2.contents.keys())
mutual_fields = vcard1_fields.intersection(vcard2_fields)
logger.debug('Potentially conflicting fields: {}'.format(mutual_fields))
for field i... | Create a new vCard and populate it. |
def SelectFieldPrompt(field_name, context_str, *options):
option_format_str = '[ {} ] "{}"'
option_dict = {}
print(context_str)
print('Please select one of the following options for field "{}"'.format(
field_name)
)
for cnt, option in enumerate(options):
option_dict['{}'.for... | Prompts user to pick from provided options.
It is possible to provide a function as an option although it is
not yet tested. This could allow a user to be prompted to provide
their own value rather than the listed options.
Args:
field_name (string): Name of the field.
context_str (string)... |
def make_fixture(model_class, **kwargs):
all_fields = get_fields(model_class)
fields_for_random_generation = map(
lambda x: getattr(model_class, x), all_fields
)
overrides = {}
for kwarg, value in kwargs.items():
if kwarg in all_fields:
kwarg_field = getattr(model... | Take the model_klass and generate a fixure for it
Args:
model_class (MongoEngine Document): model for which a fixture
is needed
kwargs (dict): any overrides instead of random values
Returns:
dict for now, other fixture types are not implemented yet |
def get_fields(model_class):
return [
attr for attr, value in model_class.__dict__.items()
if issubclass(type(value), (mongo.base.BaseField, mongo.EmbeddedDocumentField)) # noqa
] | Pass in a mongo model class and extract all the attributes which
are mongoengine fields
Returns:
list of strings of field attributes |
def get_random_values(fields):
values = {}
for field in fields:
try:
value = get_random_value(field)
except AttributeError:
# this can only really occur if the field is not implemented yet.
# Silencing the exception during the prototype phase
... | Pass in a list of fields (as strings) to get a dict with the
field name as a key and a randomly generated value as another |
def head_bucket(self, name):
try:
self.s3.head_bucket(Bucket=name)
info = self.s3.get_bucket_website(Bucket=self.sitename)
if not info:
return False, 404, "Configure improrperly"
return True, None, None
except botocore.exceptions.C... | Check if a bucket exists
:param name:
:return: |
def purge_files(self, exclude_files=["index.html", "error.html"]):
for chunk in utils.chunk_list(self._get_manifest_data(), 1000):
try:
self.s3.delete_objects(
Bucket=self.sitename,
Delete={
'Objects': [{"Key": ... | To delete files that are in the manifest
:param excludes_files: list : files to not delete
:return: |
def create_manifest_from_s3_files(self):
for k in self.s3.list_objects(Bucket=self.sitename)['Contents']:
key = k["Key"]
files = []
if key not in [self.manifest_file]:
files.append(key)
self._set_manifest_data(files) | To create a manifest db for the current
:return: |
def _set_manifest_data(self, files_list):
if files_list:
data = ",".join(files_list)
self.s3.put_object(Bucket=self.sitename,
Key=self.manifest_file,
Body=data,
ACL='private') | Write manifest files
:param files_list: list
:return: |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.