index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
993,600 | 4dbd1398e4b40b9ecf78df6cf26a0b820323205f | import math
from functools import reduce
from collections import deque
from heapq import heappush,heappop
import sys
sys.setrecursionlimit(10**7)
def input():
return sys.stdin.readline().strip()
# スペース区切りの入力を読み込んで数値リストにして返します。
def get_nums_l():
return [ int(s) for s in input().split(" ")]
# 改行区切りの入力をn行読み込んで数値リストにして返します。
def get_nums_n(n):
return [ int(input()) for _ in range(n)]
# 改行またはスペース区切りの入力をすべて読み込んでイテレータを返します。
def get_all_int():
return map(int, open(0).read().split())
def rangeI(it, l, r):
for i, e in enumerate(it):
if l <= i < r:
yield e
elif l >= r:
break
def log(*args):
print("DEBUG:", *args, file=sys.stderr)
INF = 999999999999999999999999
MOD = 10**9+7
n = int(input())
edges = [ [] for _ in range(n+1) ]
for _ in range(n-1):
a,b = get_nums_l()
edges[a].append(b)
edges[b].append(a)
hq = []
heappush(hq, 1)
ans = []
visited = set()
while hq:
u = heappop(hq)
ans.append(u)
visited.add(u)
for v in edges[u]:
if v not in visited:
heappush(hq, v)
print(" ".join(map(str, ans)))
|
993,601 | eaafcb6b0a5b9216bf5908310573621d8fc68917 | from appium import webdriver
class TestApp:
def setup(self):
capabilities = {}
# Android平台测试
capabilities['platformName'] = 'Android'
# 测试手机版本为5.0
capabilities['platformVersion'] = '5.1.1'
capabilities['deviceName'] = '127.0.0.1:62001'
capabilities['appPackage'] = 'com.android.systemui'
capabilities['appActivity'] = '.Launcher'
capabilities['noReset'] = 'True'
# 连接测试机所在服务器服务器
self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', capabilities)
self.driver.implicitly_wait(8)
def teardown(self):
pass
def test_app1(self):
pass |
993,602 | 570ed1c0790e47a84601084ca67515aa14366729 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 2 13:22:03 2020
@author: zhouming
"""
import torch,pickle,os
from os.path import join as pjoin
from PIL import Image
import numpy as np
import pandas as pd
from skimage import transform
from dnnbrain.dnn.models import AlexNet
from dnnbrain.dnn.base import ip
from dnnbrain.dnn.core import Mask
from dnnbrain.dnn.algo import SynthesisImage
import matplotlib.pyplot as plt
pth = r'/nfs/s2/userhome/zhouming/workingdir/optimal_invariance/DataStore'
file = pjoin(pth,'TransferStimuli-conv3_21.pickle')
with open(file,'rb') as f:
img_set = pickle.load(f)
activ_dict = {}
mask = Mask(layer='conv3',channels=[21])
pic = img_set['top2_sub2_move:50'].astype('uint8')
plt.subplot(121)
plt.imshow(pic)
pic = pic[np.newaxis,:,:,:].transpose(0,3,1,2)
activ = dnn.compute_activation(pic,mask).get('conv3')[0,0,6,6]
activ_dict['top2_sub2_move:50'] = activ
pic = img_set['top2_sub2_move:-49'].astype('uint8')
plt.subplot(122)
plt.imshow(pic)
pic = pic[np.newaxis,:,:,:].transpose(0,3,1,2)
activ = dnn.compute_activation(pic,mask).get('conv3')[0,0,6,6]
activ_dict['top2_sub2_move:-49'] = activ
print(activ_dict)
'''
pth = r'/nfs/s2/userhome/zhouming/workingdir/optimal_invariance/DataStore'
file = pjoin(pth,'TransferStimuli-conv3_21.pickle')
name = ['top2_sub2_move:50','top2_sub2_move:-49']
activ_dict = {}
for key in img_set.keys():
i = 1
if key in name:
name_list.append(key)
stimuli = img_set[key].astype('uint8')
plt.subplot(1,2,i)
plt.imshow(stimuli)
i += 1
dnn_input = stimuli[np.newaxis,:,:,:].transpose(0,3,1,2)
activ = dnn.compute_activation(dnn_input,mask).get('conv3')[0,0,6,6]
activ_dict[key]=activ
print(activ_dict)
'''
'''
pth = r'/nfs/s2/userhome/zhouming/workingdir/optimal_invariance/DataStore'
pdir = os.listdir(pth)
for file in pdir:
if 'Transfer' in file:
filename = file
#layer = filename[filename.rfind('-')+1:filename.rfind('_')]
# chn = int(filename[filename.rfind('_')+1:filename.rfind('.')])
#experiment.set_unit(layer,chn,unit)
with open(pjoin(pth,file),'rb') as f:
img_set = pickle.load(f)
#experiment.gen_rot(img_set,30)
print(img_set.keys())
for file in pdir:
if 'RotateStimuli' in file:
filename = file
layer = filename[filename.rfind('-')+1:filename.rfind('_')]
chn = int(filename[filename.rfind('_')+1:filename.rfind('.')])
experiment.set_unit(layer,chn,unit)
with open(pjoin(pth,file),'rb') as f:
stimuli_set = pickle.load(f)
# print(f'=========={filename}===========',stimuli_set.keys())
experiment.extr_act(stimuli_set,topnum,subnum)
'''
print('==============!!OK!!====================') |
993,603 | 1308f0aa5ec8937a50ee23f070afa36f00cfa909 | """------------------for Dehumidifier"""
import enum
import logging
from typing import Optional
from .const import (
FEAT_HUMIDITY,
FEAT_TARGET_HUMIDITY,
FEAT_WATER_TANK_FULL,
)
from .core_exceptions import InvalidRequestError
from .device import Device, DeviceStatus
CTRL_BASIC = ["Control", "basicCtrl"]
STATE_POWER_V1 = "InOutInstantPower"
SUPPORT_OPERATION_MODE = ["SupportOpMode", "support.airState.opMode"]
SUPPORT_WIND_STRENGTH = ["SupportWindStrength", "support.airState.windStrength"]
SUPPORT_AIR_POLUTION = ["SupportAirPolution", "support.airPolution"]
STATE_OPERATION = ["Operation", "airState.operation"]
STATE_OPERATION_MODE = ["OpMode", "airState.opMode"]
STATE_TARGET_HUM = ["HumidityCfg", "airState.humidity.desired"]
STATE_WIND_STRENGTH = ["WindStrength", "airState.windStrength"]
STATE_CURRENT_HUM = ["SensorHumidity", "airState.humidity.current"]
STATE_PM1 = ["SensorPM1", "airState.quality.PM1"]
STATE_PM10 = ["SensorPM10", "airState.quality.PM10"]
STATE_PM25 = ["SensorPM2", "airState.quality.PM2"]
STATE_TANK_LIGHT = ["WatertankLight", "airState.miscFuncState.watertankLight"]
STATE_POWER = [STATE_POWER_V1, "airState.energy.onCurrent"]
CMD_STATE_OPERATION = [CTRL_BASIC, "Set", STATE_OPERATION]
CMD_STATE_OP_MODE = [CTRL_BASIC, "Set", STATE_OPERATION_MODE]
CMD_STATE_TARGET_HUM = [CTRL_BASIC, "Set", STATE_TARGET_HUM]
CMD_STATE_WIND_STRENGTH = [CTRL_BASIC, "Set", STATE_WIND_STRENGTH]
CMD_ENABLE_EVENT_V2 = ["allEventEnable", "Set", "airState.mon.timeout"]
DEFAULT_MIN_HUM = 30
DEFAULT_MAX_HUM = 70
DEFAULT_STEP_HUM = 5
ADD_FEAT_POLL_INTERVAL = 300 # 5 minutes
_LOGGER = logging.getLogger(__name__)
class DHumOp(enum.Enum):
"""Whether a device is on or off."""
OFF = "@operation_off"
ON = "@operation_on"
class DHumMode(enum.Enum):
"""The operation mode for a Dehumidifier device."""
SMART = "@AP_MAIN_MID_OPMODE_SMART_DEHUM_W"
FAST = "@AP_MAIN_MID_OPMODE_FAST_DEHUM_W"
CILENT = "@AP_MAIN_MID_OPMODE_CILENT_DEHUM_W"
CONC_DRY = "@AP_MAIN_MID_OPMODE_CONCENTRATION_DRY_W"
CLOTH_DRY = "@AP_MAIN_MID_OPMODE_CLOTHING_DRY_W"
IONIZER = "@AP_MAIN_MID_OPMODE_IONIZER_W"
class DHumFanSpeed(enum.Enum):
"""The fan speed for a Dehumidifier device."""
LOW = "@AP_MAIN_MID_WINDSTRENGTH_DHUM_LOW_W"
MID = "@AP_MAIN_MID_WINDSTRENGTH_DHUM_MID_W"
HIGH = "@AP_MAIN_MID_WINDSTRENGTH_DHUM_HIGH_W"
class DeHumidifierDevice(Device):
"""A higher-level interface for DeHumidifier."""
def __init__(self, client, device):
super().__init__(client, device, DeHumidifierStatus(self, None))
self._supported_op_modes = None
self._supported_fan_speeds = None
self._humidity_range = None
self._humidity_step = DEFAULT_STEP_HUM
self._current_power = 0
self._current_power_supported = True
def _get_humidity_range(self):
"""Get valid humidity range for model."""
if not self._humidity_range:
if not self.model_info:
return None
key = self._get_state_key(STATE_TARGET_HUM)
range_info = self.model_info.value(key)
if not range_info:
min_hum = DEFAULT_MIN_HUM
max_hum = DEFAULT_MAX_HUM
else:
min_hum = min(range_info.min, DEFAULT_MIN_HUM)
max_hum = max(range_info.max, DEFAULT_MAX_HUM)
self._humidity_range = [min_hum, max_hum]
return self._humidity_range
@property
def op_modes(self):
"""Return a list of available operation modes."""
if self._supported_op_modes is None:
key = self._get_state_key(SUPPORT_OPERATION_MODE)
if not self.model_info.is_enum_type(key):
self._supported_op_modes = []
return []
mapping = self.model_info.value(key).options
mode_list = [e.value for e in DHumMode]
self._supported_op_modes = [DHumMode(o).name for o in mapping.values() if o in mode_list]
return self._supported_op_modes
@property
def fan_speeds(self):
"""Return a list of available fan speeds."""
if self._supported_fan_speeds is None:
key = self._get_state_key(SUPPORT_WIND_STRENGTH)
if not self.model_info.is_enum_type(key):
self._supported_fan_speeds = []
return []
mapping = self.model_info.value(key).options
mode_list = [e.value for e in DHumFanSpeed]
self._supported_fan_speeds = [DHumFanSpeed(o).name for o in mapping.values() if o in mode_list]
return self._supported_fan_speeds
@property
def target_humidity_step(self):
"""Return target humidity step used."""
return self._humidity_step
@property
def target_humidity_min(self):
"""Return minimum value for target humidity."""
if not (hum_range := self._get_humidity_range()):
return None
return hum_range[0]
@property
def target_humidity_max(self):
"""Return maximum value for target humidity."""
if not (hum_range := self._get_humidity_range()):
return None
return hum_range[1]
async def power(self, turn_on):
"""Turn on or off the device (according to a boolean)."""
op = DHumOp.ON if turn_on else DHumOp.OFF
keys = self._get_cmd_keys(CMD_STATE_OPERATION)
op_value = self.model_info.enum_value(keys[2], op.value)
if self._should_poll:
# different power command for ThinQ1 devices
cmd = "Start" if turn_on else "Stop"
await self.set(keys[0], keys[2], key=None, value=cmd)
self._status.update_status(keys[2], op_value)
return
await self.set(keys[0], keys[1], key=keys[2], value=op_value)
async def set_op_mode(self, mode):
"""Set the device's operating mode to an `OpMode` value."""
if mode not in self.op_modes:
raise ValueError(f"Invalid operating mode: {mode}")
keys = self._get_cmd_keys(CMD_STATE_OP_MODE)
mode_value = self.model_info.enum_value(keys[2], DHumMode[mode].value)
await self.set(keys[0], keys[1], key=keys[2], value=mode_value)
async def set_fan_speed(self, speed):
"""Set the fan speed to a value from the `ACFanSpeed` enum."""
if speed not in self.fan_speeds:
raise ValueError(f"Invalid fan speed: {speed}")
keys = self._get_cmd_keys(CMD_STATE_WIND_STRENGTH)
speed_value = self.model_info.enum_value(keys[2], DHumFanSpeed[speed].value)
await self.set(keys[0], keys[1], key=keys[2], value=speed_value)
async def set_target_humidity(self, humidity):
"""Set the device's target humidity."""
range_info = self._get_humidity_range()
if range_info and not (range_info[0] <= humidity <= range_info[1]):
raise ValueError(f"Target humidity out of range: {humidity}")
keys = self._get_cmd_keys(CMD_STATE_TARGET_HUM)
await self.set(keys[0], keys[1], key=keys[2], value=humidity)
async def get_power(self):
"""Get the instant power usage in watts of the whole unit"""
if not self._current_power_supported:
return 0
try:
value = await self._get_config(STATE_POWER_V1)
return value[STATE_POWER_V1]
except (ValueError, InvalidRequestError):
# Device does not support whole unit instant power usage
self._current_power_supported = False
return 0
async def set(self, ctrl_key, command, *, key=None, value=None, data=None, ctrl_path=None):
"""Set a device's control for `key` to `value`."""
await super().set(
ctrl_key, command, key=key, value=value, data=data, ctrl_path=ctrl_path
)
if key is not None and self._status:
self._status.update_status(key, value)
def reset_status(self):
self._status = DeHumidifierStatus(self, None)
return self._status
# async def _get_device_info(self):
# """Call additional method to get device information for API v1.
#
# Called by 'device_poll' method using a lower poll rate
# """
# # this command is to get power usage on V1 device
# self._current_power = await self.get_power()
# async def _pre_update_v2(self):
# """Call additional methods before data update for v2 API."""
# # this command is to get power and temp info on V2 device
# keys = self._get_cmd_keys(CMD_ENABLE_EVENT_V2)
# await self.set(keys[0], keys[1], key=keys[2], value="70", ctrl_path="control")
async def poll(self) -> Optional["DeHumidifierStatus"]:
"""Poll the device's current state."""
res = await self.device_poll()
# res = await self.device_poll(
# thinq1_additional_poll=ADD_FEAT_POLL_INTERVAL,
# thinq2_query_device=True,
# )
if not res:
return None
# if self._should_poll:
# res[AC_STATE_POWER_V1] = self._current_power
self._status = DeHumidifierStatus(self, res)
return self._status
class DeHumidifierStatus(DeviceStatus):
"""Higher-level information about a DeHumidifier's current status."""
def __init__(self, device, data):
super().__init__(device, data)
self._operation = None
def _get_operation(self):
if self._operation is None:
key = self._get_state_key(STATE_OPERATION)
operation = self.lookup_enum(key, True)
if not operation:
return None
self._operation = operation
try:
return DHumOp(self._operation)
except ValueError:
return None
def update_status(self, key, value):
if not super().update_status(key, value):
return False
if key in STATE_OPERATION:
self._operation = None
return True
@property
def is_on(self):
op = self._get_operation()
if not op:
return False
return op != DHumOp.OFF
@property
def operation(self):
op = self._get_operation()
if not op:
return None
return op.name
@property
def operation_mode(self):
key = self._get_state_key(STATE_OPERATION_MODE)
if (value := self.lookup_enum(key, True)) is None:
return None
try:
return DHumMode(value).name
except ValueError:
return None
@property
def fan_speed(self):
key = self._get_state_key(STATE_WIND_STRENGTH)
if (value := self.lookup_enum(key, True)) is None:
return None
try:
return DHumFanSpeed(value).name
except ValueError:
return None
@property
def current_humidity(self):
support_key = self._get_state_key(SUPPORT_AIR_POLUTION)
if self._device.model_info.enum_value(support_key, "@SENSOR_HUMID_SUPPORT") is None:
return None
key = self._get_state_key(STATE_CURRENT_HUM)
if (value := self.to_int_or_none(self.lookup_range(key))) is None:
return None
return self._update_feature(FEAT_HUMIDITY, value, False)
@property
def target_humidity(self):
key = self._get_state_key(STATE_TARGET_HUM)
if (value := self.to_int_or_none(self.lookup_range(key))) is None:
return None
return self._update_feature(FEAT_TARGET_HUMIDITY, value, False)
@property
def water_tank_full(self):
key = self._get_state_key(STATE_TANK_LIGHT)
if (value := self.lookup_enum(key)) is None:
return None
return self._update_feature(FEAT_WATER_TANK_FULL, value)
def _update_features(self):
_ = [
self.current_humidity,
self.target_humidity,
self.water_tank_full,
]
|
993,604 | 7b9a85ca9fd1fb354cd76dff8bf59aaad3feee2b | import dramatiq
import importlib
from django.conf import settings
DEFAULT_BROKER = "dramatiq.brokers.rabbitmq.RabbitmqBroker"
DEFAULT_SETTINGS = {
"BROKER": DEFAULT_BROKER,
"OPTIONS": {
"host": "127.0.0.1",
"port": 5672,
"heartbeat_interval": 0,
"connection_attempts": 5,
},
"MIDDLEWARE": []
}
def load_class(path):
module_path, _, class_name = path.rpartition(".")
module = importlib.import_module(module_path)
return getattr(module, class_name)
def load_middleware(path_or_obj):
return load_class(path_or_obj)()
broker_settings = getattr(settings, "DRAMATIQ_BROKER", DEFAULT_SETTINGS)
broker_path = broker_settings["BROKER"]
broker_class = load_class(broker_path)
broker_options = broker_settings.get("OPTIONS", {})
middleware = [load_middleware(path) for path in broker_settings.get("MIDDLEWARE", [])]
broker = broker_class(middleware=middleware, **broker_options)
dramatiq.set_broker(broker)
@dramatiq.actor
def delete_old_tasks(max_task_age=86400):
"""This task deletes all tasks older than `max_task_age` from the
database.
"""
from .models import Task
Task.tasks.delete_old_tasks(max_task_age)
|
993,605 | 449c099422f22df2988d9957dd34bcb0972a899b | """
Classes for writing and filtering of processed reads.
A Filter is a callable that has the read as its only argument. If it is called,
it returns True if the read should be filtered (discarded), and False if not.
To be used, a filter needs to be wrapped in one of the redirector classes.
They are called so because they can redirect filtered reads to a file if so
desired. They also keep statistics.
To determine what happens to a read, a list of redirectors with different
filters is created and each redirector is called in turn until one returns True.
The read is then assumed to have been "consumed", that is, either written
somewhere or filtered (should be discarded).
"""
from collections import defaultdict, Counter
from abc import ABC, abstractmethod
from typing import Tuple, Optional, Dict, Any, DefaultDict
from .qualtrim import expected_errors
from .utils import FileOpener
from .modifiers import ModificationInfo
# Constants used when returning from a Filter’s __call__ method to improve
# readability (it is unintuitive that "return True" means "discard the read").
DISCARD = True
KEEP = False
class SingleEndFilter(ABC):
@abstractmethod
def __call__(self, read, info: ModificationInfo):
"""
Called to process a single-end read
"""
class PairedEndFilter(ABC):
@abstractmethod
def __call__(self, read1, read2, info1: ModificationInfo, info2: ModificationInfo):
"""
Called to process the read pair (read1, read2)
"""
class WithStatistics(ABC):
def __init__(self) -> None:
# A defaultdict is much faster than a Counter
self._written_lengths1 = defaultdict(int) # type: DefaultDict[int, int]
self._written_lengths2 = defaultdict(int) # type: DefaultDict[int, int]
def written_reads(self) -> int:
"""Return number of written reads or read pairs"""
return sum(self._written_lengths1.values())
def written_bp(self) -> Tuple[int, int]:
return (
self._compute_total_bp(self._written_lengths1),
self._compute_total_bp(self._written_lengths2),
)
def written_lengths(self) -> Tuple[Counter, Counter]:
return (Counter(self._written_lengths1), Counter(self._written_lengths2))
@staticmethod
def _compute_total_bp(counts: DefaultDict[int, int]) -> int:
return sum(length * count for length, count in counts.items())
class SingleEndFilterWithStatistics(SingleEndFilter, WithStatistics, ABC):
def __init__(self):
super().__init__()
def update_statistics(self, read) -> None:
self._written_lengths1[len(read)] += 1
class PairedEndFilterWithStatistics(PairedEndFilter, WithStatistics, ABC):
def __init__(self):
super().__init__()
def update_statistics(self, read1, read2):
self._written_lengths1[len(read1)] += 1
self._written_lengths2[len(read2)] += 1
class NoFilter(SingleEndFilterWithStatistics):
"""
No filtering, just send each read to the given writer.
"""
def __init__(self, writer):
super().__init__()
self.writer = writer
def __call__(self, read, info: ModificationInfo):
self.writer.write(read)
self.update_statistics(read)
return DISCARD
class PairedNoFilter(PairedEndFilterWithStatistics):
"""
No filtering, just send each paired-end read to the given writer.
"""
def __init__(self, writer):
super().__init__()
self.writer = writer
def __call__(self, read1, read2, info1: ModificationInfo, info2: ModificationInfo):
self.writer.write(read1, read2)
self.update_statistics(read1, read2)
return DISCARD
class Redirector(SingleEndFilterWithStatistics):
"""
Redirect discarded reads to the given writer. This is for single-end reads.
"""
def __init__(self, writer, filter: SingleEndFilter, filter2=None):
super().__init__()
# TODO filter2 should really not be here
self.filtered = 0
self.writer = writer
self.filter = filter
def __call__(self, read, info: ModificationInfo):
if self.filter(read, info):
self.filtered += 1
if self.writer is not None:
self.writer.write(read)
self.update_statistics(read)
return DISCARD
return KEEP
class PairedRedirector(PairedEndFilterWithStatistics):
"""
Redirect paired-end reads matching a filtering criterion to a writer.
Different filtering styles are supported, differing by which of the
two reads in a pair have to fulfill the filtering criterion.
"""
def __init__(self, writer, filter, filter2, pair_filter_mode='any'):
"""
pair_filter_mode -- these values are allowed:
'any': The pair is discarded if any read matches.
'both': The pair is discarded if both reads match.
'first': The pair is discarded if the first read matches.
"""
super().__init__()
if pair_filter_mode not in ('any', 'both', 'first'):
raise ValueError("pair_filter_mode must be 'any', 'both' or 'first'")
self.filtered = 0
self.writer = writer
self.filter = filter
self.filter2 = filter2
if filter2 is None:
self._is_filtered = self._is_filtered_first
elif filter is None:
self._is_filtered = self._is_filtered_second
elif pair_filter_mode == 'any':
self._is_filtered = self._is_filtered_any
elif pair_filter_mode == 'both':
self._is_filtered = self._is_filtered_both
else:
self._is_filtered = self._is_filtered_first
def _is_filtered_any(self, read1, read2, info1: ModificationInfo, info2: ModificationInfo):
return self.filter(read1, info1) or self.filter2(read2, info2)
def _is_filtered_both(self, read1, read2, info1: ModificationInfo, info2: ModificationInfo):
return self.filter(read1, info1) and self.filter2(read2, info2)
def _is_filtered_first(self, read1, read2, info1: ModificationInfo, info2: ModificationInfo):
return self.filter(read1, info1)
def _is_filtered_second(self, read1, read2, info1: ModificationInfo, info2: ModificationInfo):
return self.filter2(read2, info2)
def __call__(self, read1, read2, info1: ModificationInfo, info2: ModificationInfo):
if self._is_filtered(read1, read2, info1, info2):
self.filtered += 1
if self.writer is not None:
self.writer.write(read1, read2)
self.update_statistics(read1, read2)
return DISCARD
return KEEP
class TooShortReadFilter(SingleEndFilter):
def __init__(self, minimum_length):
self.minimum_length = minimum_length
def __call__(self, read, info: ModificationInfo):
return len(read) < self.minimum_length
class TooLongReadFilter(SingleEndFilter):
def __init__(self, maximum_length):
self.maximum_length = maximum_length
def __call__(self, read, info: ModificationInfo):
return len(read) > self.maximum_length
class MaximumExpectedErrorsFilter(SingleEndFilter):
"""
Discard reads whose expected number of errors, according to the quality
values, exceeds a threshold.
The idea comes from usearch's -fastq_maxee parameter
(http://drive5.com/usearch/).
"""
def __init__(self, max_errors):
self.max_errors = max_errors
def __call__(self, read, info: ModificationInfo):
"""Return True when the read should be discarded"""
return expected_errors(read.qualities) > self.max_errors
class NContentFilter(SingleEndFilter):
"""
Discard a read if it has too many 'N' bases. It handles both raw counts
of Ns as well as proportions. Note, for raw counts, it is a 'greater than' comparison,
so a cutoff of '1' will keep reads with a single N in it.
"""
def __init__(self, count):
"""
Count -- if it is below 1.0, it will be considered a proportion, and above and equal to
1 will be considered as discarding reads with a number of N's greater than this cutoff.
"""
assert count >= 0
self.is_proportion = count < 1.0
self.cutoff = count
def __call__(self, read, info: ModificationInfo):
"""Return True when the read should be discarded"""
n_count = read.sequence.lower().count('n')
if self.is_proportion:
if len(read) == 0:
return False
return n_count / len(read) > self.cutoff
else:
return n_count > self.cutoff
class DiscardUntrimmedFilter(SingleEndFilter):
"""
Return True if read is untrimmed.
"""
def __call__(self, read, info: ModificationInfo):
return not info.matches
class DiscardTrimmedFilter(SingleEndFilter):
"""
Return True if read is trimmed.
"""
def __call__(self, read, info: ModificationInfo):
return bool(info.matches)
class CasavaFilter(SingleEndFilter):
"""
Remove reads that fail the CASAVA filter. These have header lines that
look like ``xxxx x:Y:x:x`` (with a ``Y``). Reads that pass the filter
have an ``N`` instead of ``Y``.
Reads with unrecognized headers are kept.
"""
def __call__(self, read, info: ModificationInfo):
_, _, right = read.name.partition(' ')
return right[1:4] == ':Y:' # discard if :Y: found
class Demultiplexer(SingleEndFilterWithStatistics):
"""
Demultiplex trimmed reads. Reads are written to different output files
depending on which adapter matches. Files are created when the first read
is written to them.
"""
def __init__(self, path_template, untrimmed_path, qualities, file_opener):
"""
path_template must contain the string '{name}', which will be replaced
with the name of the adapter to form the final output path.
Reads without an adapter match are written to the file named by
untrimmed_path.
"""
super().__init__()
assert '{name}' in path_template
self.template = path_template
self.untrimmed_path = untrimmed_path
self.untrimmed_writer = None
self.writers = dict()
self.qualities = qualities
self.file_opener = file_opener
def __call__(self, read, info):
"""
Write the read to the proper output file according to the most recent match
"""
if info.matches:
name = info.matches[-1].adapter.name
if name not in self.writers:
self.writers[name] = self.file_opener.dnaio_open_raise_limit(
self.template.replace('{name}', name), self.qualities)
self.update_statistics(read)
self.writers[name].write(read)
else:
if self.untrimmed_writer is None and self.untrimmed_path is not None:
self.untrimmed_writer = self.file_opener.dnaio_open_raise_limit(
self.untrimmed_path, self.qualities)
if self.untrimmed_writer is not None:
self.update_statistics(read)
self.untrimmed_writer.write(read)
return DISCARD
def close(self):
for w in self.writers.values():
w.close()
if self.untrimmed_writer is not None:
self.untrimmed_writer.close()
class PairedDemultiplexer(PairedEndFilterWithStatistics):
"""
Demultiplex trimmed paired-end reads. Reads are written to different output files
depending on which adapter (in read 1) matches.
"""
def __init__(self, path_template, path_paired_template, untrimmed_path, untrimmed_paired_path,
qualities, file_opener):
"""
The path templates must contain the string '{name}', which will be replaced
with the name of the adapter to form the final output path.
Read pairs without an adapter match are written to the files named by
untrimmed_path.
"""
super().__init__()
self._demultiplexer1 = Demultiplexer(path_template, untrimmed_path, qualities, file_opener)
self._demultiplexer2 = Demultiplexer(path_paired_template, untrimmed_paired_path,
qualities, file_opener)
def written(self) -> int:
return self._demultiplexer1.written_reads()
def written_bp(self) -> Tuple[int, int]:
return (self._demultiplexer1.written_bp()[0], self._demultiplexer2.written_bp()[0])
def __call__(self, read1, read2, info1: ModificationInfo, info2: ModificationInfo):
assert read2 is not None
self._demultiplexer1(read1, info1)
self._demultiplexer2(read2, info1)
def close(self):
self._demultiplexer1.close()
self._demultiplexer2.close()
class CombinatorialDemultiplexer(PairedEndFilterWithStatistics):
"""
Demultiplex reads depending on which adapter matches, taking into account both matches
on R1 and R2.
"""
def __init__(
self,
path_template: str,
path_paired_template: str,
untrimmed_name: Optional[str],
qualities: bool,
file_opener: FileOpener,
):
"""
path_template must contain the string '{name1}' and '{name2}', which will be replaced
with the name of the adapters found on R1 and R2, respectively to form the final output
path. For reads without an adapter match, the name1 and/or name2 are set to the string
specified by untrimmed_name. Alternatively, untrimmed_name can be set to None; in that
case, read pairs for which at least one read does not have an adapter match are
discarded.
untrimmed_name -- what to replace the templates with when one or both of the reads
do not contain an adapter (use "unknown"). Set to None to discard these read pairs.
"""
super().__init__()
assert '{name1}' in path_template and '{name2}' in path_template
assert '{name1}' in path_paired_template and '{name2}' in path_paired_template
self.template = path_template
self.paired_template = path_paired_template
self.untrimmed_name = untrimmed_name
self.writers = dict() # type: Dict[Tuple[str, str], Any]
self.qualities = qualities
self.file_opener = file_opener
@staticmethod
def _make_path(template, name1, name2):
return template.replace('{name1}', name1).replace('{name2}', name2)
def __call__(self, read1, read2, info1, info2):
"""
Write the read to the proper output file according to the most recent matches both on
R1 and R2
"""
assert read2 is not None
name1 = info1.matches[-1].adapter.name if info1.matches else None
name2 = info2.matches[-1].adapter.name if info2.matches else None
key = (name1, name2)
if key not in self.writers:
# Open writer on first use
if name1 is None:
name1 = self.untrimmed_name
if name2 is None:
name2 = self.untrimmed_name
if name1 is None or name2 is None:
return DISCARD
path1 = self._make_path(self.template, name1, name2)
path2 = self._make_path(self.paired_template, name1, name2)
self.writers[key] = (
self.file_opener.dnaio_open_raise_limit(path1, qualities=self.qualities),
self.file_opener.dnaio_open_raise_limit(path2, qualities=self.qualities),
)
writer1, writer2 = self.writers[key]
self.update_statistics(read1, read2)
writer1.write(read1)
writer2.write(read2)
return DISCARD
def close(self):
for w1, w2 in self.writers.values():
w1.close()
w2.close()
class RestFileWriter(SingleEndFilter):
def __init__(self, file):
self.file = file
def __call__(self, read, info):
# TODO this fails with linked adapters
if info.matches:
rest = info.matches[-1].rest()
if len(rest) > 0:
print(rest, read.name, file=self.file)
return KEEP
class WildcardFileWriter(SingleEndFilter):
def __init__(self, file):
self.file = file
def __call__(self, read, info):
# TODO this fails with linked adapters
if info.matches:
print(info.matches[-1].wildcards(), read.name, file=self.file)
return KEEP
class InfoFileWriter(SingleEndFilter):
def __init__(self, file):
self.file = file
def __call__(self, read, info: ModificationInfo):
current_read = info.original_read
if info.matches:
for match in info.matches:
for info_record in match.get_info_records(current_read):
# info_record[0] is the read name suffix
print(read.name + info_record[0], *info_record[1:], sep='\t', file=self.file)
current_read = match.trimmed(current_read)
else:
seq = read.sequence
qualities = read.qualities if read.qualities is not None else ''
print(read.name, -1, seq, qualities, sep='\t', file=self.file)
return KEEP
|
993,606 | fbfbd36c2d9eb5ff3cbe8d15dff01546ce4ac1f7 | import os
from django.db import models
from django.utils.translation import ugettext_lazy as _
from apps.category.models import Category
from apps.publication.models import Publication
from settings.common import MEDIA_ROOT
class News(Publication):
"""Stores HTML content and an optional featured image, besides categories
The fields defined here are:
content - A text field that can contain HTML content;
image - A path to the image location on the server. It accepts null valies;
categories - A many to many relation with category model.
"""
image = models.ImageField(_('image'), upload_to=os.path.join(MEDIA_ROOT, 'files'), null=True, blank=True)
categories = models.ManyToManyField(Category, verbose_name=_('categories'), null=True, blank=True,
related_name='news')
def __str__(self):
return self.title
class Meta(Publication.Meta):
verbose_name = _('news')
verbose_name_plural = _('tidings') |
993,607 | 524be494e0182bb5fe63a444aed49238a254fe75 | #!/usr/bin/env python3
load_frozen_lake = __import__('0-load_env').load_frozen_lake
q_init = __import__('1-q_init').q_init
env = load_frozen_lake()
Q = q_init(env)
print(Q.shape)
env = load_frozen_lake(is_slippery=True)
Q = q_init(env)
print(Q.shape)
desc = [['S', 'F', 'F'], ['F', 'H', 'H'], ['F', 'F', 'G']]
env = load_frozen_lake(desc=desc)
Q = q_init(env)
print(Q.shape)
env = load_frozen_lake(map_name='4x4')
Q = q_init(env)
print(Q.shape) |
993,608 | 7c21c5b534fd1b5fe62d74e5bc89d6a2e72977c0 | stocks = {
"GOOGLE": 520.54 ,
"FB": 76.45 ,
"YAHOO": 39.28 ,
"AMAZON": 306.21 ,
"APPLE": 99.76
}
# Sorts numerically
print(sorted(zip(stocks.values(), stocks.keys())))
# Sorts alphabetically
print(sorted(zip(stocks.keys(), stocks.values())))
# Grabs minimum number
print(min(zip(stocks.values(), stocks.keys())))
# Grabs maximum number
print(max(zip(stocks.values(), stocks.keys()))) |
993,609 | 4b32eac2d7ff7ce6074184b5239dce0a3a061791 | # 204. Count Primes
# Count the number of prime numbers less than a non-negative number, n.
# Example:
# Input: 10
# Output: 4
# Explanation:
# There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
class Solution:
def countPrimesSimple(self, n: int) -> int:
"""
Time to sift out multiples of p is proportional to n/p,
so overall = O(n/2 + n/3 + n/5 + n/7, ...) -> O(n log log n)
Space: O(n), which is the biggest problem with simple sieve.
"""
if n < 2:
return 0
primes = []
is_prime = [False, False] + [True for i in range(n-1)]
for x in range(2, n):
if is_prime[x]:
primes.append(x)
for i in range(x*2, n, x):
is_prime[i] = False
return len(primes)
def countPrimesOptimized(self, n: int) -> int:
"""
Asymptiotic time and space coplexity are same for basic sieving,
but practical improvement to runtime by sieving p's multiples
from p^2 instead of p, since all numbers of the
form `kp` where k < p have already been sieved out.
Storage is also be reduced by ignoring even numbers.
"""
if n < 2:
return 0
size = (n - 3) // 2 + 1 # -3 for 0,1,2 and // 2 to ignore evens
primes = [2]
is_prime = [True for i in range(size)] # represents if (2i+3) is prime
for i in range(size):
if is_prime[i]:
p = 2 * i + 3
primes.append(p)
# Sieve from p^2, where p^2 = (2i+3)^2 = (4i^2 + 12i + 9)
# Index in is_prime is (2i^2 + 6i + 3)
# because is_prime[i] = 2i + 3.
for j in range(2 * i**2 + 6 * i + 3, size, p):
is_prime[j] = False
return len(primes) - 1 if primes[-1] == n else len(primes)
|
993,610 | af14ff155765f427d6de8670ac2eb0ef7d1b1c51 | chrodata = ((0.005666666666666667, 0.0285, 0.0515, 0.0745, 0.09733333333333333, 0.12033333333333333, 0.14333333333333334, 0.16633333333333333, 0.18916666666666668, 0.21216666666666667, 0.23516666666666666, 0.258, 0.28099999999999997, 0.304, 0.3268333333333333, 0.34983333333333333, 0.37283333333333335, 0.39566666666666667, 0.4186666666666667, 0.44166666666666665, 0.4646666666666667, 0.4875, 0.5105, 0.5335, 0.5563333333333333, 0.5793333333333334, 0.6023333333333333, 0.6253333333333333, 0.6481666666666667, 0.6711666666666667, 0.6941666666666667, 0.717, 0.74, 0.763, 0.786, 0.8088333333333333, 0.8318333333333333, 0.8548333333333333, 0.8776666666666667, 0.9006666666666666, 0.9236666666666666, 0.9466666666666667, 0.9695, 0.9925, 1.0181666666666667, 1.1296666666666666, 1.2623333333333333, 1.3951666666666667, 1.527, 1.66, 1.794, 1.9248333333333334, 2.0585, 2.1908333333333334, 2.324, 2.4568333333333334, 2.584, 2.7165, 2.849666666666667, 2.978833333333333, 3.1106666666666665, 3.2439999999999998, 3.3735, 3.5061666666666667, 3.6365, 3.7678333333333334, 3.8985, 4.030666666666667, 4.164666666666666, 4.296, 4.427666666666667, 4.559833333333334, 4.6935, 4.8228333333333335, 4.9515, 5.083666666666667, 5.2171666666666665, 5.350833333333333, 5.4831666666666665, 5.6145, 5.7443333333333335, 5.878166666666667, 6.0115, 6.145833333333333, 6.278333333333333, 6.4115, 6.545333333333334, 6.679833333333334, 6.812666666666667, 6.946166666666667, 7.0793333333333335, 7.2085, 7.343, 7.472666666666667, 7.602833333333333, 7.734666666666667, 7.869833333333333, 7.997166666666667, 8.1295, 8.259833333333333, 8.392, 8.525833333333333, 8.657833333333333, 8.787, 8.916666666666666, 9.050333333333333, 9.180833333333334, 9.312666666666667, 9.445333333333334, 9.5785, 9.706166666666666, 9.840166666666667, 9.967666666666666, 10.099166666666667, 10.2315, 10.365333333333334, 10.498333333333333, 10.632666666666667, 10.7645, 10.893333333333333, 11.028666666666666, 11.161, 11.294833333333333, 11.431166666666666, 11.565833333333334, 11.700333333333333, 11.831333333333333, 11.9685, 12.102333333333334, 12.237, 12.370333333333333, 12.504666666666667, 12.6385, 12.772, 12.9045, 13.037166666666666, 13.169333333333332, 13.301666666666666, 13.436166666666667, 13.566833333333333, 13.690666666666667, 13.819833333333333, 13.956666666666667, 14.091666666666667, 14.222, 14.348166666666666, 14.481833333333332, 14.608166666666667, 14.744, 14.8775, 15.007833333333334, 15.123666666666667, 15.249833333333333, 15.358833333333333, 15.462333333333333, 15.576333333333332, 15.707333333333333, 15.839333333333334, 15.970666666666666, 16.099333333333334, 16.2225, 16.357333333333333, 16.488833333333332, 16.61, 16.732833333333332, 16.850666666666665, 16.9725, 17.089, 17.215, 17.33716666666667, 17.457166666666666, 17.58716666666667, 17.709, 17.823166666666665, 17.946, 18.06, 18.182666666666666, 18.297833333333333, 18.408166666666666, 18.524166666666666, 18.653166666666667, 18.7735, 18.892, 19.0265, 19.143, 19.2595, 19.366833333333332, 19.4825, 19.603, 19.716833333333334, 19.829333333333334, 19.941666666666666, 20.048333333333332, 20.156, 20.271833333333333, 20.386666666666667, 20.5015, 20.603, 20.719333333333335, 20.8185, 20.930666666666667, 21.0395, 21.140666666666668, 21.245833333333334, 21.360833333333332, 21.4765, 21.574333333333332, 21.673, 21.790666666666667, 21.911, 22.027666666666665, 22.1505, 22.264166666666668, 22.392333333333333, 22.494666666666667, 22.600666666666665, 22.725166666666667, 22.842166666666667, 22.950833333333332, 23.062666666666665, 23.177, 23.272833333333335, 23.384333333333334, 23.499, 23.608166666666666, 23.713, 23.825333333333333, 23.937333333333335, 24.052, 24.1585, 24.266, 24.375666666666667, 24.485833333333332, 24.592, 24.691, 24.806666666666665, 24.918833333333332, 25.026666666666667, 25.139499999999998, 25.2565, 25.376166666666666, 25.481833333333334, 25.592333333333332, 25.694166666666668, 25.812666666666665, 25.93016666666667, 26.046166666666668, 26.161, 26.277666666666665, 26.385166666666667, 26.493666666666666, 26.608166666666666, 26.721, 26.828833333333332, 26.9375, 27.036833333333334, 27.1525, 27.275166666666667, 27.386666666666667, 27.502666666666666, 27.612, 27.715166666666665, 27.826833333333333, 27.948333333333334, 28.061833333333333, 28.174166666666668, 28.282833333333333, 28.3915, 28.498666666666665, 28.610333333333333, 28.729, 28.849666666666668, 28.957, 29.0785, 29.187666666666665, 29.297666666666668, 29.415, 29.534, 29.646166666666666, 29.749666666666666, 29.863166666666668, 29.9745, 30.081333333333333, 30.19, 30.296, 30.414833333333334, 30.525, 30.640833333333333, 30.7505, 30.863166666666668, 30.974166666666665, 31.088166666666666, 31.200666666666667, 31.310666666666666, 31.423, 31.533666666666665, 31.647, 31.75433333333333, 31.864833333333333, 31.973, 32.085, 32.19016666666667, 32.301833333333335, 32.41433333333333, 32.527166666666666, 32.63366666666666, 32.738166666666665, 32.851333333333336, 32.96, 33.07666666666667, 33.18966666666667, 33.3, 33.40866666666667, 33.5185, 33.626333333333335, 33.73683333333334, 33.848, 33.9655, 34.079166666666666, 34.19, 34.303, 34.41833333333334, 34.532, 34.64333333333333, 34.75633333333333, 34.8625, 34.97383333333333, 35.08133333333333, 35.1975, 35.31483333333333, 35.43216666666667, 35.53933333333333, 35.65116666666667, 35.763333333333335, 35.875, 35.98383333333334, 36.105333333333334, 36.22116666666667, 36.334666666666664, 36.447, 36.56183333333333, 36.67633333333333, 36.78616666666667, 36.897333333333336, 37.01, 37.123, 37.239333333333335, 37.352333333333334, 37.469833333333334, 37.58983333333333, 37.70066666666666, 37.811166666666665, 37.926833333333335, 38.034333333333336, 38.143, 38.25333333333333, 38.365, 38.47666666666667, 38.591, 38.70183333333333, 38.8135, 38.91916666666667, 39.0265, 39.135333333333335, 39.242, 39.354166666666664, 39.466166666666666, 39.57866666666666, 39.6905, 39.801, 39.910833333333336, 40.01983333333333, 40.13283333333333, 40.24633333333333, 40.3605, 40.4795, 40.594, 40.716, 40.8355, 40.943333333333335, 41.0555, 41.16616666666667, 41.281166666666664, 41.395, 41.505833333333335, 41.618833333333335, 41.72983333333333, 41.844833333333334, 41.957166666666666, 42.07066666666667, 42.184333333333335, 42.300666666666665, 42.403999999999996, 42.517, 42.632666666666665, 42.75566666666667, 42.86516666666667, 42.97983333333333, 43.0955, 43.208, 43.32633333333333, 43.43983333333333, 43.55116666666667, 43.672333333333334, 43.78216666666667, 43.897, 44.00666666666667, 44.1195, 44.226166666666664, 44.336666666666666, 44.4495, 44.571333333333335, 44.6855, 44.8015, 44.921166666666664, 45.03483333333333, 45.148833333333336, 45.25933333333333, 45.37383333333333, 45.4905, 45.5995, 45.71, 45.82816666666667, 45.93633333333333, 46.0575, 46.169333333333334, 46.29083333333333, 46.409, 46.51866666666667, 46.63516666666666, 46.748, 46.85766666666667, 46.97233333333333, 47.090333333333334, 47.205666666666666, 47.31916666666667, 47.43183333333333, 47.541333333333334, 47.653, 47.76616666666666, 47.8705, 47.98716666666667, 48.10066666666667, 48.21383333333333, 48.33, 48.44383333333333, 48.55116666666667, 48.6645, 48.779833333333336, 48.89233333333333, 49.002833333333335, 49.11366666666667, 49.227666666666664, 49.339333333333336, 49.43983333333333, 49.558, 49.67616666666667, 49.78766666666667, 49.9005, 50.023833333333336, 50.142, 50.25216666666667, 50.36516666666667, 50.476333333333336, 50.59316666666667, 50.703, 50.81633333333333, 50.929833333333335, 51.04533333333333, 51.156666666666666, 51.275333333333336, 51.38816666666666, 51.501666666666665, 51.61383333333333, 51.72683333333333, 51.842166666666664, 51.961, 52.0745, 52.18416666666667, 52.303333333333335, 52.42366666666667, 52.534, 52.654666666666664, 52.7745, 52.89183333333333, 53.0045, 53.1175, 53.233333333333334, 53.34916666666667, 53.463166666666666, 53.5845, 53.7015, 53.815, 53.92733333333333, 54.03916666666667, 54.156, 54.26883333333333, 54.376, 54.48683333333333, 54.61183333333333, 54.723, 54.84866666666667, 54.96783333333333, 55.08166666666666, 55.19733333333333, 55.31666666666667, 55.431, 55.54233333333333, 55.66316666666667, 55.7785, 55.89183333333333, 56.009166666666665, 56.13183333333333, 56.24666666666667, 56.36666666666667, 56.4795, 56.58566666666667, 56.69716666666667, 56.82, 56.933166666666665, 57.0475, 57.156666666666666, 57.26733333333333, 57.37583333333333, 57.49016666666667, 57.60883333333334, 57.73716666666667, 57.8575, 57.971833333333336, 58.0805, 58.1865, 58.300333333333334, 58.413333333333334, 58.526666666666664, 58.65716666666667, 58.781, 58.89366666666667, 59.00783333333333, 59.13516666666666, 59.2535, 59.37316666666667, 59.4745, 59.6005, 59.711166666666664, 59.826, 59.94, 60.05266666666667, 60.159333333333336, 60.260333333333335, 60.37533333333333, 60.501333333333335, 60.62233333333333, 60.74283333333333, 60.857166666666664, 60.969, 61.099, 61.217166666666664, 61.324333333333335, 61.444, 61.55433333333333, 61.681666666666665, 61.79816666666667, 61.90833333333333, 62.023833333333336, 62.13733333333333, 62.2505, 62.363166666666665, 62.47083333333333, 62.58266666666667, 62.70483333333333, 62.813833333333335, 62.930166666666665, 63.032666666666664, 63.142833333333336, 63.262166666666666, 63.37683333333333, 63.493833333333335, 63.60766666666667, 63.727666666666664, 63.8435, 63.95283333333333, 64.0645, 64.17983333333333, 64.29833333333333, 64.42316666666666, 64.53616666666667, 64.65266666666666, 64.77316666666667, 64.887, 64.99966666666667, 65.11583333333333, 65.23083333333334, 65.36116666666666, 65.47466666666666, 65.595, 65.70416666666667, 65.82833333333333, 65.95016666666666, 66.0745, 66.19566666666667, 66.31233333333333, 66.42966666666666, 66.56033333333333, 66.68566666666666, 66.81783333333334, 66.93766666666667, 67.05633333333333, 67.17466666666667, 67.3115, 67.43299999999999, 67.55783333333333, 67.679, 67.80066666666667, 67.92016666666666, 68.04033333333334, 68.147, 68.25833333333334, 68.36283333333333, 68.47583333333333, 68.612, 68.737, 68.86366666666666, 68.99383333333333, 69.12049999999999, 69.25283333333333, 69.37866666666666, 69.5035, 69.615, 69.73833333333333, 69.856, 69.984, 70.1095, 70.24416666666667, 70.3695, 70.49233333333333, 70.61933333333333, 70.74783333333333, 70.86466666666666, 70.98916666666666, 71.10733333333333, 71.23516666666667, 71.36316666666667, 71.49033333333334, 71.61866666666667, 71.74966666666667, 71.88366666666667, 72.01183333333333, 72.147, 72.275, 72.39333333333333, 72.50916666666667, 72.63616666666667, 72.7685, 72.89833333333333, 73.02633333333333, 73.14166666666667, 73.258, 73.3855, 73.51716666666667, 73.64183333333334, 73.76633333333334, 73.90116666666667, 74.031, 74.15116666666667, 74.2705, 74.3905, 74.51766666666667, 74.65266666666666, 74.7815, 74.905, 75.03116666666666, 75.16383333333333, 75.29933333333334, 75.43066666666667, 75.5655, 75.685, 75.81099999999999, 75.922, 76.0565, 76.177, 76.30183333333333, 76.427, 76.5495, 76.67183333333334, 76.79933333333334, 76.9355, 77.07066666666667, 77.19133333333333, 77.31483333333334, 77.45033333333333, 77.57666666666667, 77.69183333333334, 77.8255, 77.9575, 78.07566666666666, 78.2025, 78.32966666666667, 78.45516666666667, 78.57433333333333, 78.69416666666666, 78.82, 78.95516666666667, 79.07816666666666, 79.19916666666667, 79.33133333333333, 79.46183333333333, 79.59683333333334, 79.727, 79.861, 79.98033333333333, 80.10333333333334, 80.22333333333333, 80.33033333333333, 80.45483333333333, 80.5865, 80.70566666666667, 80.83916666666667, 80.95933333333333, 81.09083333333334, 81.216, 81.33766666666666, 81.46783333333333, 81.59083333333334, 81.72016666666667, 81.84566666666667, 81.97833333333334, 82.1055, 82.23733333333334, 82.36483333333334, 82.50116666666666, 82.63633333333334, 82.76766666666667, 82.88116666666667, 82.994, 83.11716666666666, 83.24783333333333, 83.384, 83.5185, 83.65066666666667, 83.78433333333334, 83.91883333333334, 84.05083333333333, 84.18416666666667, 84.31099999999999, 84.43883333333333, 84.57116666666667, 84.707, 84.83816666666667, 84.96683333333333, 85.097, 85.23066666666666, 85.3645, 85.49816666666666, 85.63266666666667, 85.76716666666667, 85.90183333333333, 86.0225, 86.15716666666667, 86.2925, 86.42666666666666, 86.55983333333333, 86.69416666666666, 86.8275, 86.96333333333334, 87.09233333333333, 87.227, 87.36116666666666, 87.48216666666667, 87.61383333333333, 87.74666666666667, 87.87933333333334, 88.01383333333334, 88.13833333333334, 88.26966666666667, 88.402, 88.53533333333333, 88.66783333333333, 88.7985, 88.93366666666667, 89.0595, 89.1845, 89.29916666666666, 89.423, 89.5555, 89.68266666666666, 89.81666666666666, 89.9505, 90.08233333333334, 90.21533333333333, 90.35166666666666, 90.4845, 90.61783333333334, 90.75416666666666, 90.88833333333334, 91.01733333333333, 91.14433333333334, 91.2705, 91.38783333333333, 91.51983333333334, 91.65466666666667, 91.79066666666667, 91.924, 92.057, 92.192, 92.31833333333333, 92.45166666666667, 92.5815, 92.7165, 92.85166666666666, 92.98566666666666, 93.11866666666667, 93.25233333333334, 93.38566666666667, 93.51816666666667, 93.65166666666667, 93.78733333333334, 93.91716666666666, 94.0525, 94.1885, 94.3215, 94.45416666666667, 94.58716666666666, 94.722, 94.85583333333334, 94.98866666666666, 95.11066666666666, 95.24566666666666, 95.37716666666667, 95.5095, 95.64333333333333, 95.7765, 95.9105, 96.04466666666667, 96.17466666666667, 96.30633333333333, 96.4375, 96.573, 96.70716666666667, 96.84116666666667, 96.97466666666666, 97.1065, 97.23916666666666, 97.36533333333334, 97.49983333333333, 97.63333333333334, 97.77033333333333, 97.90166666666667, 98.03583333333333, 98.16033333333333, 98.294, 98.42766666666667, 98.5615, 98.6965, 98.8305, 98.961, 99.08833333333334, 99.21983333333333, 99.34083333333334, 99.47383333333333, 99.60733333333333, 99.74249999999999, 99.87733333333334), (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 9851.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 10759541.0, 6131661.0, 6210690.0, 6471438.0, 6250737.0, 7243351.0, 6750812.0, 6107298.0, 6183526.0, 6150587.0, 7081270.0, 6355372.0, 6137615.0, 6555940.0, 5649010.0, 6962475.0, 6589125.0, 6667645.0, 5898735.0, 6292265.0, 6688386.0, 6393165.0, 6335340.0, 5976373.0, 6995311.0, 6956309.0, 6303833.0, 5866557.0, 6328091.0, 6145499.0, 7257699.0, 6099889.0, 6630667.0, 5636699.0, 5769879.0, 6365233.0, 5848549.0, 5608924.0, 7085950.0, 6084369.0, 5967168.0, 5335270.0, 5522258.0, 6384058.0, 5443386.0, 5256448.0, 5592426.0, 6049485.0, 9969415.0, 7499857.0, 6214571.0, 6925110.0, 7055348.0, 5668383.0, 5732213.0, 6182231.0, 6006737.0, 6415189.0, 6421390.0, 6821178.0, 5715304.0, 5948377.0, 5372145.0, 6359957.0, 7186846.0, 6089558.0, 7926869.0, 9974538.0, 12217437.0, 11013490.0, 12284494.0, 18545914.0, 17182068.0, 18694162.0, 17529384.0, 17033512.0, 16704174.0, 19529622.0, 19308496.0, 21537032.0, 18831182.0, 19377191.0, 18705383.0, 17194120.0, 9329487.0, 22293001.0, 18518313.0, 12662852.0, 9431805.0, 10032684.0, 13734425.0, 15241269.0, 12782995.0, 18081637.0, 20629506.0, 12025096.0, 16660430.0, 21745635.0, 17808223.0, 21829617.0, 21539774.0, 22766523.0, 20732613.0, 18704380.0, 20590825.0, 21057981.0, 23867136.0, 27914252.0, 62989574.0, 144144149.0, 62494396.0, 33021978.0, 20720899.0, 20940229.0, 23130663.0, 23595689.0, 22095949.0, 28815658.0, 24276271.0, 35649313.0, 36111610.0, 29538317.0, 36324824.0, 33128294.0, 28217562.0, 33669778.0, 39808258.0, 37216902.0, 39514439.0, 47084043.0, 54991552.0, 77225768.0, 61364929.0, 43583860.0, 61857981.0, 62745100.0, 75746643.0, 76009844.0, 63231080.0, 64916910.0, 97894742.0, 121758216.0, 101261260.0, 90538468.0, 74984405.0, 90424632.0, 103988228.0, 111332956.0, 234717619.0, 96983044.0, 136567782.0, 182976006.0, 184251818.0, 239523886.0, 173330488.0, 278512821.0, 323298339.0, 163872518.0, 165802075.0, 174744846.0, 190453396.0, 205194025.0, 208224378.0, 214467957.0, 320202544.0, 232015968.0, 210687676.0, 333673970.0, 308666584.0, 223422825.0, 225058626.0, 230166651.0, 217917709.0, 250270797.0, 276419636.0, 291766137.0, 653123642.0, 596561062.0, 493860681.0, 291608839.0, 299693669.0, 312022767.0, 447930876.0, 520336000.0, 408820974.0, 355851427.0, 279621774.0, 283748683.0, 463691313.0, 614030249.0, 407442392.0, 374870289.0, 393745528.0, 305819570.0, 347987667.0, 367454969.0, 388713181.0, 430972396.0, 409693203.0, 355884074.0, 354240002.0, 429961444.0, 486746760.0, 386710586.0, 409724515.0, 395249367.0, 402074148.0, 573861680.0, 457869971.0, 441899921.0, 544567188.0, 367928383.0, 446286602.0, 547692412.0, 449187413.0, 582009775.0, 529191664.0, 545176835.0, 458159140.0, 448560924.0, 536335245.0, 574258260.0, 565918959.0, 466378568.0, 517018241.0, 548397418.0, 506922727.0, 477508259.0, 480030096.0, 592869606.0, 677760934.0, 531089643.0, 502220325.0, 663520852.0, 748904717.0, 516402953.0, 503979686.0, 564080627.0, 660393974.0, 854987839.0, 767284211.0, 650924557.0, 565154212.0, 598770121.0, 594782053.0, 580284912.0, 663428772.0, 713353100.0, 609088643.0, 632226097.0, 646278178.0, 641520318.0, 589203291.0, 650165316.0, 670977281.0, 693796701.0, 587217403.0, 658469096.0, 722187284.0, 873102164.0, 758240986.0, 705539038.0, 772914810.0, 589507916.0, 618014625.0, 622655354.0, 739182627.0, 853105724.0, 681409321.0, 768310493.0, 764137912.0, 763819240.0, 680834157.0, 627123395.0, 821911499.0, 821351589.0, 712543607.0, 763481190.0, 733127385.0, 758120610.0, 825594942.0, 718908288.0, 842558193.0, 761524689.0, 656791573.0, 796135202.0, 801647089.0, 731909168.0, 691472489.0, 678003247.0, 690500651.0, 768201306.0, 656024487.0, 706153083.0, 721857631.0, 643947909.0, 627580878.0, 889611081.0, 736763956.0, 693491025.0, 653181128.0, 725217816.0, 808379789.0, 686779842.0, 691111618.0, 785765519.0, 687550992.0, 771480699.0, 779573408.0, 750932282.0, 790878629.0, 722215924.0, 937477484.0, 880068440.0, 895349283.0, 804265056.0, 981662887.0, 763012162.0, 844451968.0, 889922669.0, 874427944.0, 765454184.0, 702332680.0, 740968557.0, 723931295.0, 715336761.0, 785604088.0, 704124652.0, 697038755.0, 764910444.0, 721286330.0, 777756052.0, 711063214.0, 740328875.0, 942123351.0, 1120672864.0, 954814604.0, 837691543.0, 741342084.0, 784321153.0, 855323072.0, 892634983.0, 792725368.0, 747836919.0, 658245873.0, 816478628.0, 680180756.0, 970817527.0, 818052641.0, 647762642.0, 637834424.0, 759994408.0, 726591283.0, 872626394.0, 743997347.0, 561890844.0, 722065846.0, 932844470.0, 890426291.0, 884585208.0, 719722188.0, 825666369.0, 733720652.0, 765204717.0, 926137501.0, 839913285.0, 687426064.0, 627235297.0, 800666303.0, 691254240.0, 686220786.0, 619216874.0, 810607627.0, 681586401.0, 719507502.0, 670267753.0, 775120769.0, 787438085.0, 871107248.0, 775184259.0, 617377008.0, 625457007.0, 751739850.0, 837775794.0, 698210927.0, 692649301.0, 751057469.0, 667197049.0, 638455231.0, 684424547.0, 811384530.0, 636619938.0, 764227110.0, 681913069.0, 659990524.0, 851923265.0, 798047667.0, 675701362.0, 659366656.0, 763024977.0, 661054750.0, 715541172.0, 892996646.0, 800368847.0, 686445058.0, 620969174.0, 760324550.0, 743851801.0, 749196062.0, 696562961.0, 788391072.0, 658050670.0, 681798507.0, 749554086.0, 603570199.0, 699328064.0, 745989470.0, 721961978.0, 848241192.0, 770884532.0, 746464712.0, 749935487.0, 678723314.0, 940466261.0, 830362762.0, 771284302.0, 683419383.0, 728443197.0, 693112778.0, 658121020.0, 636015593.0, 650127601.0, 728161417.0, 701329347.0, 618587110.0, 593617790.0, 771238529.0, 856282382.0, 1070429987.0, 839376095.0, 721398999.0, 671514029.0, 699453864.0, 606366462.0, 554056041.0, 596006083.0, 518264492.0, 578637721.0, 624659629.0, 690062754.0, 671164206.0, 622776597.0, 700038349.0, 612080444.0, 767575186.0, 658715804.0, 587487284.0, 533911778.0, 516813361.0, 501343158.0, 545794777.0, 580672477.0, 577719289.0, 577298868.0, 532037578.0, 559658861.0, 607060913.0, 585531637.0, 544146808.0, 527495369.0, 617541610.0, 628269019.0, 708887554.0, 580015082.0, 550437432.0, 561438372.0, 617385140.0, 499949629.0, 486035122.0, 655787936.0, 540532725.0, 576108419.0, 509262869.0, 520368144.0, 826891078.0, 804671634.0, 692613063.0, 558119128.0, 509951578.0, 495804784.0, 478734389.0, 501842470.0, 517116723.0, 432215287.0, 384753863.0, 496555060.0, 666946795.0, 772187061.0, 808239994.0, 662002432.0, 598135396.0, 519502566.0, 710778113.0, 853027795.0, 781767616.0, 525295468.0, 418345821.0, 398062951.0, 470811621.0, 484756832.0, 403463805.0, 491168423.0, 688629481.0, 960673062.0, 952354728.0, 674516163.0, 538618046.0, 561598066.0, 450777700.0, 459614631.0, 506899792.0, 450336313.0, 516770027.0, 533084634.0, 578652571.0, 589787136.0, 548463583.0, 549780520.0, 663044911.0, 664242242.0, 595129079.0, 508894754.0, 529252884.0, 468554607.0, 463081503.0, 445136447.0, 481039194.0, 434923633.0, 449370965.0, 514536361.0, 482410905.0, 434192382.0, 496243769.0, 360921863.0, 417984121.0, 732904733.0, 377708440.0, 362708937.0, 370087897.0, 354125266.0, 389246903.0, 393333040.0, 388573950.0, 374933693.0, 360206493.0, 368120930.0, 415579849.0, 357325091.0, 317290229.0, 293174668.0, 296389646.0, 305699292.0, 317931832.0, 314571197.0, 331092350.0, 449241634.0, 340081877.0, 364286323.0, 341846597.0, 365855862.0, 347700999.0, 422457920.0, 677979510.0, 562966293.0, 461534083.0, 368152723.0, 376179301.0, 315508921.0, 305201067.0, 308564682.0, 326356080.0, 324797198.0, 351076134.0, 349065781.0, 356440270.0, 335567131.0, 339394085.0, 309595848.0, 272953357.0, 261993893.0, 277812372.0, 266869337.0, 265778579.0, 328935425.0, 414472972.0, 336513792.0, 259425073.0, 246633213.0, 248355195.0, 260917564.0, 252089815.0, 241477878.0, 286346190.0, 245001032.0, 238448891.0, 289799519.0, 281387997.0, 281199441.0, 289255837.0, 270780246.0, 309612348.0, 308501981.0, 238402590.0, 303764928.0, 301927047.0, 291699550.0, 251272820.0, 264222024.0, 255020325.0, 265518859.0, 293076289.0, 237710655.0, 232528643.0, 217604288.0, 225976228.0, 257449941.0, 240606649.0, 210772987.0, 216935075.0, 212300160.0, 222331638.0, 260246336.0, 250361144.0, 233265308.0, 234750698.0, 243205913.0, 228547586.0, 210115859.0, 231551437.0, 217444962.0, 193217811.0, 220985058.0, 1073300457.0, 259343728.0, 245677831.0, 249961635.0, 232913137.0, 227714488.0, 228108029.0, 245430258.0, 214204768.0, 245209363.0, 242401648.0, 239239448.0, 245875575.0, 245316142.0, 222347925.0, 194273639.0, 230550622.0, 264507952.0, 272897370.0, 622072528.0, 227792850.0, 233524146.0, 214598982.0, 207842807.0, 248880500.0, 435984167.0, 395514797.0, 275809780.0, 221392988.0, 213865843.0, 213078779.0, 195949975.0, 189146684.0, 170627826.0, 191972760.0, 182092317.0, 156885982.0, 169848219.0, 167607796.0, 177464215.0, 156970036.0, 160811168.0, 177197026.0, 166696255.0, 178706104.0, 199036019.0, 202308549.0, 221473885.0, 206498549.0, 384731328.0, 176780787.0, 171049271.0, 179449669.0, 149933991.0, 167451567.0, 150628754.0, 179771796.0, 151935139.0, 148673326.0, 149133412.0, 141726784.0, 148831907.0, 142679133.0, 147383888.0, 144529565.0, 137231832.0, 139389449.0, 134697280.0, 126159163.0, 145420930.0, 142401257.0, 123476024.0, 135255079.0, 446421100.0, 121852233.0, 125481123.0, 123600952.0, 129662605.0, 128385484.0, 125147018.0, 138755659.0, 138265470.0, 127385058.0, 126807098.0, 119009237.0, 154262634.0, 179096068.0, 175634633.0, 146824795.0, 155363246.0, 124942550.0, 132685137.0, 129665100.0, 139774318.0, 135990290.0, 127356635.0, 131699717.0, 124631608.0, 122026247.0, 133305598.0, 120867319.0, 119332256.0, 118269634.0, 108649085.0, 119291192.0, 116232912.0, 103584708.0, 105405531.0, 108902928.0, 113744660.0, 134602368.0, 130341136.0, 113786084.0, 102931383.0, 100757113.0, 99810128.0, 97167323.0, 110509868.0, 103991787.0, 109881018.0, 105815766.0, 101249643.0, 94367058.0, 99167696.0, 100108435.0, 98210399.0, 86809025.0, 90175569.0, 91484434.0, 93892518.0, 93162558.0, 91282682.0, 89897422.0, 96537531.0, 87860218.0, 89528443.0, 87405504.0, 91428171.0, 104913681.0, 102023415.0, 118535094.0, 112247294.0, 106062612.0, 100309251.0, 94675208.0, 93097380.0, 86867429.0, 84496478.0, 89665434.0, 92199011.0, 91075511.0, 85164047.0, 81229509.0, 82078696.0, 90377606.0, 92172230.0, 92224899.0, 77372587.0, 77142753.0, 82863322.0, 78536844.0, 89968704.0, 84751181.0, 91223748.0, 79305095.0, 81264285.0, 77943473.0, 85881083.0, 85771366.0, 88896879.0, 104770671.0, 101962130.0, 83784168.0, 78146289.0, 79312444.0, 83760747.0)) |
993,611 | 007643de6617849b8a2cac54291edb091acd42f8 | from bs4 import BeautifulSoup
import coinmarketcap as cmc
import custom_utils.HTTP_helpers as HTTPh
import log_service.logger_factory as lf
logging = lf.get_loggly_logger(__name__)
name_lookup_table = cmc.get_name_symbol_lookup_table(lookup_by_name=True)
parent_blockchain_stats = []
parent_blockchain_url_list = []
def get_parent_blockchain_links(min_derivatives=2):
call = "https://tokenmarket.net/blockchain/"
page = HTTPh.general_api_call(call)
if page.status_code == 200:
page = page.content
soup = BeautifulSoup(page, 'html.parser')
parent_blockchain_html_table = soup.tbody.find_all("tr")
coin_dict = {}
for entry in parent_blockchain_html_table:
entry_contents = entry.find_all("td")
num_derivative = int(entry_contents[1].contents[0].string.strip(' \t\n\r'))
parent_blockchain_name = entry_contents[0].contents[1].string.strip(' \t\n\r')
if num_derivative < 2:
break
if parent_blockchain_name != "HyperLedger" and parent_blockchain_name not in name_lookup_table:
continue
if parent_blockchain_name in name_lookup_table:
parent_blockchain_symbol = name_lookup_table[parent_blockchain_name]
coin_dict[parent_blockchain_symbol] = {"symbol":parent_blockchain_symbol, "name":parent_blockchain_name,
"asset_list_url": entry_contents[2].contents[1]['href']}
elif parent_blockchain_name == "HyperLedger":
coin_dict["HyperLedger"] = {"symbol": "HyperLedger", "token_count":num_derivative, "name": parent_blockchain_name,
"asset_list_url": entry_contents[2].contents[1]['href']}
return coin_dict
else:
msg = "Status code of %s returned, data not collected" %str(page.status_code)
logging.warn(msg)
HTTPh.throw_HTTP_error(msg)
def get_derivative_token_list(parent_blockchain_list=None):
platform_dict = {}
if parent_blockchain_list == None:
parent_blockchains = get_parent_blockchain_links()
else:
parent_blockchains = parent_blockchain_list
derivative_asset_dict = {}
for parent_blockchain in parent_blockchains.values():
derivative_coins = {}
page = HTTPh.general_api_call(parent_blockchain["asset_list_url"])
page = page.content
soup = BeautifulSoup(page, 'html.parser')
asset_table = soup.tbody.find_all("tr")
for entry in asset_table:
entry_contents = entry.find_all("td")
token_name = entry_contents[1].contents[1].string.strip(' \t\n\r')
token_symbol = entry_contents[2].contents[0].string.strip(' \t\n\r')
token_description = entry_contents[3].contents[0].string.strip(' \t\n\r')
derivative_coins[token_symbol] = {'symbol': token_symbol, 'name': token_name, 'description':token_description,
'parent_platform_symbol': parent_blockchain['symbol'],
'parent_platform_name': parent_blockchain['name']}
if parent_blockchain['symbol'] not in platform_dict:
platform_dict[parent_blockchain['symbol']] = [derivative_coins[token_symbol]]
else:
platform_dict[parent_blockchain['symbol']].append(derivative_coins[token_symbol])
derivative_asset_dict.update(derivative_coins)
return derivative_asset_dict, parent_blockchains
|
993,612 | 094262c03f6cc2d551172dab95700a707f85c46e | from .cli import main, cli
from .d2 import video_capture
|
993,613 | 8344ffc018bb3859c157d1a8c0bd066661597b9c | # -*- coding: utf-8 -*-
import autograd as ad
import numpy as np
from autograd import config
class C_graph():
"""
aggregating class for the nodes in the computational graph
"""
def __init__(self, nodes=[]):
self.ids=[]
self.input_node=[]
self.output_node=None
self.input_shapes=[]
def reset_graph(self):
#print('start cleaning')
#self.input_node=[]
#self.input_shapes=[]
for node in config.list_of_nodes:
#remove all info from these nodes
node.gradient=None
node.times_visited=0
node.times_used=0
#_variable_.node.childrens={}
#if _variable_.node.childrens!=[]:
#this is not the root node
# _variable_.node.id=
def define_path(self, node):
"""
make a first backward pass without doing any computation
It is just meant to check which variables are involved in the computation of the node given
"""
if node.childrens!=[]:
for child in node.childrens:
node_child = child['node']
node_child.times_used+=1
self.define_path(node_child)
#take care of not used nodes, set their gradient to 0
for node in self.input_node:
if node.times_used==0:
node.gradient=np.zeros((node.output_dim, self.output_node.output_dim))
class Node():
"""
basic element of the computational graph
"""
def __init__(self, output_dim=None):
#ID of the node
if ad.c_graph.ids==[]:
#first node we create
self.id=0
ad.c_graph.ids+=[0]
else:
self.id=ad.c_graph.ids[-1]+1
ad.c_graph.ids+=[self.id]
#dimension of the current variable associated to this node
self.output_dim=output_dim
#number of times this node has been used
self.times_used=0
#number of times this node has been visited in the backprop
self.times_visited=0
#store the gradients of the output node with respect to this node
self.gradient=None
#the childrens list stores the children node, as well as the jacobian used to go from child node
# to this node
#
#for exemple, if we use the block multiply, then the output node of this block will have two children
# y=x1*x2
#
# children 1
#-------------
# node : node associated to x1
# jacobian used to go from x1 to y : diag(x2) because y' = x1'*x2 + x1*x2'
#
#children 2
#-----------
# node : node associated to x2
# jacobian used to go from x2 to y : diag(x1) because y' = x1'*x2 + x1*x2'
#
#
# childrens = [{'node':Node, 'jacobian':Jacobian}, ...]
self.childrens=[]
def backward(self):
"""
implement reverse AD, return the gradient of current variable w.r. input Variables
input variables are the ones who don't have any childrens
"""
#initiate the gradients
#print('')
#print('node {} grad {}'.format(self.id, self.gradient))
#print('node {} times visited : {}/{}'.format(self.id, self.times_visited, self.times_used))
if self.gradient is None:
self.gradient=np.eye(self.output_dim)
self.times_visited+=1
if self.childrens==[]:
return(self.gradient)
else:
self.backward()
else:
if self.childrens!=[]:
#we can still going deeper in backprop
#print(len(self.childrens), ' childrens', str([self.childrens[i]['node'].id for i in range(len(self.childrens))]))
for child in self.childrens:
node,jacobian=child['node'], child['jacobian']
new_grad = np.dot(self.gradient, jacobian)
#print(node.gradient)
#print(new_grad)
if node.gradient is None:
node.gradient = new_grad
else:
node.gradient += new_grad
node.times_visited+=1
#print('looking at node {} \ngradient {}'.format(node.id, node.gradient))
if node.times_used ==node.times_visited:
#print(node.gradient)
node.backward()
else:
#still some computations to perform upwards before going deeped
#print('node {} visits : {}/{}'.format(node.id, node.times_visited, node.times_used))
pass
|
993,614 | cdc6eb23d04b05e66379e3deeaf69974c2490400 |
# pair of parentheses to denote the empty tuple
t1 = ()
# trailing comma for a singleton tuple
t2 = 1,
t3 = (2,)
# separating items with commas
t4 = 1,2,3
t5 = (3,4,5)
# using the tuple()
t6 = tuple()
t7 = tuple([1,2,3,4])
print(t1)
print(t2)
print(t3)
print(t4)
print(t5)
print(t6)
print(t7)
|
993,615 | 27bd976760446078f21e2a974f3f645147fa8b1d | # coding=utf-8
from engineer.unittests.config_tests import BaseTestCase
__author__ = 'Tyler Butler <tyler@tylerbutler.com>'
finalization_draft_output = """title: Finalization Draft
status: draft
slug: finalization-draft
tags:
- tag
---
This is a finalization test post.
"""
finalization_fenced_output = """---
title: Finalization Fenced
status: draft
slug: finalization-fenced
tags:
- tag
---
This is a finalization test post.
"""
class MetadataFinalizationTestCase(BaseTestCase):
def test_finalization_settings(self):
from engineer.plugins.bundled import FinalizationPlugin
self.assertTrue('config' in FinalizationPlugin.get_settings())
def test_finalization_draft(self):
from engineer.conf import settings
from engineer.models import Post
settings.reload('finalization.yaml')
settings.create_required_directories()
post = Post('posts/finalization_draft.md')
self.assertEqual(post.title, "Finalization Draft")
expected_output = finalization_draft_output
with open(post.source, mode='rb') as post_file:
content = post_file.read()
self.assertEqual(content, expected_output)
def test_finalization_fenced_post(self):
from engineer.conf import settings
from engineer.models import Post
settings.reload('finalization.yaml')
settings.create_required_directories()
post = Post('posts/finalization_fenced.md')
self.assertEqual(post.title, "Finalization Fenced")
expected_output = finalization_fenced_output
with open(post.source, mode='rb') as post_file:
content = post_file.read()
self.assertEqual(content, expected_output)
def test_force_fenced_metadata(self):
from engineer.conf import settings
from engineer.models import Post
settings.reload('finalization_fenced.yaml')
settings.create_required_directories()
post = Post('posts/finalization_draft.md')
self.assertEqual(post.title, "Finalization Draft")
expected_output = '---\n\n' + finalization_draft_output
with open(post.source, mode='rb') as post_file:
content = post_file.read()
self.assertEqual(content, expected_output)
def test_finalization_unfenced_post(self):
from engineer.conf import settings
from engineer.models import Post
settings.reload('finalization_unfenced.yaml')
settings.create_required_directories()
post = Post('posts/finalization_fenced.md')
self.assertEqual(post.title, "Finalization Fenced")
expected_output = ''.join(finalization_fenced_output.splitlines(True)[2:])
with open(post.source, mode='rb') as post_file:
content = post_file.read()
self.assertEqual(content, expected_output)
|
993,616 | 2c729b3dec28875f99e7b16cd4787e5b59aafefc |
import pathlib
import yara
from pprint import pprint
base_dir = pathlib.Path(__file__).parent.absolute()
rule_path = base_dir.joinpath('rules', 'string_match.yar').as_posix()
rules = yara.compile(filepath=rule_path)
with open(base_dir.joinpath('sample.txt'), 'rb') as f:
matches = rules.match(data=f.read())
pprint(matches)
# Output:
#
# {'main': [{'matches': True,
# 'meta': {},
# 'rule': 'test',
# 'strings': [{'data': 'Lorem',
# 'flags': 19,
# 'identifier': '$identifier',
# 'offset': 561},
# {'data': 'Lorem',
# 'flags': 19,
# 'identifier': '$identifier',
# 'offset': 2337}],
# 'tags': []}]}
with open(base_dir.joinpath('sample_2.txt'), 'rb') as f:
matches = rules.match(data=f.read())
pprint(matches)
# no match because "trust" is within the file |
993,617 | 5ef9a0dd9c58573113afdbecbfa646eb95efbf8c | import asyncio
import inspect
import logging
import os
import traceback
import random
from contextlib import redirect_stdout
from datetime import datetime
from difflib import get_close_matches
from io import StringIO, BytesIO
from itertools import zip_longest, takewhile
from json import JSONDecodeError, loads
from textwrap import indent
from types import SimpleNamespace
from typing import Union
from discord import Embed, Color, Activity, Role
from discord.enums import ActivityType, Status
from discord.ext import commands, tasks
from discord.utils import escape_markdown, escape_mentions
from aiohttp import ClientResponseError
from pkg_resources import parse_version
from core import checks
from core.changelog import Changelog
from core.decorators import trigger_typing
from core.models import InvalidConfigError, PermissionLevel
from core.paginator import EmbedPaginatorSession, MessagePaginatorSession
from core import utils
logger = logging.getLogger("Modmail")
class ModmailHelpCommand(commands.HelpCommand):
async def format_cog_help(self, cog, *, no_cog=False):
bot = self.context.bot
prefix = self.clean_prefix
formats = [""]
for cmd in await self.filter_commands(
cog.get_commands() if not no_cog else cog,
sort=True,
key=lambda c: bot.command_perm(c.qualified_name),
):
perm_level = bot.command_perm(cmd.qualified_name)
if perm_level is PermissionLevel.INVALID:
format_ = f"`{prefix + cmd.qualified_name}` "
else:
format_ = f"`[{perm_level}] {prefix + cmd.qualified_name}` "
format_ += f"- {cmd.short_doc}\n"
if not format_.strip():
continue
if len(format_) + len(formats[-1]) >= 1024:
formats.append(format_)
else:
formats[-1] += format_
embeds = []
for format_ in formats:
description = (
cog.description or "No description."
if not no_cog
else "Miscellaneous commands without a category."
)
embed = Embed(description=f"*{description}*", color=bot.main_color)
embed.add_field(name="Commands", value=format_ or "No commands.")
continued = " (Continued)" if embeds else ""
name = (
cog.qualified_name + " - Help"
if not no_cog
else "Miscellaneous Commands"
)
embed.set_author(name=name + continued, icon_url=bot.user.avatar_url)
embed.set_footer(
text=f'Type "{prefix}{self.command_attrs["name"]} command" '
"for more info on a specific command."
)
embeds.append(embed)
return embeds
def process_help_msg(self, help_: str):
return help_.format(prefix=self.clean_prefix) if help_ else "No help message."
async def send_bot_help(self, mapping):
embeds = []
no_cog_commands = sorted(mapping.pop(None), key=lambda c: c.qualified_name)
cogs = sorted(mapping, key=lambda c: c.qualified_name)
bot = self.context.bot
# always come first
default_cogs = [
bot.get_cog("Modmail"),
bot.get_cog("Utility"),
bot.get_cog("Plugins"),
]
default_cogs.extend(c for c in cogs if c not in default_cogs)
for cog in default_cogs:
embeds.extend(await self.format_cog_help(cog))
if no_cog_commands:
embeds.extend(await self.format_cog_help(no_cog_commands, no_cog=True))
session = EmbedPaginatorSession(
self.context, *embeds, destination=self.get_destination()
)
return await session.run()
async def send_cog_help(self, cog):
embeds = await self.format_cog_help(cog)
session = EmbedPaginatorSession(
self.context, *embeds, destination=self.get_destination()
)
return await session.run()
async def send_command_help(self, command):
if not await self.filter_commands([command]):
return
perm_level = self.context.bot.command_perm(command.qualified_name)
if perm_level is not PermissionLevel.INVALID:
perm_level = f"{perm_level.name} [{perm_level}]"
else:
perm_level = "NONE"
embed = Embed(
title=f"`{self.get_command_signature(command)}`",
color=self.context.bot.main_color,
description=self.process_help_msg(command.help),
)
embed.set_footer(text=f"Permission level: {perm_level}")
await self.get_destination().send(embed=embed)
async def send_group_help(self, group):
if not await self.filter_commands([group]):
return
perm_level = self.context.bot.command_perm(group.qualified_name)
if perm_level is not PermissionLevel.INVALID:
perm_level = f"{perm_level.name} [{perm_level}]"
else:
perm_level = "NONE"
embed = Embed(
title=f"`{self.get_command_signature(group)}`",
color=self.context.bot.main_color,
description=self.process_help_msg(group.help),
)
if perm_level:
embed.add_field(name="Permission Level", value=perm_level, inline=False)
format_ = ""
length = len(group.commands)
for i, command in enumerate(
await self.filter_commands(group.commands, sort=True, key=lambda c: c.name)
):
# BUG: fmt may run over the embed limit
# TODO: paginate this
if length == i + 1: # last
branch = "└─"
else:
branch = "├─"
format_ += f"`{branch} {command.name}` - {command.short_doc}\n"
embed.add_field(name="Sub Command(s)", value=format_[:1024], inline=False)
embed.set_footer(
text=f'Type "{self.clean_prefix}{self.command_attrs["name"]} command" '
"for more info on a command."
)
await self.get_destination().send(embed=embed)
async def send_error_message(self, error):
command = self.context.kwargs.get("command")
val = self.context.bot.snippets.get(command)
if val is not None:
return await self.get_destination().send(
escape_mentions(f"**`{command}` is a snippet, " f"content:**\n\n{val}")
)
val = self.context.bot.aliases.get(command)
if val is not None:
values = utils.parse_alias(val)
if len(values) == 1:
embed = Embed(
title=f"{command} is an alias.",
color=self.context.bot.main_color,
description=f"`{command}` points to `{escape_markdown(values[0])}`.",
)
else:
embed = Embed(
title=f"{command} is an alias.",
color=self.context.bot.main_color,
description=f"**`{command}` points to the following steps:**",
)
for i, val in enumerate(values, start=1):
embed.description += f"\n{i}: {escape_markdown(val)}"
embed.set_footer(
text=f'Type "{self.clean_prefix}{self.command_attrs["name"]} alias" for more '
"details on aliases."
)
return await self.get_destination().send(embed=embed)
logger.warning("CommandNotFound: %s", str(error))
embed = Embed(color=Color.red())
embed.set_footer(text=f'Command/Category "{command}" not found.')
choices = set()
for cmd in self.context.bot.walk_commands():
if not cmd.hidden:
choices.add(cmd.qualified_name)
closest = get_close_matches(command, choices)
if closest:
embed.add_field(
name=f"Perhaps you meant:", value="\n".join(f"`{x}`" for x in closest)
)
else:
embed.title = "Cannot find command or category"
embed.set_footer(
text=f'Type "{self.clean_prefix}{self.command_attrs["name"]}" '
"for a list of all available commands."
)
await self.get_destination().send(embed=embed)
class Utility(commands.Cog):
"""General commands that provide utility."""
def __init__(self, bot):
self.bot = bot
self._original_help_command = bot.help_command
self.bot.help_command = ModmailHelpCommand(
verify_checks=False,
command_attrs={
"help": "Shows this help message.",
"checks": [checks.has_permissions_predicate(PermissionLevel.REGULAR)],
},
)
self.bot.help_command.cog = self
self.loop_presence.start()
def cog_unload(self):
self.bot.help_command = self._original_help_command
@commands.command()
@checks.has_permissions(PermissionLevel.REGULAR)
@trigger_typing
async def changelog(self, ctx, version: str.lower = ""):
"""Shows the changelog of the Modmail."""
changelog = await Changelog.from_url(self.bot)
version = version.lstrip("vV") if version else changelog.latest_version.version
try:
index = [v.version for v in changelog.versions].index(version)
except ValueError:
return await ctx.send(
embed=Embed(
color=Color.red(),
description=f"The specified version `{version}` could not be found.",
)
)
paginator = EmbedPaginatorSession(ctx, *changelog.embeds)
try:
paginator.current = index
await paginator.run()
except asyncio.CancelledError:
pass
except Exception:
try:
await paginator.close()
except Exception:
pass
logger.warning("Failed to display changelog.", exc_info=True)
await ctx.send(
f"View the changelog here: {changelog.CHANGELOG_URL}#v{version[::2]}"
)
@commands.command(aliases=["bot", "info"])
@checks.has_permissions(PermissionLevel.REGULAR)
@trigger_typing
async def about(self, ctx):
"""Shows information about this bot."""
embed = Embed(color=self.bot.main_color, timestamp=datetime.utcnow())
embed.set_author(
name="Modmail - About",
icon_url=self.bot.user.avatar_url,
url="https://discord.gg/F34cRU8",
)
embed.set_thumbnail(url=self.bot.user.avatar_url)
desc = "This is an open source Discord bot that serves as a means for "
desc += "members to easily communicate with server administrators in "
desc += "an organised manner."
embed.description = desc
embed.add_field(name="Uptime", value=self.bot.uptime)
embed.add_field(name="Latency", value=f"{self.bot.latency * 1000:.2f} ms")
embed.add_field(name="Version", value=f"`{self.bot.version}`")
embed.add_field(name="Author", value="[`kyb3r`](https://github.com/kyb3r)")
changelog = await Changelog.from_url(self.bot)
latest = changelog.latest_version
if parse_version(self.bot.version) < parse_version(latest.version):
footer = f"A newer version is available v{latest.version}"
else:
footer = "You are up to date with the latest version."
embed.add_field(
name="GitHub", value="https://github.com/kyb3r/modmail", inline=False
)
embed.add_field(
name="Discord Server", value="https://discord.gg/F34cRU8", inline=False
)
embed.add_field(
name="Donate",
value="Support this bot on [`Patreon`](https://patreon.com/kyber).",
)
embed.set_footer(text=footer)
await ctx.send(embed=embed)
@commands.command()
@checks.has_permissions(PermissionLevel.REGULAR)
@trigger_typing
async def sponsors(self, ctx):
"""Shows a list of sponsors."""
resp = await self.bot.session.get(
"https://raw.githubusercontent.com/kyb3r/modmail/master/SPONSORS.json"
)
data = loads(await resp.text())
embeds = []
for elem in data:
embed = Embed.from_dict(elem["embed"])
embeds.append(embed)
random.shuffle(embeds)
session = EmbedPaginatorSession(ctx, *embeds)
await session.run()
@commands.group(invoke_without_command=True)
@checks.has_permissions(PermissionLevel.OWNER)
@trigger_typing
async def debug(self, ctx):
"""Shows the recent application-logs of the bot."""
log_file_name = self.bot.token.split(".")[0]
with open(
os.path.join(
os.path.dirname(os.path.abspath(__file__)),
f"../temp/{log_file_name}.log",
),
"r+",
) as f:
logs = f.read().strip()
if not logs:
embed = Embed(
color=self.bot.main_color,
title="Debug Logs:",
description="You don't have any logs at the moment.",
)
embed.set_footer(text="Go to Heroku to see your logs.")
return await ctx.send(embed=embed)
messages = []
# Using Scala formatting because it's similar to Python for exceptions
# and it does a fine job formatting the logs.
msg = "```Scala\n"
for line in logs.splitlines(keepends=True):
if msg != "```Scala\n":
if len(line) + len(msg) + 3 > 2000:
msg += "```"
messages.append(msg)
msg = "```Scala\n"
msg += line
if len(msg) + 3 > 2000:
msg = msg[:1993] + "[...]```"
messages.append(msg)
msg = "```Scala\n"
if msg != "```Scala\n":
msg += "```"
messages.append(msg)
embed = Embed(color=self.bot.main_color)
embed.set_footer(text="Debug logs - Navigate using the reactions below.")
session = MessagePaginatorSession(ctx, *messages, embed=embed)
session.current = len(messages) - 1
return await session.run()
@debug.command(name="hastebin", aliases=["haste"])
@checks.has_permissions(PermissionLevel.OWNER)
@trigger_typing
async def debug_hastebin(self, ctx):
"""Posts application-logs to Hastebin."""
haste_url = os.environ.get("HASTE_URL", "https://hasteb.in")
log_file_name = self.bot.token.split(".")[0]
with open(
os.path.join(
os.path.dirname(os.path.abspath(__file__)),
f"../temp/{log_file_name}.log",
),
"rb+",
) as f:
logs = BytesIO(f.read().strip())
try:
async with self.bot.session.post(
haste_url + "/documents", data=logs
) as resp:
data = await resp.json()
try:
key = data["key"]
except KeyError:
logger.error(data["message"])
raise
embed = Embed(
title="Debug Logs",
color=self.bot.main_color,
description=f"{haste_url}/" + key,
)
except (JSONDecodeError, ClientResponseError, IndexError, KeyError):
embed = Embed(
title="Debug Logs",
color=self.bot.main_color,
description="Something's wrong. "
"We're unable to upload your logs to hastebin.",
)
embed.set_footer(text="Go to Heroku to see your logs.")
await ctx.send(embed=embed)
@debug.command(name="clear", aliases=["wipe"])
@checks.has_permissions(PermissionLevel.OWNER)
@trigger_typing
async def debug_clear(self, ctx):
"""Clears the locally cached logs."""
log_file_name = self.bot.token.split(".")[0]
with open(
os.path.join(
os.path.dirname(os.path.abspath(__file__)),
f"../temp/{log_file_name}.log",
),
"w",
):
pass
await ctx.send(
embed=Embed(
color=self.bot.main_color, description="Cached logs are now cleared."
)
)
@commands.command(aliases=["presence"])
@checks.has_permissions(PermissionLevel.ADMINISTRATOR)
async def activity(self, ctx, activity_type: str.lower, *, message: str = ""):
"""
Set an activity status for the bot.
Possible activity types:
- `playing`
- `streaming`
- `listening`
- `watching`
When activity type is set to `listening`,
it must be followed by a "to": "listening to..."
When activity type is set to `streaming`, you can set
the linked twitch page:
- `{prefix}config set twitch_url https://www.twitch.tv/somechannel/`
To remove the current activity status:
- `{prefix}activity clear`
"""
if activity_type == "clear":
self.bot.config.remove("activity_type")
self.bot.config.remove("activity_message")
await self.bot.config.update()
await self.set_presence()
embed = Embed(title="Activity Removed", color=self.bot.main_color)
return await ctx.send(embed=embed)
if not message:
raise commands.MissingRequiredArgument(SimpleNamespace(name="message"))
activity, msg = (
await self.set_presence(
activity_identifier=activity_type,
activity_by_key=True,
activity_message=message,
)
)["activity"]
if activity is None:
raise commands.MissingRequiredArgument(SimpleNamespace(name="activity"))
self.bot.config["activity_type"] = activity.type.value
self.bot.config["activity_message"] = message
await self.bot.config.update()
embed = Embed(
title="Activity Changed", description=msg, color=self.bot.main_color
)
return await ctx.send(embed=embed)
@commands.command()
@checks.has_permissions(PermissionLevel.ADMINISTRATOR)
async def status(self, ctx, *, status_type: str.lower):
"""
Set a status for the bot.
Possible status types:
- `online`
- `idle`
- `dnd`
- `do_not_disturb` or `do not disturb`
- `invisible` or `offline`
To remove the current status:
- `{prefix}status clear`
"""
if status_type == "clear":
self.bot.config.remove("status")
await self.bot.config.update()
await self.set_presence()
embed = Embed(title="Status Removed", color=self.bot.main_color)
return await ctx.send(embed=embed)
status_type = status_type.replace(" ", "_")
status, msg = (
await self.set_presence(status_identifier=status_type, status_by_key=True)
)["status"]
if status is None:
raise commands.MissingRequiredArgument(SimpleNamespace(name="status"))
self.bot.config["status"] = status.value
await self.bot.config.update()
embed = Embed(
title="Status Changed", description=msg, color=self.bot.main_color
)
return await ctx.send(embed=embed)
async def set_presence(
self,
*,
status_identifier=None,
status_by_key=True,
activity_identifier=None,
activity_by_key=True,
activity_message=None,
):
activity = status = None
if status_identifier is None:
status_identifier = self.bot.config["status"]
status_by_key = False
try:
if status_by_key:
status = Status[status_identifier]
else:
status = Status.try_value(status_identifier)
except (KeyError, ValueError):
if status_identifier is not None:
msg = f"Invalid status type: {status_identifier}"
logger.warning(msg)
if activity_identifier is None:
if activity_message is not None:
raise ValueError(
"activity_message must be None if activity_identifier is None."
)
activity_identifier = self.bot.config["activity_type"]
activity_by_key = False
try:
if activity_by_key:
activity_type = ActivityType[activity_identifier]
else:
activity_type = ActivityType.try_value(activity_identifier)
except (KeyError, ValueError):
if activity_identifier is not None:
msg = f"Invalid activity type: {activity_identifier}"
logger.warning(msg)
else:
url = None
activity_message = (
activity_message or self.bot.config["activity_message"]
).strip()
if activity_type == ActivityType.listening:
if activity_message.lower().startswith("to "):
# The actual message is after listening to [...]
# discord automatically add the "to"
activity_message = activity_message[3:].strip()
elif activity_type == ActivityType.streaming:
url = self.bot.config["twitch_url"]
if activity_message:
activity = Activity(type=activity_type, name=activity_message, url=url)
else:
msg = "You must supply an activity message to use custom activity."
logger.debug(msg)
await self.bot.change_presence(activity=activity, status=status)
presence = {
"activity": (None, "No activity has been set."),
"status": (None, "No status has been set."),
}
if activity is not None:
use_to = "to " if activity.type == ActivityType.listening else ""
msg = f"Activity set to: {activity.type.name.capitalize()} "
msg += f"{use_to}{activity.name}."
presence["activity"] = (activity, msg)
if status is not None:
msg = f"Status set to: {status.value}."
presence["status"] = (status, msg)
return presence
@tasks.loop(minutes=45)
async def loop_presence(self):
"""Set presence to the configured value every 45 minutes."""
# TODO: Does this even work?
presence = await self.set_presence()
logger.debug(f'{presence["activity"][1]} {presence["status"][1]}')
@loop_presence.before_loop
async def before_loop_presence(self):
await self.bot.wait_for_connected()
logger.debug("Starting metadata loop.")
logger.line()
presence = await self.set_presence()
logger.info(presence["activity"][1])
logger.info(presence["status"][1])
await asyncio.sleep(2700)
@commands.command()
@checks.has_permissions(PermissionLevel.ADMINISTRATOR)
@trigger_typing
async def ping(self, ctx):
"""Pong! Returns your websocket latency."""
embed = Embed(
title="Pong! Websocket Latency:",
description=f"{self.bot.ws.latency * 1000:.4f} ms",
color=self.bot.main_color,
)
return await ctx.send(embed=embed)
@commands.command()
@checks.has_permissions(PermissionLevel.ADMINISTRATOR)
async def mention(self, ctx, *, mention: str = None):
"""
Change what the bot mentions at the start of each thread.
Type only `{prefix}mention` to retrieve your current "mention" message.
"""
# TODO: ability to disable mention.
current = self.bot.config["mention"]
if mention is None:
embed = Embed(
title="Current mention:",
color=self.bot.main_color,
description=str(current),
)
else:
embed = Embed(
title="Changed mention!",
description=f'On thread creation the bot now says "{mention}".',
color=self.bot.main_color,
)
self.bot.config["mention"] = mention
await self.bot.config.update()
return await ctx.send(embed=embed)
@commands.command()
@checks.has_permissions(PermissionLevel.ADMINISTRATOR)
async def prefix(self, ctx, *, prefix=None):
"""
Change the prefix of the bot.
Type only `{prefix}prefix` to retrieve your current bot prefix.
"""
current = self.bot.prefix
embed = Embed(
title="Current prefix", color=self.bot.main_color, description=f"{current}"
)
if prefix is None:
await ctx.send(embed=embed)
else:
embed.title = "Changed prefix!"
embed.description = f"Set prefix to `{prefix}`"
self.bot.config["prefix"] = prefix
await self.bot.config.update()
await ctx.send(embed=embed)
@commands.group(aliases=["configuration"], invoke_without_command=True)
@checks.has_permissions(PermissionLevel.OWNER)
async def config(self, ctx):
"""
Modify changeable configuration variables for this bot.
Type `{prefix}config options` to view a list
of valid configuration variables.
Type `{prefix}config help config-name` for info
on a config.
To set a configuration variable:
- `{prefix}config set config-name value here`
To remove a configuration variable:
- `{prefix}config remove config-name`
"""
await ctx.send_help(ctx.command)
@config.command(name="options", aliases=["list"])
@checks.has_permissions(PermissionLevel.OWNER)
async def config_options(self, ctx):
"""Return a list of valid configuration names you can change."""
embeds = []
for names in zip_longest(*(iter(sorted(self.bot.config.public_keys)),) * 15):
description = "\n".join(
f"`{name}`" for name in takewhile(lambda x: x is not None, names)
)
embed = Embed(
title="Available configuration keys:",
color=self.bot.main_color,
description=description,
)
embeds.append(embed)
session = EmbedPaginatorSession(ctx, *embeds)
await session.run()
@config.command(name="set", aliases=["add"])
@checks.has_permissions(PermissionLevel.OWNER)
async def config_set(self, ctx, key: str.lower, *, value: str):
"""Set a configuration variable and its value."""
keys = self.bot.config.public_keys
if key in keys:
try:
value, value_text = await self.bot.config.clean_data(key, value)
except InvalidConfigError as exc:
embed = exc.embed
else:
self.bot.config[key] = value
await self.bot.config.update()
embed = Embed(
title="Success",
color=self.bot.main_color,
description=f"Set `{key}` to `{value_text}`",
)
else:
embed = Embed(
title="Error",
color=Color.red(),
description=f"{key} is an invalid key.",
)
valid_keys = [f"`{k}`" for k in keys]
embed.add_field(name="Valid keys", value=", ".join(valid_keys))
return await ctx.send(embed=embed)
@config.command(name="remove", aliases=["del", "delete"])
@checks.has_permissions(PermissionLevel.OWNER)
async def config_remove(self, ctx, key: str.lower):
"""Delete a set configuration variable."""
keys = self.bot.config.public_keys
if key in keys:
self.bot.config.remove(key)
await self.bot.config.update()
embed = Embed(
title="Success",
color=self.bot.main_color,
description=f"`{key}` had been reset to default.",
)
else:
embed = Embed(
title="Error",
color=Color.red(),
description=f"{key} is an invalid key.",
)
valid_keys = [f"`{k}`" for k in keys]
embed.add_field(name="Valid keys", value=", ".join(valid_keys))
return await ctx.send(embed=embed)
@config.command(name="get")
@checks.has_permissions(PermissionLevel.OWNER)
async def config_get(self, ctx, key: str.lower = None):
"""
Show the configuration variables that are currently set.
Leave `key` empty to show all currently set configuration variables.
"""
keys = self.bot.config.public_keys
if key:
if key in keys:
desc = f"`{key}` is set to `{self.bot.config[key]}`"
embed = Embed(color=self.bot.main_color, description=desc)
embed.set_author(
name="Config variable", icon_url=self.bot.user.avatar_url
)
else:
embed = Embed(
title="Error",
color=Color.red(),
description=f"`{key}` is an invalid key.",
)
embed.set_footer(
text=f'Type "{self.bot.prefix}config options" for a list of config variables.'
)
else:
embed = Embed(
color=self.bot.main_color,
description="Here is a list of currently "
"set configuration variable(s).",
)
embed.set_author(
name="Current config(s):", icon_url=self.bot.user.avatar_url
)
config = self.bot.config.filter_default(self.bot.config)
for name, value in config.items():
if name in self.bot.config.public_keys:
embed.add_field(name=name, value=f"`{value}`", inline=False)
return await ctx.send(embed=embed)
@config.command(name="help", aliases=["info"])
@checks.has_permissions(PermissionLevel.OWNER)
async def config_help(self, ctx, key: str.lower = None):
"""
Show information on a specified configuration.
"""
if key is not None and not (
key in self.bot.config.public_keys or key in self.bot.config.protected_keys
):
embed = Embed(
title="Error",
color=Color.red(),
description=f"`{key}` is an invalid key.",
)
return await ctx.send(embed=embed)
config_help = self.bot.config.config_help
if key is not None and key not in config_help:
embed = Embed(
title="Error",
color=Color.red(),
description=f"No help details found for `{key}`.",
)
return await ctx.send(embed=embed)
def fmt(val):
return val.format(prefix=self.bot.prefix, bot=self.bot)
index = 0
embeds = []
for i, (current_key, info) in enumerate(config_help.items()):
if current_key == key:
index = i
embed = Embed(
title=f"Configuration description on {current_key}:",
color=self.bot.main_color,
)
embed.add_field(name="Default:", value=fmt(info["default"]), inline=False)
embed.add_field(
name="Information:", value=fmt(info["description"]), inline=False
)
if info["examples"]:
example_text = ""
for example in info["examples"]:
example_text += f"- {fmt(example)}\n"
embed.add_field(name="Example(s):", value=example_text, inline=False)
note_text = ""
for note in info["notes"]:
note_text += f"- {fmt(note)}\n"
if note_text:
embed.add_field(name="Note(s):", value=note_text, inline=False)
if info.get("image") is not None:
embed.set_image(url=fmt(info["image"]))
if info.get("thumbnail") is not None:
embed.set_thumbnail(url=fmt(info["thumbnail"]))
embeds += [embed]
paginator = EmbedPaginatorSession(ctx, *embeds)
paginator.current = index
await paginator.run()
@commands.group(aliases=["aliases"], invoke_without_command=True)
@checks.has_permissions(PermissionLevel.MODERATOR)
async def alias(self, ctx, *, name: str.lower = None):
"""
Create shortcuts to bot commands.
When `{prefix}alias` is used by itself, this will retrieve
a list of alias that are currently set. `{prefix}alias-name` will show what the
alias point to.
To use alias:
First create an alias using:
- `{prefix}alias add alias-name other-command`
For example:
- `{prefix}alias add r reply`
- Now you can use `{prefix}r` as an replacement for `{prefix}reply`.
See also `{prefix}snippet`.
"""
if name is not None:
val = self.bot.aliases.get(name)
if val is None:
embed = utils.create_not_found_embed(
name, self.bot.aliases.keys(), "Alias"
)
return await ctx.send(embed=embed)
values = utils.parse_alias(val)
if not values:
embed = Embed(
title="Error",
color=Color.red(),
description=f"Alias `{name}` is invalid, it used to be `{escape_markdown(val)}`. "
f"This alias will now be deleted.",
)
self.bot.aliases.pop(name)
await self.bot.config.update()
return await ctx.send(embed=embed)
if len(values) == 1:
embed = Embed(
color=self.bot.main_color,
description=f"`{name}` points to `{escape_markdown(values[0])}`.",
)
else:
embed = Embed(
color=self.bot.main_color,
description=f"**`{name}` points to the following steps:**",
)
for i, val in enumerate(values, start=1):
embed.description += f"\n{i}: {escape_markdown(val)}"
return await ctx.send(embed=embed)
if not self.bot.aliases:
embed = Embed(
color=Color.red(),
description="You dont have any aliases at the moment.",
)
embed.set_footer(text=f"Do {self.bot.prefix}help alias for more commands.")
embed.set_author(name="Aliases", icon_url=ctx.guild.icon_url)
return await ctx.send(embed=embed)
embeds = []
for i, names in enumerate(zip_longest(*(iter(sorted(self.bot.aliases)),) * 15)):
description = utils.format_description(i, names)
embed = Embed(color=self.bot.main_color, description=description)
embed.set_author(name="Command Aliases", icon_url=ctx.guild.icon_url)
embeds.append(embed)
session = EmbedPaginatorSession(ctx, *embeds)
await session.run()
@alias.command(name="raw")
@checks.has_permissions(PermissionLevel.MODERATOR)
async def alias_raw(self, ctx, *, name: str.lower):
"""
View the raw content of an alias.
"""
val = self.bot.aliases.get(name)
if val is None:
embed = utils.create_not_found_embed(name, self.bot.aliases.keys(), "Alias")
return await ctx.send(embed=embed)
return await ctx.send(escape_markdown(escape_mentions(val)).replace("<", "\\<"))
@alias.command(name="add")
@checks.has_permissions(PermissionLevel.MODERATOR)
async def alias_add(self, ctx, name: str.lower, *, value):
"""
Add an alias.
Alias also supports multi-step aliases, to create a multi-step alias use quotes
to wrap each step and separate each step with `&&`. For example:
- `{prefix}alias add movenreply "move admin-category" && "reply Thanks for reaching out to the admins"`
However, if you run into problems, try wrapping the command with quotes. For example:
- This will fail: `{prefix}alias add reply You'll need to type && to work`
- Correct method: `{prefix}alias add reply "You'll need to type && to work"`
"""
embed = None
if self.bot.get_command(name):
embed = Embed(
title="Error",
color=Color.red(),
description=f"A command with the same name already exists: `{name}`.",
)
elif name in self.bot.aliases:
embed = Embed(
title="Error",
color=Color.red(),
description=f"Another alias with the same name already exists: `{name}`.",
)
elif name in self.bot.snippets:
embed = Embed(
title="Error",
color=Color.red(),
description=f"A snippet with the same name already exists: `{name}`.",
)
elif len(name) > 120:
embed = Embed(
title="Error",
color=Color.red(),
description=f"Alias names cannot be longer than 120 characters.",
)
if embed is not None:
return await ctx.send(embed=embed)
values = utils.parse_alias(value)
if not values:
embed = Embed(
title="Error",
color=Color.red(),
description="Invalid multi-step alias, try wrapping each steps in quotes.",
)
embed.set_footer(text=f'See "{self.bot.prefix}alias add" for more details.')
return await ctx.send(embed=embed)
if len(values) == 1:
linked_command = values[0].split()[0].lower()
if not self.bot.get_command(linked_command):
embed = Embed(
title="Error",
color=Color.red(),
description="The command you are attempting to point "
f"to does not exist: `{linked_command}`.",
)
return await ctx.send(embed=embed)
embed = Embed(
title="Added alias",
color=self.bot.main_color,
description=f'`{name}` points to: "{values[0]}".',
)
else:
embed = Embed(
title="Added alias",
color=self.bot.main_color,
description=f"`{name}` now points to the following steps:",
)
for i, val in enumerate(values, start=1):
linked_command = val.split()[0]
if not self.bot.get_command(linked_command):
embed = Embed(
title="Error",
color=Color.red(),
description="The command you are attempting to point "
f"to on step {i} does not exist: `{linked_command}`.",
)
return await ctx.send(embed=embed)
embed.description += f"\n{i}: {val}"
self.bot.aliases[name] = " && ".join(values)
await self.bot.config.update()
return await ctx.send(embed=embed)
@alias.command(name="remove", aliases=["del", "delete"])
@checks.has_permissions(PermissionLevel.MODERATOR)
async def alias_remove(self, ctx, *, name: str.lower):
"""Remove an alias."""
if name in self.bot.aliases:
self.bot.aliases.pop(name)
await self.bot.config.update()
embed = Embed(
title="Removed alias",
color=self.bot.main_color,
description=f"Successfully deleted `{name}`.",
)
else:
embed = utils.create_not_found_embed(name, self.bot.aliases.keys(), "Alias")
return await ctx.send(embed=embed)
@alias.command(name="edit")
@checks.has_permissions(PermissionLevel.MODERATOR)
async def alias_edit(self, ctx, name: str.lower, *, value):
"""
Edit an alias.
"""
if name not in self.bot.aliases:
embed = utils.create_not_found_embed(name, self.bot.aliases.keys(), "Alias")
return await ctx.send(embed=embed)
values = utils.parse_alias(value)
if not values:
embed = Embed(
title="Error",
color=Color.red(),
description="Invalid multi-step alias, try wrapping each steps in quotes.",
)
embed.set_footer(text=f'See "{self.bot.prefix}alias add" for more details.')
return await ctx.send(embed=embed)
if len(values) == 1:
linked_command = values[0].split()[0].lower()
if not self.bot.get_command(linked_command):
embed = Embed(
title="Error",
color=Color.red(),
description="The command you are attempting to point "
f"to does not exist: `{linked_command}`.",
)
return await ctx.send(embed=embed)
embed = Embed(
title="Edited alias",
color=self.bot.main_color,
description=f'`{name}` now points to: "{values[0]}".',
)
else:
embed = Embed(
title="Edited alias",
color=self.bot.main_color,
description=f"`{name}` now points to the following steps:",
)
for i, val in enumerate(values, start=1):
linked_command = val.split()[0]
if not self.bot.get_command(linked_command):
embed = Embed(
title="Error",
color=Color.red(),
description="The command you are attempting to point "
f"to on step {i} does not exist: `{linked_command}`.",
)
return await ctx.send(embed=embed)
embed.description += f"\n{i}: {val}"
self.bot.aliases[name] = "&&".join(values)
await self.bot.config.update()
return await ctx.send(embed=embed)
@commands.group(aliases=["perms"], invoke_without_command=True)
@checks.has_permissions(PermissionLevel.OWNER)
async def permissions(self, ctx):
"""
Set the permissions for Modmail commands.
You may set permissions based on individual command names, or permission
levels.
Acceptable permission levels are:
- **Owner** [5] (absolute control over the bot)
- **Administrator** [4] (administrative powers such as setting activities)
- **Moderator** [3] (ability to block)
- **Supporter** [2] (access to core Modmail supporting functions)
- **Regular** [1] (most basic interactions such as help and about)
By default, owner is set to the absolute bot owner and regular is `@everyone`.
To set permissions, see `{prefix}help permissions add`; and to change permission level for specific
commands see `{prefix}help permissions override`.
Note: You will still have to manually give/take permission to the Modmail
category to users/roles.
"""
await ctx.send_help(ctx.command)
@staticmethod
def _verify_user_or_role(user_or_role):
if isinstance(user_or_role, Role):
if user_or_role.is_default():
return -1
elif user_or_role in {"everyone", "all"}:
return -1
if hasattr(user_or_role, "id"):
return user_or_role.id
raise commands.BadArgument(f'User or Role "{user_or_role}" not found')
@staticmethod
def _parse_level(name):
name = name.upper()
try:
return PermissionLevel[name]
except KeyError:
pass
transform = {
"1": PermissionLevel.REGULAR,
"2": PermissionLevel.SUPPORTER,
"3": PermissionLevel.MODERATOR,
"4": PermissionLevel.ADMINISTRATOR,
"5": PermissionLevel.OWNER,
}
return transform.get(name, PermissionLevel.INVALID)
@permissions.command(name="override")
@checks.has_permissions(PermissionLevel.OWNER)
async def permissions_override(
self, ctx, command_name: str.lower, *, level_name: str
):
"""
Change a permission level for a specific command.
Examples:
- `{prefix}perms override reply administrator`
- `{prefix}perms override "plugin enabled" moderator`
To undo a permission override, see `{prefix}help permissions remove`.
Example:
- `{prefix}perms remove override reply`
- `{prefix}perms remove override plugin enabled`
You can retrieve a single or all command level override(s), see`{prefix}help permissions get`.
"""
command = self.bot.get_command(command_name)
if command is None:
embed = Embed(
title="Error",
color=Color.red(),
description=f"The referenced command does not exist: `{command_name}`.",
)
return await ctx.send(embed=embed)
level = self._parse_level(level_name)
if level is PermissionLevel.INVALID:
embed = Embed(
title="Error",
color=Color.red(),
description=f"The referenced level does not exist: `{level_name}`.",
)
else:
logger.info(
"Updated command permission level for `%s` to `%s`.",
command.qualified_name,
level.name,
)
self.bot.config["override_command_level"][
command.qualified_name
] = level.name
await self.bot.config.update()
embed = Embed(
title="Success",
color=self.bot.main_color,
description="Successfully set command permission level for "
f"`{command.qualified_name}` to `{level.name}`.",
)
return await ctx.send(embed=embed)
@permissions.command(name="add", usage="[command/level] [name] [user/role]")
@checks.has_permissions(PermissionLevel.OWNER)
async def permissions_add(
self,
ctx,
type_: str.lower,
name: str,
*,
user_or_role: Union[Role, utils.User, str],
):
"""
Add a permission to a command or a permission level.
For sub commands, wrap the complete command name with quotes.
To find a list of permission levels, see `{prefix}help perms`.
Examples:
- `{prefix}perms add level REGULAR everyone`
- `{prefix}perms add command reply @user`
- `{prefix}perms add command "plugin enabled" @role`
- `{prefix}perms add command help 984301093849028`
Do not ping `@everyone` for granting permission to everyone, use "everyone" or "all" instead,
"""
if type_ not in {"command", "level"}:
return await ctx.send_help(ctx.command)
command = level = None
if type_ == "command":
name = name.lower()
command = self.bot.get_command(name)
check = command is not None
else:
level = self._parse_level(name)
check = level is not PermissionLevel.INVALID
if not check:
embed = Embed(
title="Error",
color=Color.red(),
description=f"The referenced {type_} does not exist: `{name}`.",
)
return await ctx.send(embed=embed)
value = self._verify_user_or_role(user_or_role)
if type_ == "command":
name = command.qualified_name
await self.bot.update_perms(name, value)
else:
await self.bot.update_perms(level, value)
name = level.name
if level > PermissionLevel.REGULAR:
if value == -1:
key = self.bot.modmail_guild.default_role
elif isinstance(user_or_role, Role):
key = user_or_role
else:
key = self.bot.modmail_guild.get_member(value)
if key is not None:
logger.info("Granting %s access to Modmail category.", key.name)
await self.bot.main_category.set_permissions(
key, read_messages=True
)
embed = Embed(
title="Success",
color=self.bot.main_color,
description=f"Permission for `{name}` was successfully updated.",
)
return await ctx.send(embed=embed)
@permissions.command(
name="remove",
aliases=["del", "delete", "revoke"],
usage="[command/level] [name] [user/role] or [override] [command name]",
)
@checks.has_permissions(PermissionLevel.OWNER)
async def permissions_remove(
self,
ctx,
type_: str.lower,
name: str,
*,
user_or_role: Union[Role, utils.User, str] = None,
):
"""
Remove permission to use a command, permission level, or command level override.
For sub commands, wrap the complete command name with quotes.
To find a list of permission levels, see `{prefix}help perms`.
Examples:
- `{prefix}perms remove level REGULAR everyone`
- `{prefix}perms remove command reply @user`
- `{prefix}perms remove command "plugin enabled" @role`
- `{prefix}perms remove command help 984301093849028`
- `{prefix}perms remove override block`
- `{prefix}perms remove override "snippet add"`
Do not ping `@everyone` for granting permission to everyone, use "everyone" or "all" instead,
"""
if type_ not in {"command", "level", "override"} or (
type_ != "override" and user_or_role is None
):
return await ctx.send_help(ctx.command)
if type_ == "override":
extension = ctx.kwargs["user_or_role"]
if extension is not None:
name += f" {extension}"
name = name.lower()
name = getattr(self.bot.get_command(name), "qualified_name", name)
level = self.bot.config["override_command_level"].get(name)
if level is None:
perm = self.bot.command_perm(name)
embed = Embed(
title="Error",
color=Color.red(),
description=f"The command permission level was never overridden: `{name}`, "
f"current permission level is {perm.name}.",
)
else:
logger.info("Restored command permission level for `%s`.", name)
self.bot.config["override_command_level"].pop(name)
await self.bot.config.update()
perm = self.bot.command_perm(name)
embed = Embed(
title="Success",
color=self.bot.main_color,
description=f"Command permission level for `{name}` was successfully restored to {perm.name}.",
)
return await ctx.send(embed=embed)
level = None
if type_ == "command":
name = name.lower()
name = getattr(self.bot.get_command(name), "qualified_name", name)
else:
level = self._parse_level(name)
if level is PermissionLevel.INVALID:
embed = Embed(
title="Error",
color=Color.red(),
description=f"The referenced level does not exist: `{name}`.",
)
return await ctx.send(embed=embed)
name = level.name
value = self._verify_user_or_role(user_or_role)
await self.bot.update_perms(level or name, value, add=False)
if type_ == "level":
if level > PermissionLevel.REGULAR:
if value == -1:
logger.info("Denying @everyone access to Modmail category.")
await self.bot.main_category.set_permissions(
self.bot.modmail_guild.default_role, read_messages=False
)
elif isinstance(user_or_role, Role):
logger.info(
"Denying %s access to Modmail category.", user_or_role.name
)
await self.bot.main_category.set_permissions(
user_or_role, overwrite=None
)
else:
member = self.bot.modmail_guild.get_member(value)
if member is not None and member != self.bot.modmail_guild.me:
logger.info(
"Denying %s access to Modmail category.", member.name
)
await self.bot.main_category.set_permissions(
member, overwrite=None
)
embed = Embed(
title="Success",
color=self.bot.main_color,
description=f"Permission for `{name}` was successfully updated.",
)
return await ctx.send(embed=embed)
def _get_perm(self, ctx, name, type_):
if type_ == "command":
permissions = self.bot.config["command_permissions"].get(name, [])
else:
permissions = self.bot.config["level_permissions"].get(name, [])
if not permissions:
embed = Embed(
title=f"Permission entries for {type_} `{name}`:",
description="No permission entries found.",
color=self.bot.main_color,
)
else:
values = []
for perm in permissions:
if perm == -1:
values.insert(0, "**everyone**")
continue
member = ctx.guild.get_member(perm)
if member is not None:
values.append(member.mention)
continue
user = self.bot.get_user(perm)
if user is not None:
values.append(user.mention)
continue
role = ctx.guild.get_role(perm)
if role is not None:
values.append(role.mention)
else:
values.append(str(perm))
embed = Embed(
title=f"Permission entries for {type_} `{name}`:",
description=", ".join(values),
color=self.bot.main_color,
)
return embed
@permissions.command(name="get", usage="[@user] or [command/level/override] [name]")
@checks.has_permissions(PermissionLevel.OWNER)
async def permissions_get(
self, ctx, user_or_role: Union[Role, utils.User, str], *, name: str = None
):
"""
View the currently-set permissions.
To find a list of permission levels, see `{prefix}help perms`.
To view all command and level permissions:
Examples:
- `{prefix}perms get @user`
- `{prefix}perms get 984301093849028`
To view all users and roles of a command or level permission:
Examples:
- `{prefix}perms get command reply`
- `{prefix}perms get command plugin remove`
- `{prefix}perms get level SUPPORTER`
To view command level overrides:
Examples:
- `{prefix}perms get override block`
- `{prefix}perms get override permissions add`
Do not ping `@everyone` for granting permission to everyone, use "everyone" or "all" instead,
"""
if name is None and user_or_role not in {"command", "level", "override"}:
value = self._verify_user_or_role(user_or_role)
cmds = []
levels = []
done = set()
for command in self.bot.walk_commands():
if command not in done:
done.add(command)
permissions = self.bot.config["command_permissions"].get(
command.qualified_name, []
)
if value in permissions:
cmds.append(command.qualified_name)
for level in PermissionLevel:
permissions = self.bot.config["level_permissions"].get(level.name, [])
if value in permissions:
levels.append(level.name)
mention = getattr(
user_or_role, "name", getattr(user_or_role, "id", user_or_role)
)
desc_cmd = (
", ".join(map(lambda x: f"`{x}`", cmds))
if cmds
else "No permission entries found."
)
desc_level = (
", ".join(map(lambda x: f"`{x}`", levels))
if levels
else "No permission entries found."
)
embeds = [
Embed(
title=f"{mention} has permission with the following commands:",
description=desc_cmd,
color=self.bot.main_color,
),
Embed(
title=f"{mention} has permission with the following permission levels:",
description=desc_level,
color=self.bot.main_color,
),
]
else:
user_or_role = (user_or_role or "").lower()
if user_or_role == "override":
if name is None:
done = set()
overrides = {}
for command in self.bot.walk_commands():
if command not in done:
done.add(command)
level = self.bot.config["override_command_level"].get(
command.qualified_name
)
if level is not None:
overrides[command.qualified_name] = level
embeds = []
if not overrides:
embeds.append(
Embed(
title="Permission Overrides",
description="You don't have any command level overrides at the moment.",
color=Color.red(),
)
)
else:
for items in zip_longest(
*(iter(sorted(overrides.items())),) * 15
):
description = "\n".join(
": ".join((f"`{name}`", level))
for name, level in takewhile(
lambda x: x is not None, items
)
)
embed = Embed(
color=self.bot.main_color, description=description
)
embed.set_author(
name="Permission Overrides", icon_url=ctx.guild.icon_url
)
embeds.append(embed)
session = EmbedPaginatorSession(ctx, *embeds)
return await session.run()
name = name.lower()
name = getattr(self.bot.get_command(name), "qualified_name", name)
level = self.bot.config["override_command_level"].get(name)
perm = self.bot.command_perm(name)
if level is None:
embed = Embed(
title="Error",
color=Color.red(),
description=f"The command permission level was never overridden: `{name}`, "
f"current permission level is {perm.name}.",
)
else:
embed = Embed(
title="Success",
color=self.bot.main_color,
description=f'Permission override for command "{name}" is "{perm.name}".',
)
return await ctx.send(embed=embed)
if user_or_role not in {"command", "level"}:
return await ctx.send_help(ctx.command)
embeds = []
if name is not None:
name = name.strip('"')
command = level = None
if user_or_role == "command":
name = name.lower()
command = self.bot.get_command(name)
check = command is not None
else:
level = self._parse_level(name)
check = level is not PermissionLevel.INVALID
if not check:
embed = Embed(
title="Error",
color=Color.red(),
description=f"The referenced {user_or_role} does not exist: `{name}`.",
)
return await ctx.send(embed=embed)
if user_or_role == "command":
embeds.append(
self._get_perm(ctx, command.qualified_name, "command")
)
else:
embeds.append(self._get_perm(ctx, level.name, "level"))
else:
if user_or_role == "command":
done = set()
for command in self.bot.walk_commands():
if command not in done:
done.add(command)
embeds.append(
self._get_perm(ctx, command.qualified_name, "command")
)
else:
for perm_level in PermissionLevel:
embeds.append(self._get_perm(ctx, perm_level.name, "level"))
session = EmbedPaginatorSession(ctx, *embeds)
return await session.run()
@commands.group(invoke_without_command=True)
@checks.has_permissions(PermissionLevel.OWNER)
async def oauth(self, ctx):
"""
Commands relating to logviewer oauth2 login authentication.
This functionality on your logviewer site is a [**Patron**](https://patreon.com/kyber) only feature.
"""
await ctx.send_help(ctx.command)
@oauth.command(name="whitelist")
@checks.has_permissions(PermissionLevel.OWNER)
async def oauth_whitelist(self, ctx, target: Union[Role, utils.User]):
"""
Whitelist or un-whitelist a user or role to have access to logs.
`target` may be a role ID, name, mention, user ID, name, or mention.
"""
whitelisted = self.bot.config["oauth_whitelist"]
# target.id is not int??
if target.id in whitelisted:
whitelisted.remove(target.id)
removed = True
else:
whitelisted.append(target.id)
removed = False
await self.bot.config.update()
embed = Embed(color=self.bot.main_color)
embed.title = "Success"
if not hasattr(target, "mention"):
target = self.bot.get_user(target.id) or self.bot.modmail_guild.get_role(
target.id
)
embed.description = (
f"{'Un-w' if removed else 'W'}hitelisted " f"{target.mention} to view logs."
)
await ctx.send(embed=embed)
@oauth.command(name="show", aliases=["get", "list", "view"])
@checks.has_permissions(PermissionLevel.OWNER)
async def oauth_show(self, ctx):
"""Shows a list of users and roles that are whitelisted to view logs."""
whitelisted = self.bot.config["oauth_whitelist"]
users = []
roles = []
for id_ in whitelisted:
user = self.bot.get_user(id_)
if user:
users.append(user)
role = self.bot.modmail_guild.get_role(id_)
if role:
roles.append(role)
embed = Embed(color=self.bot.main_color)
embed.title = "Oauth Whitelist"
embed.add_field(
name="Users", value=" ".join(u.mention for u in users) or "None"
)
embed.add_field(
name="Roles", value=" ".join(r.mention for r in roles) or "None"
)
await ctx.send(embed=embed)
@commands.command(hidden=True, name="eval")
@checks.has_permissions(PermissionLevel.OWNER)
async def eval_(self, ctx, *, body: str):
"""Evaluates Python code."""
env = {
"ctx": ctx,
"bot": self.bot,
"channel": ctx.channel,
"author": ctx.author,
"guild": ctx.guild,
"message": ctx.message,
"source": inspect.getsource,
"discord": __import__("discord"),
}
env.update(globals())
body = utils.cleanup_code(body)
stdout = StringIO()
to_compile = f'async def func():\n{indent(body, " ")}'
def paginate(text: str):
"""Simple generator that paginates text."""
last = 0
pages = []
appd_index = curr = None
for curr in range(0, len(text)):
if curr % 1980 == 0:
pages.append(text[last:curr])
last = curr
appd_index = curr
if appd_index != len(text) - 1:
pages.append(text[last:curr])
return list(filter(lambda a: a != "", pages))
try:
exec(to_compile, env) # pylint: disable=exec-used
except Exception as exc:
await ctx.send(f"```py\n{exc.__class__.__name__}: {exc}\n```")
return await ctx.message.add_reaction("\u2049")
func = env["func"]
try:
with redirect_stdout(stdout):
ret = await func()
except Exception:
value = stdout.getvalue()
await ctx.send(f"```py\n{value}{traceback.format_exc()}\n```")
return await ctx.message.add_reaction("\u2049")
else:
value = stdout.getvalue()
if ret is None:
if value:
try:
await ctx.send(f"```py\n{value}\n```")
except Exception:
paginated_text = paginate(value)
for page in paginated_text:
if page == paginated_text[-1]:
await ctx.send(f"```py\n{page}\n```")
break
await ctx.send(f"```py\n{page}\n```")
else:
try:
await ctx.send(f"```py\n{value}{ret}\n```")
except Exception:
paginated_text = paginate(f"{value}{ret}")
for page in paginated_text:
if page == paginated_text[-1]:
await ctx.send(f"```py\n{page}\n```")
break
await ctx.send(f"```py\n{page}\n```")
def setup(bot):
bot.add_cog(Utility(bot))
|
993,618 | 8073873a79495cde696926a4e503ec744052ce80 | # Generated by Django 3.0.3 on 2020-02-21 06:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('firstsiteapp', '0004_year_name'),
]
operations = [
migrations.RemoveField(
model_name='year',
name='update',
),
migrations.AlterField(
model_name='year',
name='year',
field=models.CharField(max_length=4, unique=True),
),
]
|
993,619 | 8709fd5908773f5e491bed752e38a75419527a7a | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Screen(object):
@property
def width(self):
return self._width
@width.setter
def width(self,value):
self._width = value
@property
def height(self):
return self._height
@height.setter
def height(self,value):
self._height = value
@property
def resolution(self):
return self._width * self._height
a = Screen()
a.width = 2
a.height = 3
print(a.resolution)
assert a.resolution == 786432, '1024 * 768 = %d ?' % a.resolution |
993,620 | 43bc4500b9bea33d1e722aaf88d1f01ac74c0ece | #!/usr/bin/env python3
import logging
import yaml
from pathlib import Path
from ops.charm import CharmBase
from ops.main import main
from ops.framework import StoredState
from ops.model import ActiveStatus, MaintenanceStatus
from jinja2 import Template
import os
from oci_image import OCIImageResource, OCIImageResourceError
logger = logging.getLogger(__name__)
class CustomResourceDefintion(object):
def __init__(self, name, spec):
self._name = name
self._spec = spec
@property
def spec(self):
return self._spec
@property
def name(self):
return self._name
class OPAAuditCharm(CharmBase):
"""
A Juju Charm for OPA
"""
_stored = StoredState()
def __init__(self, *args):
super().__init__(*args)
self.framework.observe(self.on.config_changed, self._on_config_changed)
self.framework.observe(self.on.stop, self._on_stop)
self.framework.observe(self.on.install, self._on_install)
self._stored.set_default(things=[])
self.image = OCIImageResource(self, "gatekeeper-image")
def _on_config_changed(self, _):
"""
Set a new Juju pod specification
"""
self._configure_pod()
def _on_stop(self, _):
"""
Mark unit is inactive
"""
self.unit.status = MaintenanceStatus("Pod is terminating.")
logger.info("Pod is terminating.")
def _on_install(self, event):
logger.info("Congratulations, the charm was properly installed!")
def _build_pod_spec(self):
"""
Construct a Juju pod specification for OPA
"""
logger.debug("Building Pod Spec")
crds = []
try:
crds = [
yaml.load(Path(f).read_text())
for f in [
"files/configs.config.gatekeeper.sh.yaml",
"files/constrainttemplates.templates.gatekeeper.sh.yaml",
"files/constraintpodstatuses.status.gatekeeper.sh.yaml",
"files/constrainttemplatepodstatuses.status.gatekeeper.sh.yaml",
]
]
except yaml.YAMLError as exc:
logger.error("Error in configuration file:", exc)
crd_objects = [
CustomResourceDefintion(crd["metadata"]["name"], crd["spec"])
for crd in crds
]
config = self.model.config
spec_template = {}
with open("files/pod-spec.yaml.jinja2") as fh:
spec_template = Template(fh.read())
try:
image_details = self.image.fetch()
except OCIImageResourceError as e:
self.model.unit.status = e.status
return
template_args = {
"crds": crd_objects,
"image_details": image_details,
"imagePullPolicy": config["imagePullPolicy"],
"app_name": self.app.name,
"audit_cli_args": self._audit_cli_args(),
"namespace": os.environ["JUJU_MODEL_NAME"],
}
spec = yaml.load(spec_template.render(**template_args))
print(f"Pod spec: {spec}")
return spec
def _audit_cli_args(self):
"""
Construct command line arguments for OPA Audit
"""
args = [
"--operation=audit",
"--operation=status",
"--logtostderr",
]
return args
def _configure_pod(self):
"""
Setup a new opa pod specification
"""
logger.debug("Configuring Pod")
if not self.unit.is_leader():
self.unit.status = ActiveStatus()
return
self.unit.status = MaintenanceStatus("Setting pod spec.")
pod_spec = self._build_pod_spec()
self.model.pod.set_spec(pod_spec)
self.unit.status = ActiveStatus()
if __name__ == "__main__":
main(OPAAuditCharm)
|
993,621 | f0f0a264a4ab96277422f610591626d5f61b8f43 | class Diffstat(object):
def __init__(self):
self.lines_added = 0
self.lines_deleted = 0
self.filename = '' |
993,622 | 4d8fd957759e0f597eb30b56abed13e7a625ad26 | import hashlib
import itertools
import logging
import time
from functools import reduce
from operator import or_
from flask import current_app as app
from flask import request_started, url_for
from flask_login import AnonymousUserMixin, UserMixin, current_user
from passlib.apps import custom_app_context as pwd_context
from sqlalchemy.dialects import postgresql
from sqlalchemy_utils import EmailType
from sqlalchemy_utils.models import generic_repr
from redash import redis_connection
from redash.utils import dt_from_timestamp, generate_token
from .base import Column, GFKBase, db, key_type, primary_key
from .mixins import BelongsToOrgMixin, TimestampMixin
from .types import MutableDict, MutableList, json_cast_property
logger = logging.getLogger(__name__)
LAST_ACTIVE_KEY = "users:last_active_at"
def sync_last_active_at():
"""
Update User model with the active_at timestamp from Redis. We first fetch
all the user_ids to update, and then fetch the timestamp to minimize the
time between fetching the value and updating the DB. This is because there
might be a more recent update we skip otherwise.
"""
user_ids = redis_connection.hkeys(LAST_ACTIVE_KEY)
for user_id in user_ids:
timestamp = redis_connection.hget(LAST_ACTIVE_KEY, user_id)
active_at = dt_from_timestamp(timestamp)
user = User.query.filter(User.id == user_id).first()
if user:
user.active_at = active_at
redis_connection.hdel(LAST_ACTIVE_KEY, user_id)
db.session.commit()
def update_user_active_at(sender, *args, **kwargs):
"""
Used as a Flask request_started signal callback that adds
the current user's details to Redis
"""
if current_user.is_authenticated and not current_user.is_api_user():
redis_connection.hset(LAST_ACTIVE_KEY, current_user.id, int(time.time()))
def init_app(app):
"""
A Flask extension to keep user details updates in Redis and
sync it periodically to the database (User.details).
"""
request_started.connect(update_user_active_at, app)
class PermissionsCheckMixin(object):
def has_permission(self, permission):
return self.has_permissions((permission,))
def has_permissions(self, permissions):
has_permissions = reduce(
lambda a, b: a and b,
[permission in self.permissions for permission in permissions],
True,
)
return has_permissions
@generic_repr("id", "name", "email")
class User(TimestampMixin, db.Model, BelongsToOrgMixin, UserMixin, PermissionsCheckMixin):
id = primary_key("User")
org_id = Column(key_type("Organization"), db.ForeignKey("organizations.id"))
org = db.relationship("Organization", backref=db.backref("users", lazy="dynamic"))
name = Column(db.String(320))
email = Column(EmailType)
password_hash = Column(db.String(128), nullable=True)
group_ids = Column(
"groups",
MutableList.as_mutable(postgresql.ARRAY(key_type("Group"))),
nullable=True,
)
api_key = Column(db.String(40), default=lambda: generate_token(40), unique=True)
disabled_at = Column(db.DateTime(True), default=None, nullable=True)
details = Column(
MutableDict.as_mutable(postgresql.JSONB),
nullable=True,
server_default="{}",
default={},
)
active_at = json_cast_property(db.DateTime(True), "details", "active_at", default=None)
_profile_image_url = json_cast_property(db.Text(), "details", "profile_image_url", default=None)
is_invitation_pending = json_cast_property(db.Boolean(True), "details", "is_invitation_pending", default=False)
is_email_verified = json_cast_property(db.Boolean(True), "details", "is_email_verified", default=True)
__tablename__ = "users"
__table_args__ = (db.Index("users_org_id_email", "org_id", "email", unique=True),)
def __str__(self):
return "%s (%s)" % (self.name, self.email)
def __init__(self, *args, **kwargs):
if kwargs.get("email") is not None:
kwargs["email"] = kwargs["email"].lower()
super(User, self).__init__(*args, **kwargs)
@property
def is_disabled(self):
return self.disabled_at is not None
def disable(self):
self.disabled_at = db.func.now()
def enable(self):
self.disabled_at = None
def regenerate_api_key(self):
self.api_key = generate_token(40)
def to_dict(self, with_api_key=False):
profile_image_url = self.profile_image_url
if self.is_disabled:
assets = app.extensions["webpack"]["assets"] or {}
path = "images/avatar.svg"
profile_image_url = url_for("static", filename=assets.get(path, path))
d = {
"id": self.id,
"name": self.name,
"email": self.email,
"profile_image_url": profile_image_url,
"groups": self.group_ids,
"updated_at": self.updated_at,
"created_at": self.created_at,
"disabled_at": self.disabled_at,
"is_disabled": self.is_disabled,
"active_at": self.active_at,
"is_invitation_pending": self.is_invitation_pending,
"is_email_verified": self.is_email_verified,
}
if self.password_hash is None:
d["auth_type"] = "external"
else:
d["auth_type"] = "password"
if with_api_key:
d["api_key"] = self.api_key
return d
def is_api_user(self):
return False
@property
def profile_image_url(self):
if self._profile_image_url:
return self._profile_image_url
email_md5 = hashlib.md5(self.email.lower().encode()).hexdigest()
return "https://www.gravatar.com/avatar/{}?s=40&d=identicon".format(email_md5)
@property
def permissions(self):
# TODO: this should be cached.
return list(itertools.chain(*[g.permissions for g in Group.query.filter(Group.id.in_(self.group_ids))]))
@classmethod
def get_by_org(cls, org):
return cls.query.filter(cls.org == org)
@classmethod
def get_by_id(cls, _id):
return cls.query.filter(cls.id == _id).one()
@classmethod
def get_by_email_and_org(cls, email, org):
return cls.get_by_org(org).filter(cls.email == email).one()
@classmethod
def get_by_api_key_and_org(cls, api_key, org):
return cls.get_by_org(org).filter(cls.api_key == api_key).one()
@classmethod
def all(cls, org):
return cls.get_by_org(org).filter(cls.disabled_at.is_(None))
@classmethod
def all_disabled(cls, org):
return cls.get_by_org(org).filter(cls.disabled_at.isnot(None))
@classmethod
def search(cls, base_query, term):
term = "%{}%".format(term)
search_filter = or_(cls.name.ilike(term), cls.email.like(term))
return base_query.filter(search_filter)
@classmethod
def pending(cls, base_query, pending):
if pending:
return base_query.filter(cls.is_invitation_pending.is_(True))
else:
return base_query.filter(cls.is_invitation_pending.isnot(True)) # check for both `false`/`null`
@classmethod
def find_by_email(cls, email):
return cls.query.filter(cls.email == email)
def hash_password(self, password):
self.password_hash = pwd_context.hash(password)
def verify_password(self, password):
return self.password_hash and pwd_context.verify(password, self.password_hash)
def update_group_assignments(self, group_names):
groups = Group.find_by_name(self.org, group_names)
groups.append(self.org.default_group)
self.group_ids = [g.id for g in groups]
db.session.add(self)
db.session.commit()
def has_access(self, obj, access_type):
return AccessPermission.exists(obj, access_type, grantee=self)
def get_id(self):
identity = hashlib.md5("{},{}".format(self.email, self.password_hash).encode()).hexdigest()
return "{0}-{1}".format(self.id, identity)
def get_actual_user(self):
return repr(self) if self.is_api_user() else self.email
@generic_repr("id", "name", "type", "org_id")
class Group(db.Model, BelongsToOrgMixin):
DEFAULT_PERMISSIONS = [
"create_dashboard",
"create_query",
"edit_dashboard",
"edit_query",
"view_query",
"view_source",
"execute_query",
"list_users",
"schedule_query",
"list_dashboards",
"list_alerts",
"list_data_sources",
]
ADMIN_PERMISSIONS = ["admin", "super_admin"]
BUILTIN_GROUP = "builtin"
REGULAR_GROUP = "regular"
id = primary_key("Group")
data_sources = db.relationship("DataSourceGroup", back_populates="group", cascade="all")
org_id = Column(key_type("Organization"), db.ForeignKey("organizations.id"))
org = db.relationship("Organization", back_populates="groups")
type = Column(db.String(255), default=REGULAR_GROUP)
name = Column(db.String(100))
permissions = Column(postgresql.ARRAY(db.String(255)), default=DEFAULT_PERMISSIONS)
created_at = Column(db.DateTime(True), default=db.func.now())
__tablename__ = "groups"
def __str__(self):
return str(self.id)
def to_dict(self):
return {
"id": self.id,
"name": self.name,
"permissions": self.permissions,
"type": self.type,
"created_at": self.created_at,
}
@classmethod
def all(cls, org):
return cls.query.filter(cls.org == org)
@classmethod
def members(cls, group_id):
return User.query.filter(User.group_ids.any(group_id))
@classmethod
def find_by_name(cls, org, group_names):
result = cls.query.filter(cls.org == org, cls.name.in_(group_names))
return list(result)
@generic_repr("id", "object_type", "object_id", "access_type", "grantor_id", "grantee_id")
class AccessPermission(GFKBase, db.Model):
id = primary_key("AccessPermission")
# 'object' defined in GFKBase
access_type = Column(db.String(255))
grantor_id = Column(key_type("User"), db.ForeignKey("users.id"))
grantor = db.relationship(User, backref="grantor", foreign_keys=[grantor_id])
grantee_id = Column(key_type("User"), db.ForeignKey("users.id"))
grantee = db.relationship(User, backref="grantee", foreign_keys=[grantee_id])
__tablename__ = "access_permissions"
@classmethod
def grant(cls, obj, access_type, grantee, grantor):
grant = cls.query.filter(
cls.object_type == obj.__tablename__,
cls.object_id == obj.id,
cls.access_type == access_type,
cls.grantee == grantee,
cls.grantor == grantor,
).one_or_none()
if not grant:
grant = cls(
object_type=obj.__tablename__,
object_id=obj.id,
access_type=access_type,
grantee=grantee,
grantor=grantor,
)
db.session.add(grant)
return grant
@classmethod
def revoke(cls, obj, grantee, access_type=None):
permissions = cls._query(obj, access_type, grantee)
return permissions.delete()
@classmethod
def find(cls, obj, access_type=None, grantee=None, grantor=None):
return cls._query(obj, access_type, grantee, grantor)
@classmethod
def exists(cls, obj, access_type, grantee):
return cls.find(obj, access_type, grantee).count() > 0
@classmethod
def _query(cls, obj, access_type=None, grantee=None, grantor=None):
q = cls.query.filter(cls.object_id == obj.id, cls.object_type == obj.__tablename__)
if access_type:
q = q.filter(AccessPermission.access_type == access_type)
if grantee:
q = q.filter(AccessPermission.grantee == grantee)
if grantor:
q = q.filter(AccessPermission.grantor == grantor)
return q
def to_dict(self):
d = {
"id": self.id,
"object_id": self.object_id,
"object_type": self.object_type,
"access_type": self.access_type,
"grantor": self.grantor_id,
"grantee": self.grantee_id,
}
return d
class AnonymousUser(AnonymousUserMixin, PermissionsCheckMixin):
@property
def permissions(self):
return []
def is_api_user(self):
return False
class ApiUser(UserMixin, PermissionsCheckMixin):
def __init__(self, api_key, org, groups, name=None):
self.object = None
if isinstance(api_key, str):
self.id = api_key
self.name = name
else:
self.id = api_key.api_key
self.name = "ApiKey: {}".format(api_key.id)
self.object = api_key.object
self.group_ids = groups
self.org = org
def __repr__(self):
return "<{}>".format(self.name)
def is_api_user(self):
return True
@property
def org_id(self):
if not self.org:
return None
return self.org.id
@property
def permissions(self):
return ["view_query"]
def has_access(self, obj, access_type):
return False
|
993,623 | ad4fe739103382994d7dbed7889abd8eaccfa619 | import pandas as pd
from random import randint
def get_random_bipartite(n_edges=10000000, n_a=10000, n_b=10000):
return pd.DataFrame([(f"a{randint(0, n_a)}", f"b{randint(0, n_b)}") for x in range(n_edges)], columns=["A_id", "B_id"]) |
993,624 | ab7c2ed09aeb2d96a0f83e253010bd742a71513e | from aocd import get_data
content = get_data(day=4, year=2018)
numGuards = content.count("Guard")
content = content.split("\n")
content.sort()
schedule = [[["a"],["0" for i in range(60)]] for j in range(numGuards)]
currentGuard = 0
currentSpot = -1
startTime = 0
for i in range(0,len(content)):
line = content[i]
if "Guard" in line:
currentSpot += 1
b1 = line.index("b")
currentGuard = int(line[26:b1-1])
schedule[currentSpot][0] = currentGuard
startTime = int(line[15:17])
for j in range(startTime,60):
schedule[currentSpot][1][j] = "1"
if "wakes" in line:
startTime = int(line[15:17])
for j in range(startTime,60):
schedule[currentSpot][1][j] = "1"
if "falls" in line:
startTime = int(line[15:17])
for j in range(startTime,60):
schedule[currentSpot][1][j] = "X"
def part1():
count = []
for i in schedule:
if i[0] in [j[0] for j in count]:
num = count[[j[0] for j in count].index(i[0])][1]
num += i[1].count("X")
count[[j[0] for j in count].index(i[0])][1] = num
else:
num = i[1].count("X")
count.append([i[0],num])
maxSleep = max([i[1] for i in count])
maxId = count[[i[1] for i in count].index(maxSleep)][0]
sleepiestMin = (-1,-1)
for i in range(0,60):
miniSum = 0
for j in schedule:
if j[0] == maxId and j[1][i] == 'X':
miniSum += 1
if miniSum > sleepiestMin[1]:
sleepiestMin = (i,miniSum)
return sleepiestMin[0]*maxId
def part2():
elf_list = []
for i in schedule:
if not i[0] in elf_list:
elf_list.append(i[0])
# Schedule in the format of [[elfId],[0] * 60] * number of elves
sleepiestElf = (0, 0, 0)
for elf in elf_list:
sleepiestMin = (-1,-1)
for j in range(0,60):
miniSum = 0
for k in schedule:
if k[0] == elf and k[1][j] == 'X':
miniSum += 1
if miniSum > sleepiestMin[1]:
sleepiestMin = (j,miniSum)
if sleepiestMin[1] > sleepiestElf[1]:
sleepiestElf = (elf, sleepiestMin[1],sleepiestMin[0])
return sleepiestElf[0] * sleepiestElf[2]
print(part1())
print(part2()) |
993,625 | 2ee5ade35d56433370e3d43ffd68b153fac1a86c | from ..java_class_def import JavaClassDef
from ..java_field_def import JavaFieldDef
from ..java_method_def import java_method_def, JavaMethodDef
class File(metaclass=JavaClassDef, jvm_name='java/io/File'):
def __init__(self, path):
self.__path = path
#
@java_method_def(name='getPath', signature='()Ljava/lang/String;', native=False)
def getPath(self, emu):
return self.__path
#
#
|
993,626 | e549cb21a02c16017d5db430e579355a7d57176a | from collections import defaultdict
names = 'bob julian tim martin rod sara joyce nick beverly kevin'.split()
ids = range(len(names))
users = dict(zip(ids, names)) # 0: bob, 1: julian, etc
friendships = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3),
(3, 4), (4, 5), (5, 6), (5, 7), (5, 9),
(6, 8), (7, 8), (8, 9)]
def get_friend_with_most_friends(friendships, users=users):
"""Receives the friendships list of user ID pairs,
parse it to see who has most friends, return a tuple
of (name_friend_with_most_friends, his_or_her_friends)"""
user_friends = defaultdict(set)
for u, f in friendships:
user_friends[u].add(f)
user_friends[f].add(u)
res = sorted(user_friends.items(), key=lambda x: -len(x[1]))
return users[res[0][0]], [users[id] for id in res[0][1]]
|
993,627 | a335f7cb8da78ddcf79d0b037399a66f51813b90 | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 30 22:22:33 2015
@author: thoma
"""
import numpy as np
from sklearn.cross_validation import train_test_split
from sklearn.datasets import load_digits
from random import sample
from sklearn.ensemble import BaggingClassifier, RandomForestClassifier
from scipy.stats import mode
from sklearn.preprocessing import Imputer
digits = load_digits()
print(digits.data.shape)
test_percentage = 0.5
f_t, f_v, c_t, c_v = train_test_split(digits.data, digits.target, test_size=test_percentage)
nan_prob_t = 0.0
nan_mask_t = np.random.binomial(n=1, p=nan_prob_t, size=np.shape(f_t))
nan_f_t = f_t
nan_f_t[nan_mask_t==1] = np.nan
nan_prob_v = 0.0
nan_mask_v = np.random.binomial(n=1, p=nan_prob_v, size=np.shape(f_v))
nan_f_v = f_v
nan_f_v[nan_mask_v == 1] = np.nan
class HalfRF:
def __init__(self, data, classes, tree_features, n_trees=100):
self.n_features = np.shape(data)[1]
n_rows = np.shape(data)[0]
n_nans = np.sum(np.isnan(data), 0)
data = data[:, n_nans < n_rows]
self.n_features = np.shape(data)[1]
n_nans = np.sum(np.isnan(data), 1)
data = data[n_nans < self.n_features, :]
self.n_rows = np.shape(data)[0]
if (tree_features > self.n_features):
tree_features = self.n_features
self.col_list = np.zeros((n_trees, tree_features), dtype='int')
self.n_trees = n_trees
self.bags = []
for i in range(n_trees):
cols = sample(range(self.n_features), tree_features)
cols.sort()
self.col_list[i, :] = cols
data_temp = data[:, cols]
n_nans = np.sum(np.isnan(data_temp), 1)
data_temp = data_temp[n_nans == 0, :]
classes_temp = classes[n_nans == 0]
#bag = BaggingClassifier(n_estimators=1, max_features=tree_features)
bag = RandomForestClassifier(n_estimators=1, max_features=tree_features)
bag.fit(data_temp, classes_temp)
self.bags.append(bag)
print(np.shape(data_temp))
def classify(self, data):
nan_cols = np.arange(self.n_features)[np.isnan(data)]
decisions = []
s1 = set(nan_cols)
for i in range(self.n_trees):
cols = self.col_list[i]
s2 = set(cols)
if len(s1.intersection(s2)) > 0:
#decisions[i] = -1
continue
decisions.append(self.bags[i].predict(data[cols]))
if (len(decisions) == 0):
return (-1, 0, 0)
return (mode(decisions)[0][0][0], mode(decisions)[1][0][0], len(decisions))
imp = Imputer(missing_values='NaN', strategy='mean', axis=0)
imp.fit(f_t)
imp_f_t = imp.transform(f_t)
imp_f_v = imp.transform(f_v)
n_trees = 300
tree_features = 64
clf = HalfRF(imp_f_t, c_t, tree_features, n_trees)
n_validation = np.shape(f_v)[0]
results = np.zeros((n_validation, 3))
for i in range(n_validation):
v_item = imp_f_v[i, :]
(prediction, votes, total_votes) = clf.classify(v_item)
results[i, :] = (prediction, votes, total_votes)
#print("%f/%f" % (prediction, c_v[i]))
print(1.0* sum(results[:, 0] == c_v)/n_validation)
print(sum(results[:, 2] == 0))
print(np.mean(results[:, 2]))
imp_clf = RandomForestClassifier(n_trees, max_features=tree_features)
imp_clf.fit(imp_f_t, c_t)
imp_prediction = imp_clf.predict(imp_f_v)
print(1.0*sum(imp_prediction == c_v)/n_validation)
print("Hello World") |
993,628 | c98810eca094f8231ca523394fafa2390ac6b15a | import sys
sys.exi
|
993,629 | 47ce23087190686739ac9b3c5e7b7fb5e57be9db | """ Command-line tool for use with Strom services.
User is able to upload and register a local template file, and retrieve a unique stream token back for that template.
Allows uploading of local data files for event recognition.
Can return event object containing all found events in given data file.
"""
import click
import requests
import json
import os
import datetime
try:
from pyfiglet import Figlet
except:
pass
__version__ = '0.1.0'
__author__ = 'Adrian Agnic <adrian@tura.io>'
def _print_ver(ctx, param, value):
""" (private method) Print current CLI version. """
if not value or ctx.resilient_parsing:
return
click.secho(__version__, fg='yellow')
ctx.exit()
def _abort_if_false(ctx, param, value):
""" (private method) Abort command if not confirmed. """
if not value:
ctx.abort()
def _convert_to_utc(date_string):
""" (private method) Expected input: YYYY-MM-DD-HH:MM:SS.
Conversion of standard date format to UTC.
:param date_string: string of date in format: YYYY-MM-DD-HH:MM:SS
:type date_string: string
"""
big_time_tmp = date_string.split("-")
year = int(big_time_tmp[0])
month = int(big_time_tmp[1])
day = int(big_time_tmp[2])
time_arr = big_time_tmp[3].split(":")
hours = int(time_arr[0])
minutes = int(time_arr[1])
seconds = int(time_arr[2])
dt = datetime.datetime(year, month, day, hours, minutes, seconds)
return dt.timestamp()
def _api_POST(config, function, data_dict):
""" (private method) Takes name of endpoint and dict of data to post.
:param function: endpoint of where to post data (eg. define or load)
:type function: string
:param data_dict: dictionary containing data description and data (eg. '{'template': data file }')
:type data_dict: dictionary
"""
if config.verbose:
click.secho("\nPOSTing to /{}".format(function), fg='white')
try:
ret = requests.post(config.url + "/api/{}".format(function), data=data_dict)
except:
click.secho("\nConnection Refused!...\n", fg='red', reverse=True)
if config.verbose:
click.secho("Server connection was denied. Check your internet connections and try again. Otherwise contact support.", fg='cyan')
else:
click.secho(str(ret.status_code), fg='yellow')
click.secho(ret.text, fg='yellow')
return [ret.status_code, ret.text]
def _api_GET(config, function, param, value, token):
""" Takes name of endpoint, time/range and its value, as well as token.
:param function: endpoint of where to get data (eg. raw or all)
:type function: string
:param param: indicate whether to collect from singular time or range of time.
:type param: string
:param value: UTC formatted timestamp
:type value: integer
:param token: unique token from template registration.
:type token: string
"""
if config.verbose:
click.secho("\nGETing {}={} from {} with {}".format(param, value, function, token), fg='white')
try:
ret = requests.get(config.url + "/api/get/{}?".format(function) + "{}={}".format(param, value) + "&token={}".format(token))
except:
click.secho("\nConnection Refused!...\n", fg='red', reverse=True)
if config.verbose:
click.secho("Server connection was denied. Check your internet connections and try again. Otherwise contact support.", fg='cyan')
else:
click.secho(str(ret.status_code), fg='yellow')
click.secho(ret.text, fg='yellow')
return [ret.status_code, ret.text]
def _collect_token(config, cert):
""" Load json-formatted input and return stream_token, if found.
:param cert: registered template file with stream token field.
:type cert: JSON-formatted string
"""
try:
json_cert = json.loads(cert)
except:
click.secho("There was an error accessing/parsing those files!...\n", fg='red', reverse=True)
if config.verbose:
click.secho("The file you uploaded must be compatible with a JSON parser. Please revise and try again.", fg='cyan')
else:
if config.verbose:
click.secho("Searching for token...", fg='white')
try:
token = json_cert["stream_token"]
if token is None:
raise ValueError
except:
click.secho("Token not found in provided template!...\n", fg='red', reverse=True)
if config.verbose:
click.secho("Make sure your using the template file generated from 'dstream define'!", fg='cyan')
else:
if config.verbose:
click.secho("Found stream_token: " + token + '\n', fg='white')
return token
def _check_options(config, function, time, utc, a, token):
""" Check options given for GET methods before send.
:param function: endpoint of where to get data (eg. raw or all)
:type function: string
:param time: date-formatted string
:type time: string
:param utc: UTC-formatted string
:type utc: string
:param a: flag designating retrievel of all events found.
:type a: boolean
:param token: unique token from registered template file
:type token: string
"""
if a:
result = _api_GET(config, "{}".format(function), "range", "ALL", token)
elif utc:
if len(utc) == 1:
result = _api_GET(config, "{}".format(function), "time", utc[0], token)
elif len(utc) == 2:
result = _api_GET(config, "{}".format(function), "range", utc, token)
else:
click.secho("Too many arguments given!({})...".format(len(utc)), fg='red', reverse=True)
elif time:
if len(time) == 1:
utime = _convert_to_utc(time[0])
result = _api_GET(config, "{}".format(function), "time", utime, token)
elif len(time) == 2:
utime_zero = _convert_to_utc(time[0])
utime_one = _convert_to_utc(time[1])
utime = [utime_zero, utime_one]
result = _api_GET(config, "{}".format(function), "range", utime, token)
else:
click.secho("Too many arguments given!({})...".format(len(time)), fg='red', reverse=True)
else:
click.secho("No options given, try '--all'...", fg='cyan')
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class CLIConfig(object):
""" Configuration class for storing options given to CLI, such as verbosity and temporary single-token storage. """
def __init__(self, verbose, store):
self.verbose = verbose
self.token = None
self.url = 'http://127.0.0.1:5000'
self.store = store
def _set_token(self):
""" If -store option is given, CLI locally saves token in hidden file for future easy retrieval. """
f = open(".cli_token")
data = f.read()
if data is not None:
self.token = data
return self.token
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@click.group()
@click.option('-verbose', '-v', 'verbose', is_flag=True, help="Enables verbose mode")
@click.option('-store', '-S', 'store', is_flag=True, help="(SHORTCUT) Don't use if defining multiple templates. Allows omission of '-token'")
@click.option('--version', is_flag=True, callback=_print_ver, is_eager=True, expose_value=False, help="Current version")
@click.pass_context
def dstream(ctx, verbose, store):
""" Entry-point. Parent command for all DStream methods.
:param verbose: verbosity flag
:type verbose: boolean
:param store: token storage flag
:type store: boolean
"""
ctx.obj = CLIConfig(verbose, store)
@click.command()
def welcome():
""" Usage instructions for first time users. """
try:
f = Figlet(font='slant')
click.secho(f.renderText("Strom-C.L.I.\n"), fg='cyan')
except:
click.secho("USAGE INSTRUCTIONS:\n", fg='cyan', underline=True)
click.secho("1. dstream define -template [template filepath]\n", fg='green')
click.secho("2. dstream load -filepath [data filepath] -token [template token file]\n", fg='green')
click.secho("3. dstream events --all -token [template token file]\n", fg='green')
click.pause()
else:
click.secho("USAGE INSTRUCTIONS:\n", fg='cyan', underline=True)
click.secho("1. dstream define -template [template filepath]\n", fg='green')
click.secho("2. dstream load -filepath [data filepath] -token [template token file]\n", fg='green')
click.secho("3. dstream events --all -token [template token file]\n", fg='green')
click.pause()
@click.command()
@click.option('-template', '-t', 'template', prompt=True, type=click.File('r'), help="Template file with required and custom fields")
@click.option('--y', is_flag=True, callback=_abort_if_false, expose_value=False, prompt="\nInitialize new DStream with this template?", help="Bypass confirmation prompt")
@click.pass_obj
def define(config, template):
""" Upload template file for DStream.
:param template: template file to register
:type template: JSON-formatted string
"""
template_data = template.read()
#Try send template to server, if success...collect stream_token
result = _api_POST(config, "define", {'template':template_data})
if result:
if result[0] == 200:
token = result[1]
else:
click.secho("\nServer Error!...\n", fg='red', reverse=True)
if config.verbose:
click.secho("Server connection was denied. Check your internet connections and try again. Otherwise contact support.", fg='cyan')
#Try load template as json and set stream_token field, if success...store tokenized template in new file
try:
json_template = json.loads(template_data)
json_template['stream_token'] = token
template_filename = os.path.basename(template.name)
path_list = template_filename.split('.')
template_name = path_list[0]
template_ext = path_list[1]
if config.verbose:
click.secho("File Extension found: {}".format(template_ext), fg='white')
except:
click.secho("\nProblem parsing template file!...\n", fg='red', reverse=True)
if config.verbose:
click.secho("The template file provided was not formatted correctly, please follow JSON templating guidelines.", fg='cyan')
else:
if config.verbose:
click.secho("\nTemplate has been tokenized with...{}".format(json_template['stream_token']), fg='white')
template_file = open("{}_token.txt".format(template_name), "w")
template_file.write(json.dumps(json_template))
template_file.close()
if config.store:
cli_templ = open(".cli_token", "w")
cli_templ.write(token)
cli_templ.close()
click.secho("New template stored locally as '{}_token.txt'.\n".format(template_name), fg='yellow')
@click.command()
@click.option('-source', '-s', 'source', prompt=True, type=click.Choice(['kafka', 'file']), help="Specify source of data")
@click.option('--kafka-topic', default=None, help="If source is kafka, specify topic")
@click.option('-token', '-tk', 'token', default=None, type=click.File('r'), help="Tokenized template file for verification")
@click.pass_obj
def add_source(config, source, kafka_topic, token):
""" Declare source of data: file upload or kafka stream.
:param source: designate the source of this data, be it kafka stream of a local file
:type source: string
:param kafka_topic: string of the kafka topic to listen to
:type kafka_topic: string
:param token: unique token from registered template file
:type token: string
"""
#Check if topic was supplied when source is kafka
if source == 'kafka' and kafka_topic == None:
click.secho("No topic specified, please re-run command.", fg='red', reverse=True)
else:
if config.store:
tk = config._set_token()
else:
try:
cert = token.read()
except:
click.secho("Please provide a tokenized template.", fg='red', reverse=True)
tk = None
else:
#Try loading template as json and retrieving token, if success...pass
tk = _collect_token(config, cert)
if tk:
if config.verbose:
click.secho("\nSending source for this DStream...\n", fg='white')
#Try posting data to server, if success...return status_code
result = _api_POST(config, "add-source", {'source':source, 'topic':kafka_topic, 'token':tk})
@click.command()
@click.option('-filepath', '-f', 'filepath', prompt=True, type=click.Path(exists=True), help="File-path of data file to upload")
@click.option('-token', '-tk', 'token', default=None, type=click.File('r'), help="Tokenized template file for verification")
@click.pass_obj
def load(config, filepath, token):
""" Provide file-path of data to upload, along with tokenized_template for this DStream.
:param filepath: filepath of local data file to upload
:type filepath: string
:param token: unique token from registered template file
:type token: string
"""
if config.verbose:
click.secho("\nTokenizing data fields of {}".format(click.format_filename(filepath)), fg='white')
if not config.store:
try:
cert = token.read()
except:
click.secho("Please provide a tokenized template.", fg='red', reverse=True)
cert = None
#Try load client files as json, if success...pass
try:
json_data = json.load(open(filepath))
except:
click.secho("There was an error accessing/parsing those files!...\n", fg='red', reverse=True)
if config.verbose:
click.secho("Data files are required to be JSON-formatted. Please supply the correct format.", fg='cyan')
else:
if config.store:
tk = config._set_token()
else:
if cert:
#Try collect stream_token, if success...pass
tk = _collect_token(config, cert)
#Try set stream_token fields to collected token, if success...pass
try:
with click.progressbar(json_data) as bar:
for obj in bar:
obj['stream_token'] = tk
except:
click.secho("Data file not correctly formatted!...\n", fg='red', reverse=True)
if config.verbose:
click.secho("Not able to set stream token fields in your data. Please supply JSON-formatted data.", fg='cyan')
else:
if config.verbose:
click.secho("\nSending data...", fg='white')
#Try send data with token to server, if success...return status_code
result = _api_POST(config, "load", {'stream_data':json.dumps(json_data)})
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@click.command()
@click.option('-datetime', '-d', 'time', type=str, multiple=True, help="Datetime to collect from (YYYY-MM-DD-HH:MM:SS)")
@click.option('-utc', type=str, multiple=True, help="UTC-formatted time to collect from")
@click.option('--all', '--a', 'a', is_flag=True, is_eager=True, help="Collect all data")
@click.option('-token', '-tk', 'tk', default=None, type=click.File('r'), help="Tokenized template file for verification")
@click.pass_obj
def raw(config, time, utc, a, tk):
"""
\b
Collect all raw data for specified datetime or time-range*.
*Options can be supplied twice to indicate a range.
:param time: date-time formatted string
:type time: string
:param utc: UTC-formatted string
:type utc: string
:param a: flag for collecting all events found
:type a: boolean
:param tk: unique token from registered template file
:type tk: string
"""
if not config.store:
try:
cert = tk.read()
token = _collect_token(config, cert)
except:
click.secho("No token", fg='red')
else:
_check_options(config, "events", time, utc, a, token)
else:
try:
token = config._set_token()
except:
click.secho("No token", fg='red')
else:
_check_options(config, "events", time, utc, a, token)
@click.command()
@click.option('-datetime', '-d', 'time', type=str, multiple=True, help="Datetime to collect from (YYYY-MM-DD-HH:MM:SS)")
@click.option('-utc', type=str, multiple=True, help="UTC-formatted time to collect from")
@click.option('--all', '--a', 'a', is_flag=True, is_eager=True, help="Collect all data")
@click.option('-token', '-tk', 'tk', default=None, type=click.File('r'), help="Tokenized template file for verification")
@click.pass_obj
def filtered(config, time, utc, a, tk):
"""
\b
Collect all filtered data for specified datetime or time-range*.
*Options can be supplied twice to indicate a range.
:param time: date-time formatted string
:type time: string
:param utc: UTC-formatted string
:type utc: string
:param a: flag for collecting all events found
:type a: boolean
:param tk: unique token from registered template file
:type tk: string
"""
if not config.store:
try:
cert = tk.read()
token = _collect_token(config, cert)
except:
click.secho("No token", fg='red')
else:
_check_options(config, "events", time, utc, a, token)
else:
try:
token = config._set_token()
except:
click.secho("No token", fg='red')
else:
_check_options(config, "events", time, utc, a, token)
@click.command()
@click.option('-datetime', '-d', 'time', type=str, multiple=True, help="Datetime to collect from (YYYY-MM-DD-HH:MM:SS)")
@click.option('-utc', type=str, multiple=True, help="UTC-formatted time to collect from")
@click.option('--all', '--a', 'a', is_flag=True, is_eager=True, help="Collect all data")
@click.option('-token', '-tk', 'tk', default=None, type=click.File('r'), help="Tokenized template file for verification")
@click.pass_obj
def derived_params(config, time, utc, a, tk):
"""
\b
Collect all derived parameters for specified datetime or time-range*.
*Options can be supplied twice to indicate a range.
:param time: date-time formatted string
:type time: string
:param utc: UTC-formatted string
:type utc: string
:param a: flag for collecting all events found
:type a: boolean
:param tk: unique token from registered template file
:type tk: string
"""
if not config.store:
try:
cert = tk.read()
token = _collect_token(config, cert)
except:
click.secho("No token", fg='red')
else:
_check_options(config, "events", time, utc, a, token)
else:
try:
token = config._set_token()
except:
click.secho("No token", fg='red')
else:
_check_options(config, "events", time, utc, a, token)
@click.command()
@click.option('-datetime', '-d', 'time', type=str, multiple=True, help="Datetime to collect from (YYYY-MM-DD-HH:MM:SS)")
@click.option('-utc', type=str, multiple=True, help="UTC-formatted time to collect from")
@click.option('--all', '--a', 'a', is_flag=True, is_eager=True, help="Collect all data")
@click.option('-token', '-tk', 'tk', default=None, type=click.File('r'), help="Tokenized template file for verification")
@click.pass_obj
def events(config, time, utc, a, tk):
"""
\b
Collect all event data for specified datetime or time-range*.
*Options can be supplied twice to indicate a range.
:param time: date-time formatted string
:type time: string
:param utc: UTC-formatted string
:type utc: string
:param a: flag for collecting all events found
:type a: boolean
:param tk: unique token from registered template file
:type tk: string
"""
if not config.store:
try:
cert = tk.read()
token = _collect_token(config, cert)
except:
click.secho("No token", fg='red')
else:
_check_options(config, "events", time, utc, a, token)
else:
try:
token = config._set_token()
except:
click.secho("No token", fg='red')
else:
_check_options(config, "events", time, utc, a, token)
# d-stream group
dstream.add_command(welcome)
dstream.add_command(define)
dstream.add_command(add_source)
dstream.add_command(load)
#
# dstream.add_command(raw)
# dstream.add_command(filtered)
# dstream.add_command(derived_params)
dstream.add_command(events)
|
993,630 | c7a064d5748eec5c5065e584ac07f8dbfd5ee100 | # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: sms.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='sms.proto',
package='jarvis.sms',
syntax='proto3',
serialized_options=_b('\n\njarvis.smsB\016JarvisSMSProto\242\002\tJARVISSMS'),
serialized_pb=_b('\n\tsms.proto\x12\njarvis.sms\"C\n\x0c\x41uSMSRequest\x12\x15\n\rmobile_number\x18\x01 \x01(\t\x12\x0f\n\x07message\x18\x02 \x01(\t\x12\x0b\n\x03\x61pp\x18\x03 \x01(\t\"1\n\x11\x41uAdminSMSRequest\x12\x0f\n\x07message\x18\x01 \x01(\t\x12\x0b\n\x03\x61pp\x18\x02 \x01(\t\"0\n\rAuSMSResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\x0e\n\x06\x64\x65tail\x18\x02 \x01(\t\"\xc4\x01\n\x10\x41liyunSMSRequest\x12@\n\x0emobile_numbers\x18\x01 \x03(\x0b\x32(.jarvis.sms.AliyunSMSRequest.PhoneNumber\x12\x15\n\rtemplate_code\x18\x02 \x01(\t\x12\x16\n\x0etemplate_param\x18\x03 \x01(\t\x12\x13\n\x0b\x62usiness_id\x18\x04 \x01(\t\x12\x0b\n\x03\x61pp\x18\x05 \x01(\t\x1a\x1d\n\x0bPhoneNumber\x12\x0e\n\x06number\x18\x01 \x01(\t\"4\n\x11\x41liyunSMSResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\x0e\n\x06\x64\x65tail\x18\x02 \x01(\t2\xd3\x01\n\x03SMS\x12\x44\n\x08SMSAdmin\x12\x1d.jarvis.sms.AuAdminSMSRequest\x1a\x19.jarvis.sms.AuSMSResponse\x12<\n\x05SMSAu\x12\x18.jarvis.sms.AuSMSRequest\x1a\x19.jarvis.sms.AuSMSResponse\x12H\n\tSMSAliyun\x12\x1c.jarvis.sms.AliyunSMSRequest\x1a\x1d.jarvis.sms.AliyunSMSResponseB(\n\njarvis.smsB\x0eJarvisSMSProto\xa2\x02\tJARVISSMSb\x06proto3')
)
_AUSMSREQUEST = _descriptor.Descriptor(
name='AuSMSRequest',
full_name='jarvis.sms.AuSMSRequest',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='mobile_number', full_name='jarvis.sms.AuSMSRequest.mobile_number', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='message', full_name='jarvis.sms.AuSMSRequest.message', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='app', full_name='jarvis.sms.AuSMSRequest.app', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=25,
serialized_end=92,
)
_AUADMINSMSREQUEST = _descriptor.Descriptor(
name='AuAdminSMSRequest',
full_name='jarvis.sms.AuAdminSMSRequest',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='message', full_name='jarvis.sms.AuAdminSMSRequest.message', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='app', full_name='jarvis.sms.AuAdminSMSRequest.app', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=94,
serialized_end=143,
)
_AUSMSRESPONSE = _descriptor.Descriptor(
name='AuSMSResponse',
full_name='jarvis.sms.AuSMSResponse',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='success', full_name='jarvis.sms.AuSMSResponse.success', index=0,
number=1, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='detail', full_name='jarvis.sms.AuSMSResponse.detail', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=145,
serialized_end=193,
)
_ALIYUNSMSREQUEST_PHONENUMBER = _descriptor.Descriptor(
name='PhoneNumber',
full_name='jarvis.sms.AliyunSMSRequest.PhoneNumber',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='number', full_name='jarvis.sms.AliyunSMSRequest.PhoneNumber.number', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=363,
serialized_end=392,
)
_ALIYUNSMSREQUEST = _descriptor.Descriptor(
name='AliyunSMSRequest',
full_name='jarvis.sms.AliyunSMSRequest',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='mobile_numbers', full_name='jarvis.sms.AliyunSMSRequest.mobile_numbers', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='template_code', full_name='jarvis.sms.AliyunSMSRequest.template_code', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='template_param', full_name='jarvis.sms.AliyunSMSRequest.template_param', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='business_id', full_name='jarvis.sms.AliyunSMSRequest.business_id', index=3,
number=4, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='app', full_name='jarvis.sms.AliyunSMSRequest.app', index=4,
number=5, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[_ALIYUNSMSREQUEST_PHONENUMBER, ],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=196,
serialized_end=392,
)
_ALIYUNSMSRESPONSE = _descriptor.Descriptor(
name='AliyunSMSResponse',
full_name='jarvis.sms.AliyunSMSResponse',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='success', full_name='jarvis.sms.AliyunSMSResponse.success', index=0,
number=1, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='detail', full_name='jarvis.sms.AliyunSMSResponse.detail', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=394,
serialized_end=446,
)
_ALIYUNSMSREQUEST_PHONENUMBER.containing_type = _ALIYUNSMSREQUEST
_ALIYUNSMSREQUEST.fields_by_name['mobile_numbers'].message_type = _ALIYUNSMSREQUEST_PHONENUMBER
DESCRIPTOR.message_types_by_name['AuSMSRequest'] = _AUSMSREQUEST
DESCRIPTOR.message_types_by_name['AuAdminSMSRequest'] = _AUADMINSMSREQUEST
DESCRIPTOR.message_types_by_name['AuSMSResponse'] = _AUSMSRESPONSE
DESCRIPTOR.message_types_by_name['AliyunSMSRequest'] = _ALIYUNSMSREQUEST
DESCRIPTOR.message_types_by_name['AliyunSMSResponse'] = _ALIYUNSMSRESPONSE
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
AuSMSRequest = _reflection.GeneratedProtocolMessageType('AuSMSRequest', (_message.Message,), {
'DESCRIPTOR' : _AUSMSREQUEST,
'__module__' : 'sms_pb2'
# @@protoc_insertion_point(class_scope:jarvis.sms.AuSMSRequest)
})
_sym_db.RegisterMessage(AuSMSRequest)
AuAdminSMSRequest = _reflection.GeneratedProtocolMessageType('AuAdminSMSRequest', (_message.Message,), {
'DESCRIPTOR' : _AUADMINSMSREQUEST,
'__module__' : 'sms_pb2'
# @@protoc_insertion_point(class_scope:jarvis.sms.AuAdminSMSRequest)
})
_sym_db.RegisterMessage(AuAdminSMSRequest)
AuSMSResponse = _reflection.GeneratedProtocolMessageType('AuSMSResponse', (_message.Message,), {
'DESCRIPTOR' : _AUSMSRESPONSE,
'__module__' : 'sms_pb2'
# @@protoc_insertion_point(class_scope:jarvis.sms.AuSMSResponse)
})
_sym_db.RegisterMessage(AuSMSResponse)
AliyunSMSRequest = _reflection.GeneratedProtocolMessageType('AliyunSMSRequest', (_message.Message,), {
'PhoneNumber' : _reflection.GeneratedProtocolMessageType('PhoneNumber', (_message.Message,), {
'DESCRIPTOR' : _ALIYUNSMSREQUEST_PHONENUMBER,
'__module__' : 'sms_pb2'
# @@protoc_insertion_point(class_scope:jarvis.sms.AliyunSMSRequest.PhoneNumber)
})
,
'DESCRIPTOR' : _ALIYUNSMSREQUEST,
'__module__' : 'sms_pb2'
# @@protoc_insertion_point(class_scope:jarvis.sms.AliyunSMSRequest)
})
_sym_db.RegisterMessage(AliyunSMSRequest)
_sym_db.RegisterMessage(AliyunSMSRequest.PhoneNumber)
AliyunSMSResponse = _reflection.GeneratedProtocolMessageType('AliyunSMSResponse', (_message.Message,), {
'DESCRIPTOR' : _ALIYUNSMSRESPONSE,
'__module__' : 'sms_pb2'
# @@protoc_insertion_point(class_scope:jarvis.sms.AliyunSMSResponse)
})
_sym_db.RegisterMessage(AliyunSMSResponse)
DESCRIPTOR._options = None
_SMS = _descriptor.ServiceDescriptor(
name='SMS',
full_name='jarvis.sms.SMS',
file=DESCRIPTOR,
index=0,
serialized_options=None,
serialized_start=449,
serialized_end=660,
methods=[
_descriptor.MethodDescriptor(
name='SMSAdmin',
full_name='jarvis.sms.SMS.SMSAdmin',
index=0,
containing_service=None,
input_type=_AUADMINSMSREQUEST,
output_type=_AUSMSRESPONSE,
serialized_options=None,
),
_descriptor.MethodDescriptor(
name='SMSAu',
full_name='jarvis.sms.SMS.SMSAu',
index=1,
containing_service=None,
input_type=_AUSMSREQUEST,
output_type=_AUSMSRESPONSE,
serialized_options=None,
),
_descriptor.MethodDescriptor(
name='SMSAliyun',
full_name='jarvis.sms.SMS.SMSAliyun',
index=2,
containing_service=None,
input_type=_ALIYUNSMSREQUEST,
output_type=_ALIYUNSMSRESPONSE,
serialized_options=None,
),
])
_sym_db.RegisterServiceDescriptor(_SMS)
DESCRIPTOR.services_by_name['SMS'] = _SMS
# @@protoc_insertion_point(module_scope)
|
993,631 | bd46532cc5d6c1ebb7cd1b4aec6d510282dc3c84 | # Generated by Django 3.2.5 on 2021-07-26 10:28
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='ShopModel',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('domain', models.CharField(max_length=64, unique=True)),
],
),
migrations.CreateModel(
name='ReviewModel',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('shop_link', models.URLField(blank=True, max_length=255)),
('title', models.CharField(blank=True, max_length=64)),
('description', models.CharField(blank=True, max_length=550)),
('rating', models.IntegerField(blank=True, validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(5)])),
('created', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('shop', models.ForeignKey(blank=True, on_delete=django.db.models.deletion.CASCADE, related_name='reviews', to='reviews.shopmodel')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='reviews', to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'review',
'verbose_name_plural': 'reviews',
'ordering': ['-created'],
},
),
]
|
993,632 | 53f8c5d48b7b8f355130356d2b0dee1cc1f78382 | soma = qtd = 0
for c in range(6):
num = float(input())
if num > 0:
qtd += 1
soma += num
print(qtd, "valores positivos")
print("{:.1f}".format(soma/qtd))
|
993,633 | 42693e443e4b741ed8502146fbbb73f545a26db2 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
import json
def jsonTextReader(jsonFilePath):#讀取 json 的程式
with open(jsonFilePath, encoding="utf-8") as f:#將讀入的json檔案以純文字載入並回傳
text = json.loads(f.read())
return text
def text2Sentence(inputSTR):#將字串轉為「句子」列表的程式
symbol=[ "、", ",","。", ","] #斷句符號
for i in symbol :
inputSTR = inputSTR.replace(i,"|")
inputSTR = inputSTR.replace("…", "")
inputSTR = inputSTR.replace("...", "")
if "|" in inputSTR:
inputSTR = inputSTR.replace("2|718", "2,718")
sentenceLIST = inputSTR.split("|")
return sentenceLIST[:len(sentenceLIST)-1]
if __name__== "__main__":
news_loc = "./example/news.json" #設定要讀取的 news.json 路徑
news_text = jsonTextReader(news_loc)#將 news.json 利用 [讀取 json] 的程式打開
news_LIST = text2Sentence(news_text['text']) #將讀出來的內容字串傳給 [將字串轉為「句子」 列表」]的程式,存為 newsLIST
test_loc = "./example/test.json"#設定要讀取的 test.json 路徑
test_LIST = jsonTextReader(test_loc)['sentence']#將 test.json 的 sentenceLIST 內容讀出,存為 testLIS
#測試是否達到作業需求
if news_LIST == test_LIST:
print("作業過關!")
else:
print("作業不過關,請回到上面修改或是貼文求助!") |
993,634 | f9863ac5a3d641b692c18f6a8d073c3f8418096d | import urllib.request
import json
"""
Capsules
Detailed info for serialized dragon capsules
Get all capsules : GET /capsules
Get one capsule : GET /capsules/:id
Query capsules : POST /capsules/query
lock Create a capsule : POST /capsules
lock Update a capsule : PATCH /capsules/:id
lock Delete a capsule : DELETE /capsules/:id
Cores
Detailed info for serialized first stage cores
Get all cores : GET /cores
Get one core : GET /v4/cores/:id
Query cores : POST /cores/query
lock Create a core : POST /cores - lock
lock Update a core : PATCH /cores/:id - lock
lock Delete a core : DELETE /cores/:id - lock
Crew
Detailed info on dragon crew members
Get all crew members : GET /crew
Get one crew member : GET /crew/:id
Query crew members : POST /crew/query
Dragons
Detailed info about dragon capsule versions
Get all dragons : GET /dragons
Get one dragon : GET /dragons/:id
Query dragons : POST /dragons/query
Landpads
Detailed info about landing pads and ships
Get all landpads : GET /landpads
Get one landpad : GET /landpads/:id
Query landpads : POST /landpads/query
Launches
Detailed info about launches
Get past launches : GET /launches/past
Get upcoming launches : GET /launches/upcoming
Get latest launches : GET /launches/latest
Get next launches : GET /launches/next
Get all launches : GET /launches
Get one launch : GET /launches/:id
Query launches : POST /launches/query
Launchpads
Detailed info about launchpads
Get all launchpads : GET /launchpads
Get one launchpad : GET /launchpads/:id
Query launchpads : POST /launchpads/query
Payloads
Detailed info about launch payloads
Get all payloads : GET /payloads
Get one payload : GET /payloads/:id
Query payloads : POST /payloads/query
Rockets
Detailed info about rocket versions
Get all rockets : GET /rockets
Get one rocket : GET /rockets/:id
Query rockets : POST /rockets/query
Ships
Detailed info about ships in the SpaceX fleet
Get all ships : GET /ships
Get one ship : GET /ships/:id
Query ships : POST /ships/query
Company Info
Detailed info about SpaceX as a company
Get company info : GET /company
Roadster info
Detailed info about Elon's Tesla roadster's current position
Get roadster info : GET /roadster
"""
req = urllib.request.Request('https://api.spacexdata.com/v4/payloads')
#req = urllib.request.Request('https://api.spacexdata.com/v4/roadster')
response = urllib.request.urlopen(req)
the_page = response.read()
json_dump = json.loads(the_page)
#print(json_dump[0])
print(len(json_dump))
#print(json.dumps(json_dump,indent=3, sort_keys = True))
for key in json_dump:
print("Name: ", key["name"], "| Reused:", key["reused"], "| Type:", key["type"], "| Customers: ", ", ".join(key["customers"]))
#print(key)
#print("{0} - {1}".format(i["name"], i["date_local"]))
#print("Name: ", v["name"])
#for value in key:
# print("Value: " + value)
"""
print("orignal list is : " + str(json_dump))
#res = [dict(zip(json_dump, i)) for i in zip(*json_dump.values())]
# printing result
#print ("The converted list of dictionaries " + str(res))
for i in json_dump['flickr_images']:
print(i)
for k in json_dump.keys():
for i in json_dump[k]:
print(k)
#response.close()
"""
|
993,635 | 2ea91cd8dda5e8b6075dc005555ed0b166ab3f03 | # Generated by Django 2.1.5 on 2019-01-10 10:16
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('proposal', '0002_auto_20181228_0050'),
]
operations = [
migrations.AlterField(
model_name='proposal',
name='brand',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='device.Brand'),
),
migrations.AlterField(
model_name='proposal',
name='device_model',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='device.DeviceModel'),
),
migrations.AlterField(
model_name='proposal',
name='mark',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='device.Mark'),
),
]
|
993,636 | e14c432f0f765bdf607f45fc5225a6c45f055379 | #Nguyen Thi Yen Khoa
# MSSV: B1709343
#---------------Cau1-----------------
#print("Hello ! welcome to python!")
#------------------------------------
#--------------------------------Cau2----------------------
#print("Nhap ten cua ban: ")
#x = input()
#print("Hello " + x + " Welcome to Python")
#----------------------------------------------------------
#---------------------------------Cau3---------------------
#print("Nhap so b: ")
#b = float(input())
#print("Nhap so a: ")
#a = float(input())
#while b == 0:
# print("Moi nhap lai b")
# b = float(input())
#tong = a+b
#print("tong la: ", tong)
#tru = a-b
#print("Hieu la: ", tru)
#tich = a*b
#print("Tich la: ", tich)
#thuong = a/b
#print("Thuong la: ", thuong)
#sodu = a%b
#print("Phep du la: ", sodu)
#luythua = a**b
#print("Luy thua la: ", luythua)
#------------------------------------------------------------
#-------------------------Cau4-------------------------------
# print("Nhap r: ")
# r = float(input())
# pi = 3.14
# chuvi = 2*r*pi
# print("Chu vi hinh tron la: ", chuvi)
# dientich = pi*r*r
# print("Dien tich hinh tron la: ", dientich)
#------------------------------------------------------------
#--------------------------Cau5------------------------------
# print("Nhap so nguyen n: ")
# n = int(input())
# while(n<0) :
# print("Moi ban nhap lai")
# n = int(input())
# def giaithua(n) :
# if n==0:
# return 1
# return n*giaithua(n-1)
# print("Giai thua la: ", giaithua(n))
#--------------------------------------------------------------
#--------------------------Cau6-------------------------------------------------------------
# import math
# print("Nhap a: ")
# a = float(input())
# print("Nhap b: ")
# b = float(input())
# print("Nhap c: ")
# c = float(input())
# if a==0:
# print("Phuong trinh co nghiem la: ", (0-c)/b)
# if a!=0:
# delta = (b*b) - 4*a*c
# print ("delta = ", delta)
# if delta==0:
# print("Phuong trinh co nghiem kep: ", (-b)/(2*a))
# if delta < 0:
# print("Phuong trinh vo nghiem")
# if delta > 0:
# print("Phuong trinh co hai nghiemn")
# print("x1= ", ((-b)+math.sqrt(delta))/(2*a), "\nx2= ", ((-b)-math.sqrt(delta))/(2*a))
#-----------------------------------------------------------------------------------------------
#----------------------------Cau7---------------------------------------------------------------
# numbers = []
# for i in range(5000,7001):
# if i%7==0 and i%5!=0:
# numbers.append(str(i))
# print(", ". join(numbers))
#-----------------------------------------------------------------------------------------------
#----------------------------------Cau8----------------------------------------------------------
# print("Nhap so nguyen: ")
# n = int(input())
# while n < 0:
# print("Moi ban nhap lai:")
# n = int(input())
# print("Doi sang nhi phan: ", int(bin(n)[2:]))
#------------------------------------------------------------------------------------------------
#------------------------------------Cau9--------------------------------------------------------
# print("Nhap so a:")
# a = int(input())
# print("Nhap so b:")
# b = int(input())
# def UCLN(a,b):
# while a!=b:
# if a>b:
# a = a - b
# else :
# b = b - a
# return a
# print("UCLN la: ",UCLN(a,b))
# def BCNN(a,b):
# result = UCLN(a,b)
# return int ((a*b)/result)
# print("BCNN la: ", BCNN(a,b))
#------------------------------------------------------------------------------------------------
#---------------------------------------Cau10-----------------------------------------------------
# import math
# print("Nhap so n: ")
# n = int(input())
# def isPrimeNumber(n) :
# if n<2:
# return False
# else :
# squarenumber = int(math.sqrt(n))
# for i in range(2,squarenumber+1):
# if n%i==0:
# return False
# return True
# print("So nguyen to nho hon", n, "la: ")
# result=""
# if n>=2:
# result = result + "2" + " "
# for i in range(3,n+1):
# if isPrimeNumber(i):
# result = result + str(i) + " "
# i = i + 2
# print(result)
#-------------------------------------------------------------------------------------------------
#------------------------------------------------Cau11--------------------------------------------
# import math
# def isPrimeNumber(n) :
# if n<2:
# return False
# else :
# squarenumber = int(math.sqrt(n))
# for i in range(2,squarenumber+1):
# if n%i==0:
# return False
# return True
# print("Nhung so nguyen to co 4 chu so la: ")
# result = ""
# for i in range(1001,9999):
# if isPrimeNumber(i):
# result = result + str(i) + " "
# print(result)
#-------------------------------------------------------------------------------------------------
#-------------------------------------------Cau12-------------------------------------------------
# print("Nhap vao so nguyen n: ")
# n = int(input())
# def SumN(n):
# sum = 0
# while n>0:
# sum = sum + (n%10)
# n = int(n/10)
# return sum
# print("Tong cac chu so trong ", n, " la: ", SumN(n))
#-------------------------------------------------------------------------------------------------
#-----------------------------------------------Cau13---------------------------------------------
# values = []
# for i in range(1000,2001):
# n = str(i)
# if (int(n[0])%2!=0) and (int(n[1])%2!=0) and (int(n[2])%2!=0) and (int(n[3])%2!=0):
# values.append(n)
# print(", ".join(values))
#-------------------------------------------------------------------------------------------------
#------------------------------------------Cau14---------------------------------------------------
# print("Nhap n: ")
# n = int(input())
# while n < 0:
# print("Moi nhap lai n: ")
# n = int(input())
# sum = 0
# for i in range(1,n+1):
# sum = sum + float(i/(i+1))
# print(sum)
#--------------------------------------------------------------------------------------------------
#------------------------------------------------Cau15---------------------------------------------
# print("Nhap n: ")
# n = int(input())
# def fibonaci(n):
# if n==0:
# return 0
# if n==1:
# return 1
# else :
# return fibonaci(n-1) + fibonaci(n-2)
# print("Day fibonaci la: ",fibonaci(n))
#--------------------------------------------------------------------------------------------------
# print(1,2,3,4,sep='*')
print(3>=3) |
993,637 | 3c403889219a11b5d3ae4b2158d5a1ea80bda766 | #!/usr/bin/env seiscomp-python
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (C) GFZ Potsdam #
# All rights reserved. #
# #
# Author: Joachim Saul (saul@gfz-potsdam.de) #
# #
# GNU Affero General Public License Usage #
# This file may be used under the terms of the GNU Affero #
# Public License version 3.0 as published by the Free Software Foundation #
# and appearing in the file LICENSE included in the packaging of this #
# file. Please review the following information to ensure the GNU Affero #
# Public License version 3.0 requirements will be met: #
# https://www.gnu.org/licenses/agpl-3.0.html. #
###########################################################################
import sys, os
import seiscomp.core
import seiscomp.client
import seiscomp.datamodel
import seiscomp.io
import seiscomp.logging
import seiscomp.utils
def notifierMessageFromXML(xml):
b = seiscomp.utils.stringToStreambuf(xml)
ar = seiscomp.io.XMLArchive(b)
obj = ar.readObject()
if obj is None:
raise TypeError("got invalid xml")
nmsg = seiscomp.datamodel.NotifierMessage.Cast(obj)
if nmsg is None:
raise TypeError("no NotifierMessage object found")
return nmsg
def notifierInput(filename):
f = open(filename)
while True:
while True:
line = f.readline()
if not line:
# empty input
return True
line = line.strip()
if not line:
# blank line
continue
if line[0] == "#":
break
if len(line.split()) == 3:
sharp, timestamp, nbytes = line.split()
elif len(line.split()) == 4:
sharp, timestamp, nbytes, sbytes = line.split()
assert sbytes == "bytes"
elif len(line.split()) == 5:
sharp, timestamp, md5hash, nbytes, sbytes = line.split()
assert sbytes == "bytes"
else:
break
assert sharp[0] == "#"
time = seiscomp.core.Time.GMT()
time.fromString(timestamp, "%FT%T.%fZ")
nbytes = int(nbytes)
assert sharp[0] == "#"
xml = f.read(nbytes).strip()
yield time, notifierMessageFromXML(xml)
class NotifierPlayer(seiscomp.client.Application):
def __init__(self, argc, argv):
super(NotifierPlayer, self).__init__(argc, argv)
self.setMessagingEnabled(False)
self.setDatabaseEnabled(False, False)
self._startTime = self._endTime = None
self.xmlInputFileName = None
self._time = None
def createCommandLineDescription(self):
super(NotifierPlayer, self).createCommandLineDescription()
self.commandline().addGroup("Play")
self.commandline().addStringOption("Play", "begin", "specify start of time window")
self.commandline().addStringOption("Play", "end", "specify end of time window")
self.commandline().addGroup("Input")
self.commandline().addStringOption("Input", "xml-file", "specify xml file")
def init(self):
if not super(NotifierPlayer, self).init():
return False
try: start = self.commandline().optionString("begin")
except: start = None
try: end = self.commandline().optionString("end")
except: end = None
try: self.xmlInputFileName = self.commandline().optionString("xml-file")
except: pass
if start:
self._startTime = seiscomp.core.Time.GMT()
if self._startTime.fromString(start, "%FT%TZ") == False:
seiscomp.logging.error("Wrong 'begin' format")
return False
if end:
self._endTime = Core.Time.GMT()
if self._endTime.fromString(end, "%FT%TZ") == False:
seiscomp.logging.error("Wrong 'end' format")
return False
return True
def run(self):
if not self.xmlInputFileName:
return False
seiscomp.logging.debug("input file is %s" % self.xmlInputFileName)
for time,nmsg in notifierInput(self.xmlInputFileName):
if self._startTime is not None and time < self._startTime:
continue
if self._endTime is not None and time > self._endTime:
break
self.sync(time)
# We either extract and handle all Notifier objects individually
for item in nmsg:
n = seiscomp.datamodel.Notifier.Cast(item)
assert n is not None
n.apply()
self.handleNotifier(n)
# OR simply handle the NotifierMessage
# self.handleMessage(nmsg)
return True
def sync(self, time):
self._time = time
seiscomp.logging.debug("sync time=%s" % time.toString("%FT%T.%fZ"))
def addObject(self, parent, obj):
# in a usable player, this must be reimplemented
seiscomp.logging.debug("addObject class=%s parent=%s" % (obj.className(),parent))
def updateObject(self, parent, obj):
# in a usable player, this must be reimplemented
seiscomp.logging.debug("updateObject class=%s parent=%s" % (obj.className(),parent))
app = NotifierPlayer(len(sys.argv), sys.argv)
sys.exit(app())
|
993,638 | b10cc9cc3565a3d58a9482f0e59146255f625728 | #!usr/bin/python3
# 主界面
# 使用tk模块
# 包含一个菜单栏,工具栏,状态栏的图形化程序
import tkinter as tk
from tkinter import messagebox as mes
from tkinter import ttk
class Main():
pass
if __name__ == '__main__':
vi = Main()
vi.mainloop()
|
993,639 | ca55a43dfc14a33095e18b68e109077050eb4017 | """
In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
The town judge trusts nobody.
Everybody (except for the town judge) trusts the town judge.
There is exactly one person that satisfies properties 1 and 2.
You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b.
If the town judge exists and can be identified, return the label of the town judge. Otherwise, return -1.
Example 1:
Input: N = 2, trust = [[1,2]]
Output: 2
Example 2:
Input: N = 3, trust = [[1,3],[2,3]]
Output: 3
Example 3:
Input: N = 3, trust = [[1,3],[2,3],[3,1]]
Output: -1
Example 4:
Input: N = 3, trust = [[1,2],[2,3]]
Output: -1
Example 5:
Input: N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]
Output: 3
Note:
1 <= N <= 1000
trust.length <= 10000
trust[i] are all different
trust[i][0] != trust[i][1]
1 <= trust[i][0], trust[i][1] <= N
"""
import collections
def find_judge(N, trust):
in_order = {}
graph = {}
for i in range(1, N + 1):
in_order[i] = 0
graph[i] = []
for each_trust in trust:
a, b = each_trust # where a trust b => have a edge from a -> b
in_order[b] += 1
graph[a].append(b)
for each in in_order:
if in_order[each] == N-1 and len(graph[each]) == 0:
return each
return -1
print(find_judge(3, [[1,3],[2,3]]))
print(find_judge(3, [[1,3],[2,3],[3,1]]))
print(find_judge(4, [[1,3],[1,4],[2,3],[2,4],[4,3]])) |
993,640 | 032e1e45ebb701f1898f05b1afbf76579221c01e | import tkinter as tk
import socket
import errno
import sys
import threading
import json
from tkinter import messagebox
from ttkthemes import ThemedTk
from functools import partial
# TODO: Lanjut fix ui, export & restore, refactor, close window and server is all destroy function and message finalizing
class ClientWindow:
def __init__(self):
self.mainwindow = ThemedTk(theme='breeze')
self.mainwindow.resizable(0, 0)
self.address = tk.StringVar()
self.port = tk.IntVar()
self.username = tk.StringVar()
self.room_var = tk.StringVar()
self.address.set("127.0.0.1")
self.port.set(5000)
self.room_list = []
self.is_join_room = False
self.connection = None
self.room = None
self.title("ChatClient")
self.__init()
def title(self, title):
self.mainwindow.title(title)
def __init(self):
# Frame Widgets
self.__server_frame = tk.ttk.LabelFrame(
self.mainwindow, text="Connection Info")
self.__chat_frame = tk.ttk.LabelFrame(
self.mainwindow, text="Chat Room")
self.__input_frame = tk.ttk.Frame(self.mainwindow)
# Frame Packing
self.__server_frame.pack(side='top', fill='both', pady=(10, 0), padx=5)
self.__chat_frame.pack(side='top', fill='both', padx=5, pady=5)
self.__input_frame.pack(side='top', fill='both', pady=10, padx=10)
# Widgets
# Connection Form Widgets
self.room_entry = tk.ttk.Entry(
self.__server_frame, textvariable=self.room_var)
self.address_label = tk.ttk.Label(
self.__server_frame, text="Address")
self.address_entry = tk.ttk.Entry(
self.__server_frame, textvariable=self.address)
self.port_label = tk.ttk.Label(
self.__server_frame, text="Port")
self.port_entry = tk.ttk.Entry(
self.__server_frame, textvariable=self.port)
self.connect_button = tk.ttk.Button(
self.__server_frame, text="Connect", command=lambda: self.connecting(self.room_entry.get()))
self.disconnect_button = tk.ttk.Button(
self.__server_frame, text="Disconnect", command=self.disconnect)
self.username_label = tk.ttk.Label(
self.__server_frame, text="Username")
self.username_entry = tk.ttk.Entry(
self.__server_frame, textvariable=self.username)
self.username_button_edit = tk.ttk.Button(
self.__server_frame, text="Edit", state='disabled')
self.room_label = tk.ttk.Label(
self.__server_frame, text="Room")
self.room_button_scan = tk.ttk.Button(
self.__server_frame, text="Scan", command=self.request_room)
# Chat Scrollframe Widget
self.scrollframe = ScrollFrame(self.__chat_frame)
# Message Form Widgets
self.message_label = tk.ttk.Label(self.__input_frame, text="Message")
self.message_text = tk.ttk.Entry(self.__input_frame, width=35)
self.message_text.bind("<Return>", self.send)
self.message_button = tk.ttk.Button(
self.__input_frame, text="Send", command=self.send)
### Packing & Grid
# Connection Form Grid
self.address_label.grid(row=0, column=0)
self.address_entry.grid(row=0, column=1)
self.port_label.grid(row=1, column=0)
self.port_entry.grid(row=1, column=1)
self.connect_button.grid(
row=0, column=2, rowspan=2, sticky="NSEW", padx=5)
self.disconnect_button.grid(
row=0, column=3, rowspan=2, sticky="NSEW", padx=5)
self.username_label.grid(row=2, column=0)
self.username_entry.grid(row=2, column=1)
self.username_button_edit.grid(
row=2, column=2, columnspan=2, sticky="NSEW", padx=5, pady=5)
self.room_label.grid(row=3, column=0, pady=(0, 10))
self.room_entry.grid(row=3, column=1, pady=(0, 10))
self.room_button_scan.grid(
row=3, column=2, columnspan=2, sticky="NSEW", padx=5, pady=(0, 10))
# Chat Field Pack
self.scrollframe.pack(side="top", fill="both", expand=True)
# Message Widget Grid
self.message_label.grid(row=0, column=0, sticky="NSEW")
self.message_text.grid(row=0, column=1, sticky="NSEW")
self.message_button.grid(row=0, column=2, sticky="NSEW", padx=(10, 2))
def connecting(self, room=None):
try:
username = bool(self.username_entry.get())
if username:
self.connection = ConnectServer(username=self.username_entry.get(
), address=(self.address_entry.get(), int(self.port_entry.get())), room=room)
self.connection.connect()
self.connected()
self.title(room)
self.username_button_edit.config(state='normal')
self.username_entry.config(state='disabled')
self.room_button_scan.config(state='disabled')
self.room_entry.delete(0, 'end')
self.room_entry.insert(0, room)
self.room_entry.config(state='disabled')
else:
messagebox.showwarning(
"Warning", "Please fill username field.")
except Exception as e:
messagebox.showerror("Error", str(e))
def connected(self):
try:
self.room = threading.Thread(
target=self.connection.receive_message, kwargs={'window': self, })
self.room.start()
except:
messagebox.showerror('error', 'Failed')
def disconnect(self):
if self.connection != None:
self.connection.disconnect()
self.connection = None
self.room = None
messagebox.showinfo("Success", "Disconnected from server.")
self.address_entry.configure(state='normal')
self.port_entry.configure(state='normal')
self.connect_button.configure(
state='normal', text='Connect')
self.username_entry.config(state='normal')
self.username_button_edit.config(state='disabled')
self.room_entry.config(state='normal')
self.room_button_scan.config(state='normal')
else:
messagebox.showinfo("Info", "Connect to a Server First.")
def send(self, event=None):
try:
message = self.message_text.get()
data = {'type': 'message',
'username': self.username_entry.get(),
'room': self.room_entry.get(),
'message': message}
if message:
self.connection.send_message(data)
self.message_text.delete(0, 'end')
self.insert(json.dumps(data), 'e')
except:
messagebox.showerror("Error", "Please connect to server and room.")
def insert(self, text, anchor):
data = json.loads(text)
if data['type'] == 'message':
f = tk.Frame(self.scrollframe.viewPort, width=25,
highlightbackground='#3daee9', highlightthickness=1)
f.pack(fill='x', side='top', expand=True, padx=5, pady=5)
tk.ttk.Label(f, text=data['username'], anchor=anchor, font=(
'helvetica', 7)).pack(fill='x')
tk.ttk.Label(f, text=' '+data['message'],
anchor=anchor).pack(fill='x')
self.scrollframe.canvas.yview_moveto(1)
elif data['type'] == 'respond_room':
for room in data['rooms']:
self.room_list.append(tk.ttk.Button(
self.scrollframe.viewPort, text=room, command=partial(self.connecting, room)))
for room in self.room_list:
room.pack()
if self.is_join_room is False:
self.connection.disconnect()
self.connection = None
elif data['type'] == 'error':
messagebox.showerror('error', data['message'])
self.connection.disconnect()
elif data['type'] == 'success':
self.clear()
if self.room_list:
for room in self.room_list:
room.pack_forget()
self.room_list = []
f = tk.Frame(self.scrollframe.viewPort, width=25,
highlightbackground='#3daee9', highlightthickness=1)
f.pack(fill='x', side='top', expand=True, padx=5, pady=5)
tk.ttk.Label(f, text=data['message'],
anchor='n').pack(fill='x')
self.scrollframe.canvas.yview_moveto(1)
self.is_join_room = True
self.address_entry.configure(state='disabled')
self.port_entry.configure(state='disabled')
self.connect_button.configure(
state='disabled', text='Connected')
def request_room(self):
try:
data = {'type': 'request_room',
'username': self.username_entry.get()}
if self.room_list:
for x in self.room_list:
x.pack_forget()
self.room_list = []
if self.connection == None:
self.connection = ConnectServer()
self.connection.connect_socket.connect(
(self.address_entry.get(), int(self.port_entry.get())))
self.connection.is_connect = True
self.connected()
self.connection.send_message(data)
else:
self.connection.send_message(data)
except Exception as e:
messagebox.showerror("Error", str(e))
self.connection.disconnect()
self.connection = None
def clear(self):
for widget in self.scrollframe.viewPort.winfo_children():
widget.destroy()
def sync(self):
pass
class ScrollFrame(tk.Frame):
def __init__(self, parent):
super().__init__(parent)
self.canvas = tk.Canvas(self, borderwidth=0, width=400, height=300)
self.viewPort = tk.Frame(self.canvas)
self.vsb = tk.ttk.Scrollbar(self, orient="vertical",
command=self.canvas.yview)
self.canvas.configure(yscrollcommand=self.vsb.set)
self.canvas.bind_all(
"<MouseWheel>", lambda e: self.canvas.yview_scroll(-1*(e.delta//120), 'units'))
self.vsb.pack(side="right", fill="y")
self.canvas.pack(side="left", fill="both", expand=True)
self.canvas_window = self.canvas.create_window(
(4, 4), window=self.viewPort, anchor="nw", tags="self.viewPort")
self.viewPort.bind("<Configure>", self.onFrameConfigure)
self.canvas.bind("<Configure>", self.onCanvasConfigure)
self.onFrameConfigure(None)
def onFrameConfigure(self, event):
'''Reset the scroll region to encompass the inner frame'''
self.canvas.configure(scrollregion=self.canvas.bbox(
"all"))
def onCanvasConfigure(self, event):
'''Reset the canvas window to encompass inner frame when required'''
canvas_width = event.width
self.canvas.itemconfig(self.canvas_window, width=canvas_width)
class ConnectServer:
def __init__(self, username=None, address=(), room=None):
self.HEADER = 8
self.address = address
self.username = username
self.room = room
self.connect_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.is_connect = False
def connect(self):
self.connect_socket.connect(self.address)
self.is_connect = True
data = {'type': 'initialize',
'username': self.username,
'room': self.room}
self.send_message(data)
def disconnect(self):
self.is_connect = False
self.connect_socket.close()
def receive_message(self, window):
while self.is_connect:
try:
while True:
header = self.connect_socket.recv(self.HEADER)
print(header)
if not len(header):
# messagebox.showwarning(
# "Warning", "Connection closed by server")
sys.exit()
data_length = int(
header.decode('utf-8').strip())
data = self.connect_socket.recv(
data_length).decode('utf-8')
window.insert(data, 'w')
except IOError as e:
if e.errno != errno.EAGAIN and e.errno != errno.EWOULDBLOCK:
sys.exit()
continue
except Exception as e:
sys.exit()
return True
def send_message(self, message):
serialize_message = json.dumps(message).encode('utf-8')
message_header = f"{len(serialize_message):<{self.HEADER}}".encode(
'utf-8')
self.connect_socket.send(message_header + serialize_message)
x = ClientWindow()
x.mainwindow.mainloop()
|
993,641 | dc969752031740eddc7570d79664f46ea342a359 | import urllib2
from common import *
from crawler import download_pdb_file
class PdbFileDownloaderTest(unittest.TestCase):
def test_download_file_length(self):
file_content = download_pdb_file("1LSG")
actual = len(file_content)
expected = 122472
self.assertEqual(actual, expected)
def test_not_downloadable_exception(self):
actual = download_pdb_file("~~")
expected = None
self.assertEqual(actual, expected)
if __name__ == '__main__':
unittest.main() |
993,642 | fd9978f1ea0d4ceda2af0a72c413df1984610f8a | # Autogenerated from KST: please remove this line if doing any edits by hand!
import unittest
from bits_signed_b64_le import _schema
class TestBitsSignedB64Le(unittest.TestCase):
def test_bits_signed_b64_le(self):
r = _schema.parse_file('src/bits_signed_b64_le.bin')
self.assertEqual(r.a_num, 0)
self.assertEqual(r.a_bit, True)
self.assertEqual(r.b_num, 9223372036854775807)
self.assertEqual(r.b_bit, False)
|
993,643 | 5708bf36bb260d09d933199d806f541fb632403d | from django.contrib.auth.models import User
from django.contrib.auth import *
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Address(models.Model):
street = models.CharField(max_length=200)
number = models.CharField(max_length=5)
district = models.CharField(max_length=200)
city= models.CharField(max_length=200)
state = models.CharField(max_length=200)
country =models.CharField(max_length=200, null=True)
zip_code = models.CharField(max_length=11, null=True)
def __str__(self):
return self.street+' Nº '+self.number+' '+self.district
class Business(models.Model):
name = models.CharField(max_length=200)
telefone = models.CharField(max_length=20, null=True)
email = models.CharField(max_length=200, null=True)
site=models.CharField(max_length=200, null=True)
manager = models.OneToOneField('auth.User', related_name='owner', on_delete=models.CASCADE)
cnpj = models.CharField(max_length=20)
category = models.ForeignKey(Category, related_name='category', on_delete=models.DO_NOTHING, null=True)
address = models.OneToOneField(Address, related_name='address', on_delete=models.DO_NOTHING, null=True)
def __str__(self):
return self.name
class Profession(models.Model):
name=models.CharField(max_length=200)
value = models.DecimalField(max_digits=8, decimal_places=2, null=True)
def __str__(self):
return self.name
class Professional(models.Model):
usuario = models.OneToOneField(User, related_name='professional', on_delete=models.CASCADE)
profession = models.OneToOneField(Profession, related_name='profession', on_delete=models.CASCADE)
business = models.ForeignKey(Business, related_name='professionals', on_delete=models.CASCADE, null=True)
def __str__(self):
return self.usuario.username
class Day(models.Model):
name = models.CharField(max_length=29)#explicitar como unico
def __str__(self):
return self.name
class Horario(models.Model):
day = models.ForeignKey(Day, related_name='day', on_delete=models.CASCADE)# Na views criar validação para não repetir o mesmo inicio e fim
init = models.CharField(max_length=5)
end = models.CharField(max_length=5)
def __str__(self):
return self.day.name+' de '+self.init+' às '+self.end
class Agenda(models.Model):
business = models.ForeignKey(Business, related_name='agenda', on_delete=models.CASCADE)
professional = models.OneToOneField(Professional, related_name='professional', on_delete=models.CASCADE, null=True)
horario = models.ForeignKey(Horario, related_name='horario', on_delete=models.CASCADE)
confirmed = models.BooleanField(default=False)
cliente = models.ForeignKey(User, related_name='cliente', on_delete=models.CASCADE, null=True)
class Atendimento(models.Model):
agenda = models.ForeignKey(Agenda, related_name='agenda', on_delete=models.CASCADE, null=True)
report = models.CharField(max_length=512, null=True)
realizado = models.BooleanField(default=False) |
993,644 | 1a3da7d1f13aac213e6f6175f8822a0542f6d195 | from firebase import firebase
import functions as f
import json
import time
fire = firebase.FirebaseApplication('https://proj1-6f30a.firebaseio.com/',None)
data = fire.get("/macs", None)
print(data)
diction = dict()
diction["macs"] = data
def algorithm(point):
t_point = f.cal_avg_std(point)
ref_points = json.loads(open("all-points.json").read())
for p in ref_points:
p["marker"] = -1
flag = f.find_flag(t_point)
pre_matched_points = f.get_matched_points(ref_points,flag)
for p in pre_matched_points:
print(p)
points = f.improved_euclidean_dis(t_point, pre_matched_points)
least_closest_points = f.sort_by_euclidean_dis(points)
print("**least_closest_points**")
for p in least_closest_points:
print(p)
co_ordinates1 = f.get_position_acc_to_closest_points(least_closest_points)
print("**x1,y1 **")
for co_ord in co_ordinates1:
print(co_ord)
reverse = []
reverse.append(co_ordinates1[1])
reverse.append(co_ordinates1[0])
fire.put("/","result",reverse)
algorithm(diction)
while True:
if(fire.get("/flag",None)):
real_data = data
data = fire.get("/macs", None)
diction["macs"] = data
print(diction)
if real_data != data:
algorithm(diction)
fire.put("/","flag",False)
|
993,645 | 486b1c58eb46315aad8b74edb0fc2412322cfbf7 | #!/usr/bin/env python
# coding: utf-8
import sys
from oar.lib import (config, get_logger)
from oar.lib.job_handling import (get_job_frag_state, job_arm_leon_timer, job_finishing_sequence,
get_jobs_to_kill, set_job_message, get_job_types,
set_job_state, set_finish_date, get_job_current_hostnames,
get_to_exterminate_jobs, set_running_date)
from oar.lib.event import add_new_event
import oar.lib.tools as tools
from oar.lib.tools import DEFAULT_CONFIG
logger = get_logger("oar.modules.leon", forward_stderr=True)
logger.info('Start Leon')
class Leon(object):
def __init__(self, args=None):
self.args = args if args else []
config.setdefault_config(DEFAULT_CONFIG)
self.exit_code = 0
def run(self):
deploy_hostname = None
if 'DEPLOY_HOSTNAME' in config:
deploy_hostname = config['DEPLOY_HOSTNAME']
cosystem_hostname = None
if 'COSYSTEM_HOSTNAME' in config:
cosystem_hostname = config['COSYSTEM_HOSTNAME']
epilogue_script = None
if 'SERVER_EPILOGUE_EXEC_FILE' in config:
epilogue_script = config['SERVER_EPILOGUE_EXEC_FILE']
openssh_cmd = config['OPENSSH_CMD']
ssh_timeout = config['OAR_SSH_CONNECTION_TIMEOUT']
oarexec_directory = config['OAR_RUNTIME_DIRECTORY']
# Test if we must launch a finishing sequence on a specific job
if len(self.args) >= 1:
try:
job_id = int(self.args[0])
except ValueError as ex:
logger.error('"%s" cannot be converted to an int' % ex)
self.exit_code = 1
return
frag_state = get_job_frag_state(job_id)
if frag_state == 'LEON_EXTERMINATE':
# TODO: from leon.pl, do we need to ignore some signals
# $SIG{PIPE} = 'IGNORE';
# $SIG{USR1} = 'IGNORE';
# $SIG{INT} = 'IGNORE';
# $SIG{TERM} = 'IGNORE';
logger.debug('Leon was called to exterminate job "' + str(job_id) + '"')
job_arm_leon_timer(job_id)
events = [('EXTERMINATE_JOB', 'I exterminate the job ' + str(job_id))]
job_finishing_sequence(epilogue_script, job_id, events)
tools.notify_almighty('ChState')
else:
logger.error('Leon was called to exterminate job "' + str(job_id) +
'" but its frag_state is not LEON_EXTERMINATE')
return
for job in get_jobs_to_kill():
#TODO pass if the job is job_desktop_computing one
logger.debug('Normal kill: treates job ' + str(job.id))
if (job.state == 'Waiting') or (job.state == 'Hold'):
logger.debug('Job is not launched')
set_job_state(job.id, 'Error')
set_job_message(job.id, 'Job killed by Leon directly')
if job.type == 'INTERACTIVE':
logger.debug('I notify oarsub in waiting mode')
addr, port = job.info_type.split(':')
if tools.notify_tcp_socket(addr, port, 'JOB_KILLED'):
logger.debug('Notification done')
else:
logger.debug('Cannot open connection to oarsub client for job '+
str(job.id) +', it is normal if user typed Ctrl-C !')
self.exit_code = 1
elif (job.state == 'Terminated') or (job.state == 'Error') or (job.state == 'Finishing'):
logger.debug('Job is terminated or is terminating nothing to do')
else:
job_types = get_job_types(job.id)
if 'noop' in job_types.keys():
logger.debug('Kill the NOOP job: ' + str(job.id))
set_finish_date(job)
set_job_state(job.id, 'Terminated')
job_finishing_sequence(epilogue_script, job.id, [])
self.exit_code = 1
else:
hosts = get_job_current_hostnames(job.id)
head_host = None
#deploy, cosystem and no host part
if ('cosystem' in job_types.keys()) or (len(hosts) == 0):
head_host = cosystem_hostname
elif 'deploy' in job_types.keys():
head_host = deploy_hostname
elif len(hosts) != 0:
head_host = hosts[0]
if head_host:
add_new_event('SEND_KILL_JOB', job.id, 'Send the kill signal to oarexec on ' +
head_host + ' for job ' + str(job.id))
comment = tools.signal_oarexec(head_host, job.id, 'TERM', False, openssh_cmd)
logger.warning(comment)
job_arm_leon_timer(job.id)
# Treate jobs in state EXTERMINATED in the table fragJobs
for job in get_to_exterminate_jobs():
logger.debug('EXTERMINATE the job: ' + str(job.id))
set_job_state(job.id, 'Finishing')
if job.start_time == 0:
set_running_date(job.id)
set_finish_date(job)
set_job_message(job.id, 'Job exterminated by Leon')
tools.notify_bipbip_commander({'job_id': job.id, 'cmd': 'LEONEXTERMINATE',
'args':[]})
def main(): # pragma: no cover
leon = Leon(sys.argv[1:])
leon.run()
return leon.exit_code
if __name__ == '__main__': # pragma: no cover
sys.exit(main())
|
993,646 | 2bd4a4d790abecc0742a37679b819f7f944d9707 | import json
import logging
import os
from trpycore.zookeeper_gevent.client import GZookeeperClient
from trpycore.zookeeper_gevent.watch import GHashringWatch
from trpycore.zookeeper.watch import HashringWatch
from trsvcscore.hashring.base import ServiceHashring, ServiceHashringNode, ServiceHashringException, ServiceHashringEvent
from trsvcscore.service.base import ServiceInfo
class ZookeeperServiceHashring(ServiceHashring):
"""Consistent service hashring.
Wrapper around GHashringWatch to ensure consitencies for hashring
implementations across services. ZookeeperServiceHashring should
be used by both clients of the service and instances of the services
needing to register positions on the hashring.
All hashring position nodes are ephemeral and will automatically be
removed upon service disconnection or termination.
A hashring node will be created in zookeeper at /services/<service>/hashring,
where each child node will represent an occupied position on the hashring.
The node name of each position (child) is a unique hash which will be used
to determine the appropriate service for the given service (sharding).
In order to route the data (sharding) a hash of the data will be
computed and compared against the hashring position hashes.
The first position to the right of the request or data's hash is the
position responsible for processing the request or data.
The data associated with each hashring position is a service specific
dict of key /values (string) which should contain the details necessary
for the user of the hashring to route their request. The
dict will always contain the service name, port, hostname, and fqdn. Additional
data can be added by services registering positions in the ring.
"""
def __init__(self, zookeeper_client, service_name,
service=None, positions=None, position_data=None):
"""ZookeeperServiceHashring constructor.
Args:
zookeeper_client: zookeeper client instance
service_name: service name, i.e. chatsvc
service: optional Service object which is only required for services
registering positions on the hashring.
positions: optional list of positions to occupy on the
hashring (nodes to create). Each position
must be a 128-bit integer in integer or hex string format.
If None, a randomly generated position will be used.
Note that in the case of a position collision, a
randomly generated position will also be used.
position_data: Dict of additional key /values (string) to store with
the hashring position node.
"""
super(ZookeeperServiceHashring, self).__init__(
service_name=service_name,
service=service,
positions=positions,
position_data=position_data)
self.zookeeper_client = zookeeper_client
self.path = os.path.join("/services", service_name, "hashring")
self.node_data = {}
self.log = logging.getLogger("%s.%s" % (__name__, self.__class__.__name__))
#Determine hashring class based on zookeeper client
if isinstance(self.zookeeper_client, GZookeeperClient):
hashring_class = GHashringWatch
else:
hashring_class = HashringWatch
#Create node data if registering positions
if self.service:
service_info = self.service.info()
self.node_data = {
"service_info": service_info.to_json(),
"data": self.position_data
}
#Create hash ring
self.hashring_watch = hashring_class(
client=self.zookeeper_client,
path=self.path,
positions=self.positions,
position_data=json.dumps(self.node_data),
watch_observer=self._watch_observer,
session_observer=self._session_observer)
self.observers = []
def start(self):
"""Start watching the hashring and register positions if needed."""
self.log.info("Starting ZookeeperServiceHashring ...")
self.hashring_watch.start()
def stop(self):
"""Stop watching the hashring and remove positions if needed."""
self.log.info("Stopping ZookeeperServiceHashring ...")
self.hashring_watch.stop()
def join(self, timeout=None):
"""Join the hashring."""
return self.hashring_watch.join(timeout)
def add_observer(self, method):
"""Add a hashring observer method.
The given method will be invoked with following arguments:
hashring: ServiceHashring object
event: ServiceHashringEvent object
"""
self.observers.append(method)
def remove_observer(self, method):
"""Remove a hashring observer method."""
self.observers.remove(method)
def children(self):
"""Return hashring node's children.
The children node names represent positions on the hashring.
Returns:
dict with the node name as the key and its (data, stat) as its value.
"""
return self.hashring_watch.get_children()
def hashring(self):
"""Return hashring as ordered list of ServiceHashringNode's.
Hashring is represented as an ordered list of ServiceHashringNode's.
The list is ordered by hashring position (ServiceHashringNode.token).
Returns:
Ordered list of ServiceHashringNode's.
"""
nodes = self.hashring_watch.hashring()
return self._convert_hashring_nodes(nodes)
def preference_list(self, data, hashring=None, merge_nodes=True):
"""Return a preference list of ServiceHashringNode's for the given data.
Generates an ordered list of ServiceHashringNode's responsible for
the data. The list is ordered by node preference, where the
first node in the list is the most preferred node to process
the data. Upon failure, lower preference nodes in the list
should be tried.
Note that each service (unique service_key) will only appear
once in the perference list. For each service, The
most preferred ServiceHashringNode will be returned.
Removing duplicate service nodes make the preference
list makes it easier to use for failure retries, and
replication.
Additionally, if the merge_nodes flag is True, each
unique hostname will appear once in the preference
list. The most perferred ServiceHashringNode per
hostname will be returned. This is extremely
useful for replication, since it's often a requirement
that replication nodes be on different servers.
Args:
data: string to hash to find appropriate hashring position.
hashring: Optional list of ServiceHashringNode's for which
to calculate the preference list. If None, the current
hashring will be used.
merge_nodes: Optional flag indicating that each hostname
should only appear once in the preference list. The
most preferred ServiceHashringNode per hostname will
be returned.
Returns:
Preference ordered list of ServiceHashringNode's responsible
for the given data.
"""
if hashring:
hashring = self._unconvert_hashring_nodes(hashring)
nodes = self.hashring_watch.preference_list(data, hashring)
nodes = self._convert_hashring_nodes(nodes)
results = []
keys = {}
hostnames = {}
for node in nodes:
if node.service_info.key not in keys:
if node.service_info.hostname not in hostnames or not merge_nodes:
results.append(node)
hostnames[node.service_info.hostname] = True
keys[node.service_info.key] = True
return results
def find_hashring_node(self, data):
"""Find the hashring node responsible for the given data.
The selected hashring node is determined based on the hash
of the user passed "data". The first node to the
right of the data hash on the hash ring
will be selected.
Args:
data: string to hash to find appropriate hashring position.
Returns:
ServiceHashringNode responsible for the given data.
Raises:
ServiceHashringException if no nodes are available.
"""
nodes = self.preference_list(data)
if nodes:
return nodes[0]
else:
raise ServiceHashringException("no services available (empty hashring)")
def _convert_hashring_nodes(self, hashring_nodes):
"""Convert HashringNode's to ServiceHashringNode's.
Returns:
list of ServiceHashringNode's.
"""
results = []
for node in hashring_nodes or []:
node_data = json.loads(node.data)
service_info = ServiceInfo.from_json(node_data["service_info"])
service_node = ServiceHashringNode(
token=node.token,
service_info = service_info,
data=node_data["data"])
results.append(service_node)
return results
def _unconvert_hashring_nodes(self, hashring_nodes):
"""Convert ServiceHashringNode's to HashringNode's.
Returns:
list of HashringNode's.
"""
results = []
for service_node in hashring_nodes or []:
node_data = {
"service_info": service_node.service_info.to_json(),
"data": service_node.data
}
node = self.hashring_watch.HashringNode(
token=service_node.token,
data=json.dumps(node_data))
results.append(node)
return results
def _watch_observer(self, hashring_watch, previous_hashring,
current_hashring, added_nodes, removed_nodes):
"""Hashring watch observer
Args:
hashring_watch: HashringWatch object
previous_hashring: HashringNode's prior to change
current_hashring: HashringNode's following change
added_nodes: added HashringNode's
removed_nodes: removed HashringNode's
"""
if self.observers:
previous_hashring = self._convert_hashring_nodes(previous_hashring)
current_hashring = self._convert_hashring_nodes(current_hashring)
added_nodes = self._convert_hashring_nodes(added_nodes)
removed_nodes = self._convert_hashring_nodes(removed_nodes)
event = ServiceHashringEvent(
ServiceHashringEvent.CHANGED_EVENT,
previous_hashring,
current_hashring,
added_nodes,
removed_nodes)
for observer in self.observers:
try:
observer(self, event)
except Exception as error:
self.log.exception(error)
def _session_observer(self, event):
"""Hashring watch session observer
Args:
event: Zookeeper.Client object.
"""
if self.observers:
if event.state_name == "CONNECTED_STATE":
event = ServiceHashringEvent(ServiceHashringEvent.CONNECTED_EVENT)
elif event.state_name == "CONNECTING_STATE":
event = ServiceHashringEvent(ServiceHashringEvent.DISCONNECTED_EVENT)
elif event.state_name == "EXPIRED_SESSION_STATE":
event = ServiceHashringEvent(ServiceHashringEvent.DISCONNECTED_EVENT)
else:
self.log.error("unhandled zookeeper event: state=%s" % event.state_name)
return
for observer in self.observers:
try:
observer(self, event)
except Exception as error:
self.log.exception(error)
|
993,647 | c37f07334f36cb94b0abe938379fa3f829713fd2 | A,B,C = map(int,input().split())
ans = A+B+C
if ans <= 21:
print('win')
else:
print('bust') |
993,648 | e59dff5dd9ab61d615b68462a168974478cce9e4 | import logging
from mtg_search.version import __version__
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
|
993,649 | ae5ce8051ab42f8da14cdf818257b5cfb4c90b57 | import time
import io
import sys
import webbrowser
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
from selenium import selenium
import selenium
import csv
from selenium.webdriver.support.ui import Select
import urllib
import re
import os
reload(sys)
sys.setdefaultencoding("UTF8")
browser=webdriver.Firefox()
def searching(product_name,numberOfPage):
browser.get("https://www.google.com/")
box = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, "hplogo")))
#fs = io.open('name.csv', 'a', encoding='utf8')
try:
search=browser.find_element_by_css_selector("div#gs_lc0 input#lst-ib")
product=product_name.replace("_"," ")
re = product + " review"
search.send_keys(re)
except NoSuchElementException:
print "cannot search"
return -1
try:
clicksearch = browser.find_element_by_css_selector("div.jsb center input:nth-child(1)")
clicksearch.click()
except NoSuchElementException:
print "dosen't click search!"
link=[]
for n in range(0, numberOfPage):
box = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, "resultStats")))
result= browser.find_elements_by_css_selector(".r a")
for i in result:
linkProduct = i.get_attribute('href')
#print linkProduct
link.append(linkProduct)
nextnub=browser.find_element_by_css_selector("#pnnext")
nextnub.click()
box = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, "resultStats")))
time.sleep(2)
return link
def openLink(link):
for l in link:
print l
browser.get(l)
time.sleep(4)
html_sources = browser.page_source
time.sleep(4)
getblogs = html_sources.find("blog")
if getblogs==-1:
print "No found"
continue
if "fragrantica" in l:
print "its youtube not blog"
continue
print "Word blog is found"
file_name = product_name+'.txt'
script_dir = os.path.dirname(os.path.abspath(__file__))
dest_dir = os.path.join(script_dir,product_name)
try:
os.makedirs(dest_dir)
except OSError:
pass # already exists
path = os.path.join(dest_dir, file_name)
with open(path, 'a') as stream:
stream.write(l+'\n')
try:
product_name=sys.argv[1]
b=searching(product_name,10)
openLink(b)
browser.quit()
except NoSuchElementException:
browser.quit()
print "Error"
|
993,650 | fec94463636b8d80cef5e934c1981e76470d4d3b |
from flask_restful import Resource, reqparse
#resource is something that our API can return and create, such as student, piano, item, store, ..
# Resources are also mapped into database tables as well
from models.item_model import ItemModel
from flask_jwt import jwt_required
# api is working with resources and every resource has to be a class
class Item(Resource):
parser = reqparse.RequestParser() #that is going to parse the ars that comes through json payload and put the valid ones in data
#We are going to make sure that only some elements can be passed in through the JSON payload
parser.add_argument('price',
type=float,
required=True,
help="This field cannot be left blank!"
) # it will also look at form payload that we won't look at in this course. If you have an HTML form that sens you some data you can use this request parser to go through
# form field as well
parser.add_argument('store_id',
type=int,
required=True,
help="Every item needs store id"
)
@jwt_required()
def get(self, name):
item = ItemModel.find_by_name(name)
if item:
return item.json()
return {'message': 'Item not found'}, 404
def post(self, name):
if ItemModel.find_by_name(name):
return {'message': f"An item with name '{name}' already exists."}, 400
data = Item.parser.parse_args()
item = ItemModel(name, **data)
try:
item.save_to_db()
except:
return {"message": "An error occurred inserting the item."}, 500
return item.json(), 201
def delete(self, name):
item = ItemModel.find_by_name(name)
if item:
item.delete_from_db()
return {'message': f'Item {name} deleted.'}
return {'message': 'Item not found.'}, 404
def put(self, name): # no matter how many times you call it, it will return the output never changes (idempotence)
data = Item.parser.parse_args()
item = ItemModel.find_by_name(name)
if item: #check if the item already exists
item.price = data['price'] # just update the price
else: # if not create a new item
item = ItemModel(name, **data) # inserts the new one
item.save_to_db()
return item.json() # When what we return is an object not a dict, we use .json
class ItemList(Resource):
def get(self):
return {'items': [x.json() for x in ItemModel.query.all()]}
|
993,651 | 6478b4807ea599efc21da6f0b91a8cfb76582f08 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import division
from django.shortcuts import render
from django.shortcuts import redirect
from main.models import Facilities
from main.models import FacOverview
from main.models import Users
from main.models import AccountMoney
from django.db.models import Count
from django.db.models import Sum
from django.db.models import Max
from django.views.decorators.csrf import csrf_exempt
# from django.contrib.auth.hashers import make_password, check_password
import hashlib
import re
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.db import transaction
from datetime import datetime
from django.contrib import messages
date_today = datetime.today().date()
time_now = datetime.now()
def rounder(t):
if t.hour == 6 :
return t.replace(minute=0, hour=6)
elif t.hour == 7:
return t.replace(minute=0, hour=8)
elif t.hour == 8:
return t.replace(minute=0, hour=8)
elif t.hour == 9:
return t.replace(minute=0, hour=10)
elif t.hour == 10:
return t.replace(minute=0, hour=10)
elif t.hour == 11:
return t.replace(minute=0, hour=12)
elif t.hour == 12:
return t.replace(minute=0, hour=12)
elif t.hour == 13:
return t.replace(minute=0, hour=14)
elif t.hour == 14:
return t.replace(minute=0, hour=14)
elif t.hour == 15:
return t.replace(minute=0, hour=16)
elif t.hour == 16:
return t.replace(minute=0, hour=16)
elif t.hour == 17:
return t.replace(minute=0, hour=18)
elif t.hour == 18:
return t.replace(minute=0, hour=18)
else:
return t.replace(minute=0, hour=18)
@csrf_exempt
def login(request):
login_page = True
if "fog" in request.COOKIES.keys():
cookie_value = request.COOKIES['fog']
user_id = re.sub(r"[?<=/]\w*","",cookie_value)
user_value = re.sub(r"\w*[?<=/]","",cookie_value)
users = Users.objects.filter(id_users=user_id)
for i in users:
user_id = i.id_users
if user_value == hashlib.sha1(i.username).hexdigest():
return redirect('/user/'+str(user_id)+'/')
if request.method == 'POST': # POST - to update error row list
username = request.POST['username']
password = request.POST['password']
users = Users.objects.filter(username=username)
if not users:
messages.info(request,'failed', extra_tags='login_username_invalid')
# return HttpResponse("Invalid Username/Password")
return redirect('/login/')
else:
for i in users:
user_id = i.id_users
user_username = i.username
pwd = i.password
if password == pwd :
hex_dig = hashlib.sha1(user_username).hexdigest()
# response = render(request, 'main/login.html')
if user_id == 0:
response = redirect('/admin/')
else:
response = redirect('/user/'+str(user_id)+'/')
response.set_cookie(key='fog',value= str(user_id) + "/" + str(hex_dig), max_age=86400)
# response.cookies['dashboard']['expires'] = datetime.datetime.today() + datetime.timedelta(days=2) #Expire the above 1 day from today.
return response
else:
messages.info(request,'failed', extra_tags='login_pwd_invalid')
# return HttpResponse("Invalid Username/Password")
return redirect('/login/')
context = {
"login_page":login_page
}
return render(request, "main/login.html", context)
# Create your views here.
def index(request, userReceiver):
profile=None
if "fog" not in request.COOKIES.keys():
return redirect("/login")
if "fog" in request.COOKIES.keys():
cookie_value = request.COOKIES['fog']
user_id = re.sub(r"[?<=/]\w*","",cookie_value)
# users = Users.objects.filter(id_users=user_id)
if user_id == userReceiver:
profile = True
else:
profile = False
users = Users.objects.all()
acc_money = AccountMoney.objects.all()
fac_overview = FacOverview.objects.all()
fac = Facilities.objects.all()
# Base + Bar Graph
fac_overview_list = []
fac_name_list = []
for i in fac_overview:
if date_today == i.date:
if i.time == rounder(time_now).strftime("%H%M"):
fac_overview_list.append(i.current_occupancy) # [u'20', u'1', u'1', u'10', u'0']
fac_name = fac.get(facility_id=i.facility_id)
fac_name_list.append(fac_name) # [<QuerySet [{u'facility_name': u'Library'}]>, <QuerySet [{u'facility_name': u'test'}]>...
username = users.get(id_users=userReceiver).username
acc_balance = acc_money.filter(id_account=userReceiver)
if not acc_balance:
acc_balance = 0
else:
acc_balance = acc_money.filter(id_account=userReceiver).values('balance') # <QuerySet [{u'balance': Decimal('32.00')}]>
acc_balance = acc_balance[0]['balance']
qr_image = users.filter(id_users=userReceiver).values('qr_code')
qr_image = qr_image[0]['qr_code']
context = {
#==================== Base ====================
"fac_overview_list":fac_overview_list,
"fac_name_list": fac_name_list,
'user_id': int(user_id),
#==============================================
"users":users,
"username":username,
"userReceiver":userReceiver,
"acc_balance":acc_balance,
"profile":profile,
"qr_image":qr_image
}
return render(request, "main/index.html", context)
# def testScan(request):
# return HttpResponse("Hello World")
def scan(request, userReceiver):
# userId : comes from QR image
# user_id : scanner
# userReceiver : comes from QR image
# userScanner : scanner
userReceiver = userReceiver
# scanner pov | qrcode : /scan/<id_users>
# ==========================================
fac = Facilities.objects.all()
fac_overview = FacOverview.objects.all()
user = Users.objects.all()
time_now = datetime.now()
if "fog" in request.COOKIES.keys():
cookie_value = request.COOKIES['fog']
userScanner = re.sub(r"[?<=/]\w*","",cookie_value)
user_value = re.sub(r"\w*[?<=/]","",cookie_value)
# Get facilities_id
user_fac = user.filter(id_users=userScanner)
user_cookies = user_fac.values('cookies').filter(id_users=userScanner) # library_cookies = 1
if user_cookies[0]['cookies'] == None:
# return HttpResponse("Its a user")
return redirect('/transactions/?receiver=' + str(userReceiver))
else:
# return HttpResponse("Its a facility")
checkUser = user.filter(id_users=userReceiver).values('location')
checkUser = checkUser[0]['location']
if checkUser == None:
# checksIn
time_now = rounder(time_now).strftime("%H%M")
# fac_name = fac.filter(facility_id=user_cookies).values('facility_name').first()
# fac_name = fac_name['facility_id']
facility = fac_overview.filter(facility_id=user_cookies, date=date_today,time=time_now).first() # facility_id = 1
c_occupancy = int(facility.current_occupancy)
fac_id = int(facility.facility_id)
# Update Facilities current_occupancy
fac_update = fac_overview.filter(facility_id=user_cookies, date=date_today,time=time_now).update(current_occupancy=c_occupancy + 1)
# Update Users location
userReceiver_update = user.filter(id_users=userReceiver).update(location=facility.facility_id)
return redirect("/facility/" + str(fac_id) + "/")
else:
#checksOut
time_now = rounder(time_now).strftime("%H%M")
facility = fac_overview.filter(facility_id=user_cookies, date=date_today,time=time_now).first() # facility_id = 1
c_occupancy = int(facility.current_occupancy)
fac_id = int(facility.facility_id)
# Update Facilities current_occupancy
fac_update = fac_overview.filter(facility_id=user_cookies, date=date_today,time=time_now).update(current_occupancy=c_occupancy - 1)
# Update Users location
userReceiver_update = user.filter(id_users=userReceiver).update(location=None)
return redirect("/facility/" + str(fac_id) + "/")
else:
return HttpResponse("Invalid page")
# ==========================================
context = {}
def facility(request, facilityId):
if "fog" in request.COOKIES.keys():
cookie_value = request.COOKIES['fog']
user_id = re.sub(r"[?<=/]\w*","",cookie_value)
user_value = re.sub(r"\w*[?<=/]","",cookie_value)
time_now = datetime.now()
time_now = rounder(time_now).strftime("%H%M")
fac_overview = FacOverview.objects.all()
fac = Facilities.objects.all()
facilityId = int(facilityId)
facility = fac.filter(facility_id=facilityId).first()
facility_name = facility.facility_name
facility_overview = fac_overview.filter(facility_id=facilityId, date=date_today, time=time_now).first()
current_occupancy = int(facility_overview.current_occupancy)
total_occupancy = int(facility_overview.total_occupancy)
empty_occupancy = total_occupancy - current_occupancy
try:
percentage_occupancy = round((current_occupancy/total_occupancy) * 100, 1)
except ZeroDivisionError:
percentage_occupancy = 0
# Base
fac_overview_list = []
fac_name_list = []
for i in fac_overview:
if date_today == i.date:
fac_overview_list.append(i.current_occupancy) # [u'20', u'1', u'1', u'10', u'0']
fac_name = fac.get(facility_id=i.facility_id)
fac_name_list.append(fac_name) # [<QuerySet [{u'facility_name': u'Library'}]>, <QuerySet [{u'facility_name': u'test'}]>...
# Line Graph
fac_overview_line = []
for i in fac_overview:
if i.facility_id == facilityId:
fac_overview_line.append(i)
context = {
#==================== Base ====================
"fac_overview_list":fac_overview_list,
"fac_name_list": fac_name_list,
'user_id':user_id,
#==============================================
"facility_name": facility_name,
"current_occupancy": current_occupancy,
"empty_occupancy": empty_occupancy,
"percentage_occupancy":percentage_occupancy,
"date_today": date_today,
"fac_overview_line": fac_overview_line
}
return render(request, "main/facility.html", context)
def account(request):
context = {
}
return render(request, "main/account.html", context)
@csrf_exempt
def admin(request):
if "fog" in request.COOKIES.keys():
cookie_value = request.COOKIES['fog']
user_id = re.sub(r"[?<=/]\w*","",cookie_value)
user_value = re.sub(r"\w*[?<=/]","",cookie_value)
fac = Facilities.objects.all()
fac_overview = FacOverview.objects.all()
users = Users.objects.all()
acc_money = AccountMoney.objects.all()
date_today = datetime.today().date()
time_now = datetime.now()
time_now = rounder(time_now).strftime("%H%M")
already_exist = None
invalid_input = None
if request.method == 'POST': # POST - to update error row list
if 'fac_id' in request.POST:
fac_id = request.POST['fac_id']
fac_name = request.POST['fac_name']
fac_cap = request.POST['fac_cap']
try:
fac_id = int(fac_id)
fac_name = str(fac_name)
fac_cap = int(fac_cap)
except:
messages.info(request,'failed.', extra_tags='fac_invalid')
return redirect("/admin/")
fac_exist = fac.filter(facility_id=fac_id).first()
if fac_exist:
messages.info(request,'failed.', extra_tags='fac_exist')
else:
# Not yet Exist
fac_add = Facilities(facility_id=fac_id, facility_name=fac_name)
fac_add.save()
# time_list = ["0600","0800","1000","1200","1400","1600","1800"]
# for time in time_list:
# fac_overview_add = FacOverview( date=date_today,time=time,facility_id=7, total_occupancy=20, current_occupancy=0)
# fac_overview_add.save()
FacOverview.objects.bulk_create([
FacOverview( date=date_today,time="0600",facility_id=fac_id, total_occupancy=fac_cap, current_occupancy=0),
FacOverview( date=date_today,time="0800",facility_id=fac_id, total_occupancy=fac_cap, current_occupancy=0),
FacOverview( date=date_today,time="1000",facility_id=fac_id, total_occupancy=fac_cap, current_occupancy=0),
FacOverview( date=date_today,time="1200",facility_id=fac_id, total_occupancy=fac_cap, current_occupancy=0),
FacOverview( date=date_today,time="1400",facility_id=fac_id, total_occupancy=fac_cap, current_occupancy=0),
FacOverview( date=date_today,time="1600",facility_id=fac_id, total_occupancy=fac_cap, current_occupancy=0),
FacOverview( date=date_today,time="1800",facility_id=fac_id, total_occupancy=fac_cap, current_occupancy=0),
])
# run default script for FacOverview. check if else condition.
messages.success(request,'success', extra_tags='fac_add')
return redirect("/admin/")
if 'delete_fac' in request.POST:
fac_id = int(request.POST['delete_fac']) #{{facility_id}}
try:
fac_remove = fac.get(facility_id=fac_id)
fac_remove.delete()
fac_overview_remove = fac_overview.filter(facility_id=fac_id)
fac_overview_remove.delete()
messages.success(request,'success', extra_tags='fac_remove')
except:
messages.info(request,'failed.', extra_tags='fac_remove_fail')
return redirect("/admin/") # somehow after redirecting, i still cannot unset post request
if 'fund_acc' in request.POST:
# if request.POST['fund_acc']
try:
fund_user = acc_money.filter(id_account=request.POST['fund_acc'])
fund_update = fund_user.update(balance=int(fund_user[0].balance) + int(request.POST['fund_amount']))
messages.success(request,'success.', extra_tags='fund_success')
except Exception as e:
messages.success(request,'success.', extra_tags='fund_fail')
return redirect("/admin/")
if 'new_acc' in request.POST:
try:
new_user = users.filter(id_users=request.POST['new_acc']).first()
if new_user == None:
new_user_add = Users(id_users=request.POST['new_acc'], username=request.POST['new_username'], password=request.POST['new_password'], email=request.POST['new_email'], qr_code=request.POST['new_qrcode'])
# new_user_add = Users(id_users=5, username="asd", password="asdsdd", email="dasfsd", qr_code="asdasdcxv")
new_user_add.save()
new_balance_add = AccountMoney(id_account=request.POST['new_acc'], balance=0)
new_balance_add.save()
messages.success(request,'success.', extra_tags='new_user_success')
else:
messages.info(request,'failed.', extra_tags='new_user_fail')
except Exception as e:
messages.success(request,'success.', extra_tags='new_user_success')
return redirect("/admin/")
if 'delete_user' in request.POST:
del_user_id = int(request.POST['delete_user'])
try:
user_remove = users.get(id_users=del_user_id)
user_remove.delete()
balance_remove = acc_money.get(id_account=del_user_id)
balance_remove.delete()
messages.success(request, 'success.' , extra_tags='del_user_success')
except:
messages.info(request,'failed.', extra_tags='del_user_fail')
return redirect("/admin/") # somehow after redirecting, i still cannot unset post request
return redirect("/admin/")
# Base
fac_overview_list = []
fac_name_list = []
for i in fac_overview:
if date_today == i.date:
if i.time == time_now:
fac_overview_list.append(i.current_occupancy) # [u'20', u'1', u'1', u'10', u'0']
fac_name = fac.get(facility_id=i.facility_id)
fac_name_list.append(fac_name) # [<QuerySet [{u'facility_name': u'Library'}]>, <QuerySet [{u'facility_name': u'test'}]>...
# Line Graph
date_list = []
c_occ_list = []
date_distinct = fac_overview.values('date').distinct()
for i in date_distinct:
date_list.append(i['date'])
for i in fac_overview:
x = 0
c = fac_overview.filter(facility_id=i.facility_id, date=date_list[x+1]).aggregate(Max('current_occupancy'))
c_occ_list.append(c)
context = {
"fac":fac,
"fac_overview": fac_overview,
"users":users,
#==================== Base ====================
"fac_overview_list":fac_overview_list,
"fac_name_list": fac_name_list,
'user_id':user_id,
#==============================================
"already_exist":already_exist,
"invalid_input": invalid_input,
"date_today":date_today,
"time_now":time_now,
"date_list":date_list,
"c_occ_list":c_occ_list,
}
return render(request, "main/admin.html", context)
# def user(request, userId):
# userId = userId
# fac = FacOverview.objects.all()
# library_current = fac.get(facility_id=1)
# library_current = library_current.current_occupancy
# library_update = fac.filter(facility_id=1).update(current_occupancy=library_current+1)
# return redirect("/library")
@csrf_exempt
def transactions(request):
# userReceiver : comes from QR image
# userScanner : scanner [cookies]
# use cookies as user and scan qr code as receiver.
user = Users.objects.all()
acc_money = AccountMoney.objects.all()
if "fog" in request.COOKIES.keys():
cookie_value = request.COOKIES['fog']
userScanner = re.sub(r"[?<=/]\w*","",cookie_value)
user_id = userScanner
user_value = re.sub(r"\w*[?<=/]","",cookie_value)
userScanner = user.get(id_users=userScanner)
userScanner = userScanner.id_users
else:
redirect('/login')
try:
userReceiver = request.GET.get('receiver')
userReceiver = user.get(id_users=userReceiver)
userReceiver = userReceiver.id_users
except ValueError:
userReceiver = None
invalid_input = None
invalid_user = None
userScanner_balance = int(acc_money.get(id_account=userScanner).balance)
if request.method == 'POST':
userScanner = request.POST['userScanner']
userReceiver = request.POST['userReceiver']
amount = request.POST['amount']
try:
amount = int(amount)
reference = request.POST['reference']
try:
userScanner_balance = int(acc_money.get(id_account=userScanner).balance)
if userScanner_balance < amount:
messages.info(request,'failed.', extra_tags='transactions_insufficient')
return redirect('/transactions/?receiver=' + str(userReceiver))
userScanner_update = acc_money.filter(id_account=userScanner).update(balance=userScanner_balance - amount)
userReceiver_balance = int(acc_money.get(id_account=userReceiver).balance)
userReceiver_update = acc_money.filter(id_account=userReceiver).update(balance=userReceiver_balance + amount)
messages.success(request,'success.', extra_tags='transactions_success')
return redirect('/user/'+str(userScanner)+'/')
except:
invalid_user = True
except:
invalid_input = True
# context = {
# "userReceiver":userReceiver,
# "userScanner": userScanner,
# "invalid_input":invalid_input
# }
# return render(request, "main/transactions.html", context)
fac = Facilities.objects.all()
fac_overview = FacOverview.objects.all()
# Base
fac_overview_list = []
fac_name_list = []
for i in fac_overview:
if date_today == i.date:
if i.time == rounder(time_now).strftime("%H%M"):
fac_overview_list.append(i.current_occupancy) # [u'20', u'1', u'1', u'10', u'0']
fac_name = fac.get(facility_id=i.facility_id)
fac_name_list.append(fac_name) # [<QuerySet [{u'facility_name': u'Library'}]>, <QuerySet [{u'facility_name': u'test'}]>...
context = {
"userReceiver":userReceiver,
"userScanner": userScanner,
'user_id':user_id,
"userScanner_balance":userScanner_balance,
"invalid_input":invalid_input,
"invalid_user":invalid_user,
#==================== Base ====================
"fac_overview_list":fac_overview_list,
"fac_name_list": fac_name_list,
#==============================================
}
return render(request, "main/transactions.html", context)
|
993,652 | b31681385a9af653a8ed52bba9c7f7b686d84198 | from PIL import Image, ImageOps, ImageFilter
import torchvision.transforms as transforms
import random
'''
#####
Adapted from https://github.com/facebookresearch/barlowtwins
#####
'''
class GaussianBlur(object):
def __init__(self, p):
self.p = p
def __call__(self, img):
if random.random() < self.p:
sigma = random.random() * 1.9 + 0.1
return img.filter(ImageFilter.GaussianBlur(sigma))
else:
return img
class Solarization(object):
def __init__(self, p):
self.p = p
def __call__(self, img):
if random.random() < self.p:
return ImageOps.solarize(img)
else:
return img
class Transform:
def __init__(self, transform=None, transform_prime=None):
'''
:param transform: Transforms to be applied to first input
:param transform_prime: transforms to be applied to second
'''
if transform == None:
self.transform = transforms.Compose([
transforms.RandomResizedCrop(224, interpolation=Image.BICUBIC),
transforms.RandomHorizontalFlip(p=0.5),
transforms.RandomApply(
[transforms.ColorJitter(brightness=0.4, contrast=0.4,
saturation=0.2, hue=0.1)],
p=0.8
),
transforms.RandomGrayscale(p=0.2),
GaussianBlur(p=1.0),
Solarization(p=0.0),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
else:
self.transform = transform
if transform_prime == None:
self.transform_prime = transforms.Compose([
transforms.RandomResizedCrop(224, interpolation=Image.BICUBIC),
transforms.RandomHorizontalFlip(p=0.5),
transforms.RandomApply(
[transforms.ColorJitter(brightness=0.4, contrast=0.4,
saturation=0.2, hue=0.1)],
p=0.8
),
transforms.RandomGrayscale(p=0.2),
GaussianBlur(p=0.1),
Solarization(p=0.2),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
else:
self.transform_prime = transform_prime
def __call__(self, x):
y1 = self.transform(x)
y2 = self.transform_prime(x)
return y1, y2 |
993,653 | 93a5a7494690c6219e7c1ecf872ea97b41592358 | import logging
import os
from pathlib import Path
from typing import List, TypeVar
import numpy as np
from tqdm import tqdm
from jmetal.core.observer import Observer
from jmetal.core.problem import DynamicProblem
from jmetal.core.quality_indicator import InvertedGenerationalDistance
from jmetal.lab.visualization import Plot, StreamingPlot
from jmetal.util.solution import print_function_values_to_file
S = TypeVar("S")
LOGGER = logging.getLogger("jmetal")
"""
.. module:: observer
:platform: Unix, Windows
:synopsis: Implementation of algorithm's observers.
.. moduleauthor:: Antonio J. Nebro <antonio@lcc.uma.es>
"""
class ProgressBarObserver(Observer):
def __init__(self, max: int) -> None:
"""Show a smart progress meter with the number of evaluations and computing time.
:param max: Number of expected iterations.
"""
self.progress_bar = None
self.progress = 0
self._max = max
def update(self, *args, **kwargs):
if not self.progress_bar:
self.progress_bar = tqdm(total=self._max, ascii=True, desc="Progress")
evaluations = kwargs["EVALUATIONS"]
self.progress_bar.update(evaluations - self.progress)
self.progress = evaluations
if self.progress >= self._max:
self.progress_bar.close()
class BasicObserver(Observer):
def __init__(self, frequency: int = 1) -> None:
"""Show the number of evaluations, the best fitness and the computing time.
:param frequency: Display frequency."""
self.display_frequency = frequency
def update(self, *args, **kwargs):
computing_time = kwargs["COMPUTING_TIME"]
evaluations = kwargs["EVALUATIONS"]
solutions = kwargs["SOLUTIONS"]
if (evaluations % self.display_frequency) == 0 and solutions:
if type(solutions) == list:
fitness = solutions[0].objectives
else:
fitness = solutions.objectives
LOGGER.info(
"Evaluations: {} \n Best fitness: {} \n Computing time: {}".format(evaluations, fitness, computing_time)
)
class PrintObjectivesObserver(Observer):
def __init__(self, frequency: int = 1) -> None:
"""Show the number of evaluations, best fitness and computing time.
:param frequency: Display frequency."""
self.display_frequency = frequency
def update(self, *args, **kwargs):
evaluations = kwargs["EVALUATIONS"]
solutions = kwargs["SOLUTIONS"]
if (evaluations % self.display_frequency) == 0 and solutions:
if type(solutions) == list:
fitness = solutions[0].objectives
else:
fitness = solutions.objectives
LOGGER.info("Evaluations: {}. fitness: {}".format(evaluations, fitness))
class WriteFrontToFileObserver(Observer):
def __init__(self, output_directory: str) -> None:
"""Write function values of the front into files.
:param output_directory: Output directory. Each front will be saved on a file `FUN.x`."""
self.counter = 0
self.directory = output_directory
if Path(self.directory).is_dir():
LOGGER.warning("Directory {} exists. Removing contents.".format(self.directory))
for file in os.listdir(self.directory):
os.remove("{0}/{1}".format(self.directory, file))
else:
LOGGER.warning("Directory {} does not exist. Creating it.".format(self.directory))
Path(self.directory).mkdir(parents=True)
def update(self, *args, **kwargs):
problem = kwargs["PROBLEM"]
solutions = kwargs["SOLUTIONS"]
if solutions:
if isinstance(problem, DynamicProblem):
termination_criterion_is_met = kwargs.get("TERMINATION_CRITERIA_IS_MET", None)
if termination_criterion_is_met:
print_function_values_to_file(solutions, "{}/FUN.{}".format(self.directory, self.counter))
self.counter += 1
else:
print_function_values_to_file(solutions, "{}/FUN.{}".format(self.directory, self.counter))
self.counter += 1
class PlotFrontToFileObserver(Observer):
def __init__(self, output_directory: str, step: int = 100, **kwargs) -> None:
"""Plot and save Pareto front approximations into files.
:param output_directory: Output directory.
"""
self.directory = output_directory
self.plot_front = Plot(title="Pareto front approximation", **kwargs)
self.last_front = []
self.fronts = []
self.counter = 0
self.step = step
if Path(self.directory).is_dir():
LOGGER.warning("Directory {} exists. Removing contents.".format(self.directory))
for file in os.listdir(self.directory):
os.remove("{0}/{1}".format(self.directory, file))
else:
LOGGER.warning("Directory {} does not exist. Creating it.".format(self.directory))
Path(self.directory).mkdir(parents=True)
def update(self, *args, **kwargs):
problem = kwargs["PROBLEM"]
solutions = kwargs["SOLUTIONS"]
evaluations = kwargs["EVALUATIONS"]
if solutions:
if (evaluations % self.step) == 0:
if isinstance(problem, DynamicProblem):
termination_criterion_is_met = kwargs.get("TERMINATION_CRITERIA_IS_MET", None)
if termination_criterion_is_met:
if self.counter > 0:
igd = InvertedGenerationalDistance(np.array([s.objectives for s in self.last_front]))
igd_value = igd.compute(np.array([s.objectives for s in solutions]))
else:
igd_value = 1
if igd_value > 0.005:
self.fronts += solutions
self.plot_front.plot(
[self.fronts],
label=problem.get_name(),
filename=f"{self.directory}/front-{evaluations}",
)
self.counter += 1
self.last_front = solutions
else:
self.plot_front.plot(
[solutions],
label=f"{evaluations} evaluations",
filename=f"{self.directory}/front-{evaluations}",
)
self.counter += 1
class VisualizerObserver(Observer):
def __init__(
self, reference_front: List[S] = None, reference_point: list = None, display_frequency: int = 1
) -> None:
self.figure = None
self.display_frequency = display_frequency
self.reference_point = reference_point
self.reference_front = reference_front
def update(self, *args, **kwargs):
evaluations = kwargs["EVALUATIONS"]
solutions = kwargs["SOLUTIONS"]
if solutions:
if self.figure is None:
self.figure = StreamingPlot(reference_point=self.reference_point, reference_front=self.reference_front)
self.figure.plot(solutions)
if (evaluations % self.display_frequency) == 0:
# check if reference point has changed
reference_point = kwargs.get("REFERENCE_POINT", None)
if reference_point:
self.reference_point = reference_point
self.figure.update(solutions, reference_point)
else:
self.figure.update(solutions)
self.figure.ax.set_title("Eval: {}".format(evaluations), fontsize=13)
|
993,654 | 9f8bce39c463818651596c31c56b383910a264d9 | import torch
import random
from nltk.translate.bleu_score import corpus_bleu
from model.visualization import Visualization
def evaluate(model, test_loader, vocab, device, epoch):
model.eval()
total_loss = 0.
with torch.no_grad():
for idx, batch in enumerate(iter(test_loader)):
img, target = batch
img = img.to(device)
target = target.to(device)
sentence_s = []
target_s = []
sentences = []
attention_w = []
for i in range(img.shape[0]):
sentence, attention_w_t = model.inference(image=img[i].unsqueeze(0))
sentence_s=sentence.split(' ')
sentence_s.append('<END>')
sentences.append(sentence_s)
target_s.append(vocab.generate_caption(target[i,1:]).split(' '))
attention_w.append(attention_w_t)
total_loss += corpus_bleu(target_s,sentences,(1.0/1.0,))
if idx % 10 == 0:
num_img=random.randint(0,img.shape[0]-1)
example=' '.join(sentences[num_img])
reference=vocab.generate_caption(target[num_img,1:])
print(f'Evaluating batch {idx} / {len(test_loader)}...')
print(f'Gen example: {example}')
print(f'Exp example: {reference}')
string=str(num_img)+'_epoch_'+str(epoch)+'_plot.png'
string_att=str(num_img)+'_epoch_'+str(epoch)+'_plot_att.png'
Visualization.show_image(img[num_img],title=example,fn=string)
Visualization.plot_attention(img[num_img],sentences[num_img][:-1],attention_w[num_img],fn=string_att)
return total_loss / (idx+1)
|
993,655 | a244e75cfe105f1e9f7fdd2a8be893351520e726 | # FlagsTracksDefault.py
# (C)2014
# Scott Ernst
from __future__ import print_function, absolute_import, unicode_literals, division
import sqlalchemy as sqla
from pyglass.sqlalchemy.PyGlassModelsDefault import PyGlassModelsDefault
from pyglass.sqlalchemy.ConcretePyGlassModelsMeta import ConcretePyGlassModelsMeta
import six
#___________________________________________________________________________________________________ FlagsTracksDefault
@six.add_metaclass(ConcretePyGlassModelsMeta)
class FlagsTracksDefault(PyGlassModelsDefault):
#===================================================================================================
# C L A S S
__abstract__ = True
_flags = sqla.Column(sqla.Integer, default=0)
_sourceFlags = sqla.Column(sqla.Integer, default=0)
_displayFlags = sqla.Column(sqla.Integer, default=0)
_importFlags = sqla.Column(sqla.Integer, default=0)
_analysisFlags = sqla.Column(sqla.Integer, default=0)
|
993,656 | 7bede769a48a7fe4d0d7f4d33b9dad66a9c39b57 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 5 19:55:18 2021
"""
from tkinter import *
from tkinter.ttk import *
import tkinter.scrolledtext as st
import aiml
import os
import gtts
from gtts import *
import pyttsx3
import webbrowser
from playsound import playsound
def start_GUI():
def send_msg():
chat_area.config(state = NORMAL)
sent_message = bot_input.get()
bot_input.set("")
#print(sent_message)
chat_area.insert(INSERT,"You: "+ sent_message)
res = str(kernal.respond(sent_message))
#print(res)
output = ""
if res == "?!!" or res == "?!":
import requests
from bs4 import BeautifulSoup
if res == "?!!":
URL = "https://www.worldometers.info/coronavirus/country/india/"
elif res == "?!":
URL = "https://www.worldometers.info/coronavirus/"
r = requests.get(URL)
soup = BeautifulSoup(r.content,'html5lib')
n1 = soup.find('div',attrs = {'class':'container'})
n2 = n1.find_all_next('div',attrs = {'class' : 'row'})
n3 = n2[0].find_all_next('div',attrs = {'class':'col-md-8'})
n4 = n3[0].find_all_next('div',attrs = {'class':'content-inner'})
num5 = n4[0].find_all_next('div',attrs = {'id':'maincounter-wrap'})
conf = (num5[0].find_all_next('div',attrs = {'class':'maincounter-number'}))
confirm = ""
for i in conf[0].span.text:
if i == ',':
continue
else:
confirm = confirm + i
#chat_area.insert(INSERT,"\nBOT: Active Cases: " + cases[0].span.text + "\n")
conf_cases = int(confirm)
de = num5[1].find_all_next('div',attrs = {'class':'maincounter-number'})
deaths = de[0].span.text
#chat_area.insert(INSERT,"Deaths: "+ deaths[0].span.text+"\n")
recov = (num5[2].find_all_next('div',attrs = {'class':'maincounter-number'}))
recover = ""
for i in recov[0].span.text:
if i == ',':
continue
else:
recover += i
recoveries = int(recover)
active_cases = conf_cases - recoveries
active = str(active_cases)
output = "Confirmed Cases: " + conf[0].span.text +"\nActive Cases: " + active + " \nDeaths: " + deaths + " \nRecoveries: " + recover
chat_area.insert(INSERT,"\nBOT: "+ output + "\n\n")
#chat_area.insert(INSERT,"Recoveries: " + rec[0].span.text + "\n")
#print(soup.prettify())
#print(numbers)
elif res[0] == 's' and res[1] == 's':
search = ""
output = "Redirecting to your default browser"
chat_area.insert(INSERT,"\nBOT: Redirecting to your default browser\n\n")
for i in range(2,len(res)):
search += res[i]
webbrowser.open_new_tab(search)
else:
output = res
#webbrowser.open_new_tab('http://www.python.org')
chat_area.insert(INSERT,"\nBOT: " + res +"\n\n")
#chat_area.focus()
sound = gtts.gTTS(text = output,lang = 'en',slow = False)
#mp3_fp = BytesIO()
#sound.write_to_fp(mp3_fp)
sound.save("speak.mp3")
#os.system("start speak.mp3")
#os.system("taskkill /im speak.mp3 /f")
"""engine = pyttsx3.init()
engine.connect('started')
engine.say(output)
engine.runAndWait()"""
playsound("speak.mp3")
os.remove("speak.mp3")
chat_area.config(state = DISABLED)
"""
base = Tk()
base.title("CoBot 1.0")
bot_input = StringVar()
base.geometry('500x500')
heading = Label(base,text = "Welcome to CoBot",font = "25",foreground = "red").pack()
msg = Message(base,text = "ChatBot to answer Covid related queries",justify = "center",foreground = "blue").pack()
inp_entry = Entry(base,textvariable = bot_input).place(x = 220, y = 400)
send = Button(base,text = "Send",command = lambda : send_msg()).place(x = 350,y = 400 )
send_lab = Label(base,text = "Enter your query here:",font =("Italics",12)).place(x = 50,y = 400)
chat_area = st.ScrolledText(base,width = 30,height = 12,font = ("Times New Roman",15))
chat_area.config(state = DISABLED)
chat_area.place(x = 100,y = 100)
base.mainloop()"""
base = Tk()
base.title("COBOT 2.0")
bot_input = StringVar()
base.resizable(width = False,height = False)
base.configure(width = 470,height = 550,bg = "#17202A")
head = Label(base,text = "Welcome to CoBot !",font = ("helvetica",15),foreground = "orange",background ="#17202A" )
head.place(x =230,y = 30, anchor= CENTER)
footer = LabelFrame(base,borderwidth= 5,width= 450,height = 70).place(x = 10,y = 458)
send = Button(footer,text="Send",command = lambda: send_msg(),width = 10)
#send.config(font= ("helvetica" ,10, "bold"))
send.place(relheight = 0.09,x = 370,y = 468)
entrymsg = Entry(base,textvariable = bot_input ,font = ("Helvetica",15))
entrymsg.focus()
entrymsg.place(in_= footer,relwidth = 0.74, relheight = 0.09, y = 468, x = 20 )
chat_area = Text(base,width = 20,height = 2,bg = "indigo",fg = "#EAECEE",font = "Helvetica 14",padx = 5,pady = 5)
chat_area.place(relheight = 0.745,relwidth = 1,rely = 0.08)
chat_area.config(cursor= "arrow")
scroll = Scrollbar(chat_area)
scroll.config(command= chat_area.yview)
scroll.place(relheight=1,relx = 0.98)
#chat_area.insert(INSERT,"BOT: HELLO TESTING")
#chat_area.insert(INSERT,"\nTesting again")
chat_area.config(state = DISABLED)
copyr = Label(base,text = "By Team PRO_fessors",font = ("Times New Roman",10),foreground= "red",background="#17202A")
copyr.place(x = 150,y = 530)
base.mainloop()
kernal = aiml.Kernel()
#kernal.learn("startup.xml")
#kernal.learn("*.aiml.xml")
if os.path.isfile("bot_brain2.brn"):
kernal.bootstrap(brainFile = "bot_brain2.brn")
else:
kernal.bootstrap(learnFiles = "startup.xml",commands =["load aiml a","load aiml b"] )
kernal.saveBrain("bot_brain2.brn")
start_GUI()
|
993,657 | 0cfca8ab721243293628a95f38eb1d8854c16f67 | from sqlalchemy import create_engine, func
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Restaurant, MenuItem
engine = create_engine("sqlite:///restaurantmenu.db")
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
#myFirstRestaurant = Restaurant(name = "Pizza Palace")
#session.add(myFirstRestaurant)
#session.commit()
for line in session.query(Restaurant):
print line.id, line.name
#cheesepizza = MenuItem(name="Cheese Pizza", description = "Made with all natural ingredients and fresh mozzarella", course="Entree", price="$8.99",
# restaurant=myFirstRestaurant)
#session.add(cheesepizza)
#session.commit()
r = session.query(Restaurant).filter_by(name = "Boneheads").one()
i = MenuItem(name="Mushroom Burger", restaurant = r)
#session.add(i)
#session.commit()
for line in session.query(MenuItem):
print line.id, line.name
|
993,658 | df50af78e5648e5f85a18b66457cdb33f553ab28 | # -*- coding: utf-8 -*-
from cobra.core.loading import is_model_registered
from .abstract_models import * # noqa
__all__ = []
if not is_model_registered('accessgroup', 'AccessGroup'):
class AccessGroup(AbstractAccessGroup):
pass
__all__.append('AccessGroup')
|
993,659 | 7ef52e92b06600c3bca77d7689fd31b3b2af6323 | # coding=utf-8
'''
Created on 13 Feb 2018
@author: Administrator
'''
class Solution:
def swimInWater(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
import heapq
visited = {(0, 0)}
q = [(grid[0][0], 0, 0)]
ans = 0
N = len(grid)
while q:
elevation, r, c = heapq.heappop(q)
ans = max(ans, elevation)
if (r, c) == (N - 1, N - 1):
return ans
for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):
r0, c0 = r + dx, c + dy
if 0 <= r0 < N and 0 <= c0 < N and (r0, c0) not in visited:
heapq.heappush(q, (grid[r0][c0], r0, c0))
visited.add((r0, c0))
grid = [[0, 2], [1, 3]]
print(Solution().swimInWater(grid))
|
993,660 | b819c8707508d9dbdde42b2d94e368a1a424f066 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 3 16:45:01 2018
@author: Dartoon
"""
import numpy as np
import astropy.io.fits as pyfits
import matplotlib.pyplot as plt
import pickle
import copy
import matplotlib as matt
import matplotlib.lines as mlines
from matplotlib import colors
matt.rcParams['font.family'] = 'STIXGeneral'
filt_info = {'CDFS-1': 'F140w', 'CDFS-229': 'F125w', 'CDFS-724': 'F125w',\
'CID1174': 'F140w', 'CID206': 'F140w', 'CID216': 'F140w', 'CID3242': 'F140w',\
'CID3570': 'F125w', 'CID452': 'F125w', 'CID454': 'F140w', 'CID50': 'F125w',\
'CID607': 'F125w', 'CID70': 'F140w', 'LID1273': 'F140w', 'LID360': 'F140w',\
'XID2138': 'F140w', 'XID2202': 'F140w', 'XID2396': 'F140w', 'ECDFS-358': 'F140w',\
'SXDS-X1136': 'F125w', 'SXDS-X50': 'F125w', 'SXDS-X735': 'F140w',\
'CID543': 'F125w', 'LID1538': 'F140w', 'CID237': 'F140w', 'SXDS-X717': 'F125w',\
'SXDS-X763': 'F125w', 'SXDS-X969': 'F140w', 'CDFS-321': 'F140w',
'CID1281': 'F140w', 'CID597':'F125w'\
}
PSFs_dict = {}
QSOs_dict = {}
for key in filt_info.keys():
ID = key
PSFs, QSOs=pickle.load(open('{0}/analysis/{0}_PSFs_QSO'.format(ID),'rb'))
PSFs_dict.update({'{0}'.format(ID):PSFs})
QSOs_dict.update({'{0}'.format(ID):QSOs})
PSF_list = []
PSF_id = []
QSO_list = []
filter_list = []
IDs = PSFs_dict.keys()
for ID in IDs:
psfs_dict = PSFs_dict[ID]
psfs = [psfs_dict[i] for i in range(len(psfs_dict))]
PSF_list += psfs
name_id = [ID+"_"+str(i) for i in range(len(psfs_dict))]
PSF_id = PSF_id + name_id
filt = [filt_info[ID]]
filter_list += filt * len(PSFs_dict[ID])
qso = QSOs_dict[ID]
QSO_list.append(qso)
if len(PSF_list) != len(PSF_id):
raise ValueError("The PSF_list is not consistent with PSF_id")
QSO_id = IDs
#==============================================================================
#Plot the flux distribution
#==============================================================================
fluxs = []
locs = []
id_star_s = []
for i in range(len(QSO_id)):
PSFs = [PSF_list[j] for j in range(len(PSF_list)) if QSO_id[i] in PSF_id[j]]
# print len(PSFs)
flux = [np.sum(PSFs[j][0] * PSFs[j][3]) for j in range(len(PSFs))]
fluxs += flux
loc = [PSFs[j][2] for j in range(len(PSFs))]
locs += loc
id_star = [PSFs[j][1] for j in range(len(PSFs))]
id_star_s += id_star
plt.figure(figsize=(10,6))
common_params = dict(bins=30)
# label=QSO_id)
plt.hist((fluxs), **common_params)
plt.legend()
plt.xticks(np.arange(0, 4500, step=500))
plt.yticks(np.arange(0,40,step=5))
plt.xlabel('Total Flux (counts)',fontsize=15)
plt.ylabel('Number of PSFs', fontsize=15)
plt.tick_params(labelsize=15)
plt.show()
#==============================================================================
#Location
#==============================================================================
#temp_frame = pyfits.getdata('CDFS-1/astrodrz/final_drz.fits')
frame_y, frame_x = (2183, 2467) #temp_frame.shape
x_len = 15.
ratio = x_len/frame_x
y_len = frame_y * ratio
#fig, ax= plt.subplots(1)
plt.figure(figsize=(x_len,y_len))
color_label = copy.deepcopy(QSO_id)
for i in range(len(QSO_id)):
loc = QSO_list[i][1]
plt.plot(loc[0]*ratio, loc[1]*ratio, marker='X', label = color_label[i], ms = 20, linestyle = 'None')
color_label[i] = "_nolegend_"
PSFs = [PSF_list[j] for j in range(len(PSF_list)) if QSO_id[i] in PSF_id[j]]
for j in range(len(PSFs)):
loc = PSFs[j][2]
if PSFs[j][1] == 1:
plt.plot(loc[0]*ratio, loc[1]*ratio, marker='*', ms = 10, linestyle = 'None')
elif PSFs[j][1] == 0:
plt.plot(loc[0]*ratio, loc[1]*ratio, marker='o', ms = 7, linestyle = 'None')
dith_fx, dith_fy = (2128,1916)
dith_fx *= ratio
dith_fy *= ratio
box_wx, box_wy = dith_fx, dith_fy
dx = (x_len-dith_fx)/5
dy = (y_len-dith_fy)/5
for i in range(6):
rectangle = plt.Rectangle((dx*i, dy*i), box_wx, box_wy, fill=None, alpha=1)
plt.gca().add_patch(rectangle)
plt.tick_params(labelsize=20)
plt.legend(bbox_to_anchor=(0.97, 1.14),prop={'size': 12},ncol=7)
plt.xticks([]),plt.yticks([])
plt.xlim(0, x_len)
plt.ylim(0, y_len)
plt.show()
##==============================================================================
## Plot mask
##==============================================================================
#from matplotlib.colors import LogNorm
#ncols = 3
#nrows = 3
#count = 0
#import math
#ceils = math.ceil(len(PSF_list)/9.)
#for k in range(int(ceils)):
# fig, axs = plt.subplots(ncols=ncols, nrows=nrows, figsize=(9,9))
# for i in range(ncols):
# for j in range(nrows):
# if count < len(PSF_list) :
# axs[i,j].imshow(PSF_list[count][0]*PSF_list[count][3], origin='low', norm=LogNorm())
# t = axs[i,j].text(5,110,PSF_id[count], {'color': 'b', 'fontsize': 20})
# t.set_bbox(dict(facecolor='yellow', alpha=0.5, edgecolor='red'))
# if PSF_list[count][1] ==1:
# t1 = axs[i,j].text(100,5,'star', {'color': 'b', 'fontsize': 10})
# t1.set_bbox(dict(facecolor='yellow', alpha=0.5, edgecolor='red'))
# axs[i,j].set_xticks([])
# axs[i,j].set_yticks([])
# count += 1
# plt.tight_layout()
# plt.show()
#==============================================================================
# Gaussian Fit
#==============================================================================
from scipy.optimize import curve_fit
test_data = PSF_list[0][0]
center = len(test_data)/2
#def func(x, a, x0, sigma):
# return a*np.exp(-(x-x0)**2/(2*sigma**2))
def measure_FWHM(image,count=0 ,line_range= (50,70)):
seed = range(line_range[0],line_range[1])
frm = len(image)
q_frm = frm/4
center = np.where(image == image[q_frm:-q_frm,q_frm:-q_frm].max())[0][0]
x_n = np.asarray([image[i][center] for i in seed]) # The x value, vertcial
y_n = np.asarray([image[center][i] for i in seed]) # The y value, horizontal
#popt, pcov = curve_fit(func, x, yn)
from astropy.modeling import models, fitting
g_init = models.Gaussian1D(amplitude=1., mean=60, stddev=1.)
fit_g = fitting.LevMarLSQFitter()
g_x = fit_g(g_init, seed, x_n)
g_y = fit_g(g_init, seed, y_n)
FWHM_ver = g_x.stddev.value * 2.355 # The FWHM = 2*np.sqrt(2*np.log(2)) * stdd = 2.355*stdd
FWHM_hor = g_y.stddev.value * 2.355
if (FWHM_hor-FWHM_ver)/FWHM_ver > 0.20:
print "Warning, the {0} have inconsistent FWHM".format(count), FWHM_ver, FWHM_hor
# fig = plt.figure()
# ax = fig.add_subplot(111)
# seed = np.linspace(seed.min(),seed.max(),50)
# ax.plot(seed, g_x(seed), c='r', label='Gaussian')
# ax.legend()
# ax.scatter(x, sample)
# plt.show()
return (FWHM_ver+FWHM_hor)/2., FWHM_ver, FWHM_hor
FWHM = []
for i in range(len(PSF_list)):
FWHM_i = measure_FWHM(PSF_list[i][0], count = i)[0]
FWHM.append(FWHM_i)
FWHM = np.asarray(FWHM)
fig, ax = plt.subplots(figsize=(10,6))
color_dict = {"F140w": 'b', "F125w": 'g'}
label = {"F140w1":'F140w star', "F140w0":'F140w selected', "F125w1":'F125w star', "F125w0":'F125w selected'}
marker = {1:'*', 0:'o'}
for i in range(len(FWHM)):
filt = filter_list[i]
label_key = filt + str(PSF_list[i][1])
ax.scatter(FWHM[i], fluxs[i], color =color_dict[filt], label = label[label_key], marker=marker[PSF_list[i][1]])
label[label_key] = "_nolegend_"
import matplotlib
ax.set_yscale('log')
ax.set_yticks([50,100, 200, 300, 500, 1000, 2000, 5000])
ax.get_yaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
plt.xlabel('FWHM (pixel)',fontsize=15)
plt.ylabel('Total flux', fontsize=15)
plt.legend(prop={'size': 12})
plt.tick_params(labelsize=15)
plt.ylim(30,6000)
plt.show()
flux_dict, FWHM_dict, locs_dict, filter_dict, id_stars_dict = {}, {}, {}, {}, {}
for i in range(len(PSF_list)):
if filter_list[i] == 'F140w':
print PSF_id[i], round(fluxs[i],3), round(FWHM[i],3), locs[i], filter_list[i], id_star_s[i]
flux_dict.update({PSF_id[i]:fluxs[i]})
FWHM_dict.update({PSF_id[i]:FWHM[i]})
locs_dict.update({PSF_id[i]:locs[i]})
filter_dict.update({PSF_id[i]:filter_list[i]})
id_stars_dict.update({PSF_id[i]:id_star_s[i]})
print '\n'
for i in range(len(PSF_list)):
if filter_list[i] == 'F125w':
print PSF_id[i], round(fluxs[i],3), round(FWHM[i],3), locs[i], filter_list[i], id_star_s[i]
flux_dict.update({PSF_id[i]:fluxs[i]})
FWHM_dict.update({PSF_id[i]:FWHM[i]})
locs_dict.update({PSF_id[i]:locs[i]})
filter_dict.update({PSF_id[i]:filter_list[i]})
id_stars_dict.update({PSF_id[i]:id_star_s[i]})
#import pickle
#filename='PSFs_lib_dict'.format(ID)
#datafile = open(filename, 'wb')
#PSFs_lib = [flux_dict, FWHM_dict, locs_dict, filter_dict, id_stars_dict]
#pickle.dump(PSFs_lib, open(filename, 'wb'))
#datafile.close() |
993,661 | 427ea0c2538f031d75ca7547e72d8a6e2bbcb23e | from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
stack = [root]
seen = set()
seen.add(None) # add none so it can be ignored
output = []
while len(stack) > 0:
current_node = stack.pop()
# if dead end continue
if current_node is None:
continue
# visit the left if it hasn't been seen yet
elif current_node.left not in seen:
# we re-add the current node so we know what the next node is when we come back from left
stack.append(current_node)
stack.append(current_node.left)
# if the left has been visited we can visit the right
elif current_node.left in seen:
seen.add(current_node)
output.append(current_node.val)
stack.append(current_node.right)
return output
if __name__ == "__main__":
sol = Solution()
node_1 = TreeNode(1)
node_2 = TreeNode(2)
node_3 = TreeNode(3)
node_1.right = node_2
node_2.left = node_3
output = sol.inorderTraversal(node_1)
assert output == [1, 3, 2]
node_1 = TreeNode(1)
node_2 = TreeNode(2)
node_1.right = node_2
output = sol.inorderTraversal(node_1)
assert output == [1, 2]
node_1 = TreeNode(1)
output = sol.inorderTraversal(node_1)
assert output == [1]
output = sol.inorderTraversal(None)
assert output == []
node_1 = TreeNode(1)
node_2 = TreeNode(2)
node_3 = TreeNode(3)
node_4 = TreeNode(4)
node_5 = TreeNode(5)
node_1.left = node_2
node_1.right = node_3
node_3.left = node_4
node_3.right = node_5
output = sol.inorderTraversal(node_1)
assert output == [2, 1, 4, 3, 5]
|
993,662 | d8c58d227701bf3cf311e98bd5d757bef3a5a526 | def resolve():
'''
code here
'''
N, K = [int(item) for item in input().split()]
xs = [int(item) for item in input().split()]
min_lr = 10**9
min_rl = 10**9
if N != K:
for i in range(N-K+1):
min_lr = min(min_lr, abs(xs[i]) + abs(xs[i+K-1] - xs[i]))
min_rl = min(min_rl, abs(xs[i+K-1]) + abs(xs[i+K-1] - xs[i]))
print(min(min_lr, min_rl))
elif N ==1:
print(abs(xs[0]))
else:
print(min(abs(xs[0]) + abs(xs[N-1] - xs[0]), abs(xs[N-1]) + abs(xs[N-1] - xs[0])))
if __name__ == "__main__":
resolve()
|
993,663 | 06e2167ba1378437a0f9de818a5d6cc5a47f8c3a | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the designerPdfViewer function below.
def designerPdfViewer(h, word):
d = dict()
for i in range(26):
d[chr(i+97)] = h[i]
list = []
for e in word:
list.append(d[e])
return max(list)*len(word)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
h = list(map(int, input().rstrip().split()))
word = input()
result = designerPdfViewer(h, word)
fptr.write(str(result) + '\n')
fptr.close()
|
993,664 | 9922c1db724eb53341d009a27ce148733ee5708d | # Generated by Django 2.1.7 on 2019-04-17 05:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0010_auto_20190416_1352'),
]
operations = [
migrations.AddField(
model_name='estatusactividad',
name='color',
field=models.CharField(blank=True, choices=[('', 'Ninguno'), ('primary', 'Primary'), ('secondary', 'Secondary'), ('success', 'Success'), ('danger', 'Danger'), ('warning', 'Warning'), ('info', 'Info'), ('light', 'Light'), ('dark', 'Dark')], default='', max_length=50),
),
migrations.AddField(
model_name='taxonomiaexpediente',
name='color',
field=models.CharField(blank=True, choices=[('', 'Ninguno'), ('primary', 'Primary'), ('secondary', 'Secondary'), ('success', 'Success'), ('danger', 'Danger'), ('warning', 'Warning'), ('info', 'Info'), ('light', 'Light'), ('dark', 'Dark')], default='', max_length=50),
),
]
|
993,665 | 67690540bff8d3d771523ccf6a374282f683d2f9 | from app.models.base import BaseModel
from google.appengine.ext import ndb
import logging
class CommentModel( BaseModel ):
Name = ndb.StringProperty(indexed=True, required=True)
Email = ndb.StringProperty(indexed=False, required=True)
Comment = ndb.BlobProperty(indexed=False, required=True)
Published = ndb.BooleanProperty(indexed=True, required=True)
SlugId = ndb.StringProperty(indexed=True, required=True)
'''
A user will enter a comment for a particular post - eg: ABC.
We require the username, email, and comment information from the user.
The comment will be set to published once reviewed - this will be false by default
PostId will the be reference back to the comments
Comments will also require pagination - since we will only show 10 comments at a time.
Perhaps a show more click would do....
'''
def save_comment(self, **kwargs):
''' default save comment helper '''
try:
comment = CommentModel(**kwargs)
comment.put()
except Exception as e:
logging.info(e)
return None
else:
return comment
@classmethod
def create_comment(cls, commentForm, slug):
""" create a comment tied to a post """
comment = CommentModel(
Name = str(commentForm.name.data),
Email = str(commentForm.email.data),
Comment = str(commentForm.comment.data),
Published = True,
SlugId = slug
)
comment.put()
return comment
@classmethod
def get_comment_by_slug_async(cls, slug):
query = cls.query( cls.SlugId==slug )
query = query.filter(cls.Published==True)
return query.order(-cls.created).fetch_async()
@classmethod
def get_comment_by_username(cls, username):
''' returns all the comments for a user - sorted desc by creation time '''
return cls.query( ndb.AND(tuple([cls.Name==username, cls.Published==True])) ).order(-cls.created)
|
993,666 | a48b2fc5099fbc9fc8dbc76274cf505902c4976a | from petsc4py import *
from petsc4py import PETSc
import graphviz
import numpy as np
import matplotlib.pyplot as plt
from collections import namedtuple
VERTEX_DEPTH_STRATUM = 0
EDGE_DEPTH_STRATUM = 1
FACE_DEPTH_STRATUM = 2
# Cell Quality Measure datatype
# We care about a cell's area (measure), minimum angle, aspect ratio, skewness, equiangle skew, and its scaled Jacobian
CQM = namedtuple('CQM', 'area, minAngle, aspectRatio, skewness, equiangleSkew, scaledJacobian')
def distance(p1, p2):
if p1.shape[0] != p2.shape[0]:
return ValueError
return np.sqrt(np.sum([(p1[i] - p2[i])**2 for i in range(p1.shape[0])]))
def getEdgeLength(plex, sec, dim, index):
'''Takes in the index of an edge and outputs its length'''
eStart, eEnd = plex.getDepthStratum(EDGE_DEPTH_STRATUM)
assert eStart <= index < eEnd
plexCoords = plex.getCoordinates()
vertices = plex.getCone(index)
v1, v2 = [np.array([plexCoords[sec.getOffset(v) + j] for j in range(dim)]) for v in vertices]
return distance(v1, v2)
def getCellQualityMeasures(plex, sec, dim, index):
'''Takes in the index of a cell and returns MeshQualityMeasures of the cell'''
cStart, cEnd = plex.getDepthStratum(FACE_DEPTH_STRATUM)
assert cStart <= index < cEnd
plexCoords = plex.getCoordinates()
edges = plex.getCone(index)
vertices = set()
minEdgeLength = np.inf
maxEdgeLength = 0
edgeLengths = []
for e in edges:
# Add vertices to a set (to avoid overcounting), use to calculate CQM
verts = plex.getCone(e)
v1, v2 = [([plexCoords.array[sec.getOffset(v) + j] for j in range(dim)]) for v in verts]
vertices.add(tuple(v1))
vertices.add(tuple(v2))
# Compute edge length for aspect ratio and area calculations
v1 = np.array(v1)
v2 = np.array(v2)
edgeLength = distance(v1, v2)
edgeLengths.append(edgeLength)
if edgeLength < minEdgeLength:
minEdgeLength = edgeLength
if edgeLength > maxEdgeLength:
maxEdgeLength = edgeLength
# Calculate area (Heron's formula) and aspect ratio from edge lengths
# Not entirely sure, but I think we should be able to calculate skew as well from this
edgeLengthRatio = maxEdgeLength / minEdgeLength
aspectRatio = maxEdgeLength / minEdgeLength
semiPerimeter = sum(edgeLengths) / 2
area = semiPerimeter
miniProduct = 1 # We are reusing this value = (s-a)(s-b)(s-c)
edgeLengthsProduct = 1
for i in range(len(edgeLengths)):
miniProduct *= (semiPerimeter - edgeLengths[i])
edgeLengthsProduct *= edgeLengths[i]
area = np.sqrt(area * miniProduct)
aspectRatio = edgeLengthsProduct / (8 * miniProduct)
# Calculate angles at each vertex
# If we know we're dealing with triangular meshes, I could just hard-code the vector calculations
# I actually do not know how to write the code in general
# To be fair, with triangles and tetrahedra every pair of vertices is connected
v1, v2, v3 = [np.array(v) for v in vertices]
# These guys are np arrays so i can do element-wise subtraction
vec12 = v2 - v1
vec23 = v3 - v2
vec31 = v1 - v3
dist12 = distance(v1, v2)
dist23 = distance(v2, v3)
dist31 = distance(v3, v1)
a1 = np.arccos (np.dot(vec12, vec31) / (dist12 * dist31))
a2 = np.arccos (np.dot(vec12, vec23) / (dist12 * dist23))
a3 = np.arccos (np.dot(vec31, vec23) / (dist31 * dist23))
minAngle = min(a1, a2, a3)
maxAngle = max(a1, a2, a3)
idealAngle = np.pi / 3 # There's gotta be a better way to write this stuff
equiangleSkew = max( (maxAngle - idealAngle) / (np.pi - idealAngle), (idealAngle - minAngle) / idealAngle)
# Calculating in accordance with https://www.engmorph.com/skewness-finite-elemnt
# sideN -> side opposite vertex vN
midPointSide1 = v2 + (v3 - v2) / 2
midPointSide2 = v3 + (v1 - v3) / 2
midPointSide3 = v1 + (v2 - v1) / 2
# print ("Vertices: {} {}, midpoint: {}".format(v2, v3, midPointSide1))
lineNormalSide1 = midPointSide1 - v1
lineOrthSide1 = midPointSide3 - midPointSide2
theta1 = np.arccos (np.dot(lineNormalSide1, lineOrthSide1) / (distance(v1, midPointSide1) * distance(midPointSide2, midPointSide3)))
theta2 = np.pi - theta1
lineNormalSide2 = midPointSide2 - v2
lineOrthSide2 = midPointSide1 - midPointSide3
theta3 = np.arccos (np.dot(lineNormalSide2, lineOrthSide2) / (distance(v2, midPointSide2) * distance(midPointSide1, midPointSide3)))
theta4 = np.pi - theta3
lineNormalSide3 = midPointSide3 - v3
lineOrthSide3 = midPointSide2 - midPointSide1
theta5 = np.arccos (np.dot(lineNormalSide3, lineOrthSide3) / (distance(v3, midPointSide3) * distance(midPointSide2, midPointSide1)))
theta6 = np.pi - theta5
skewness = (np.pi / 2) - min(theta1, theta2, theta3, theta4, theta5, theta6)
scaledJacobian = 0
return CQM(area, minAngle, aspectRatio, skewness, equiangleSkew, scaledJacobian)
def main():
# Initial setup mesh
dim = 2
coords = np.asarray([
[0.0, 0.0], # 0
[0.5, 0.0], # 1
[1.0, 0.0], # 2
[0.0, 0.5], # 3
[0.4, 0.6], # 4
[1.0, 0.5], # 5
[0.0, 1.0], # 6
[0.5, 1.0], # 7
[1.0, 1.0], # 8
], dtype=float)
cells = np.asarray([
[0, 1, 3],
[1, 4, 3],
[1, 2, 4],
[2, 4, 5],
[3, 4, 6],
[4, 6, 7],
[5, 7, 8],
[4, 5, 7],
], dtype=PETSc.IntType)
# Create DMPlex from cells and vertices
plex = PETSc.DMPlex().createFromCellList(dim, cells, coords, comm=PETSc.COMM_WORLD)
# comm - the basic object used by MPI to determine which processes are involved in a communication
# PETSc.COMM_WORLD - the equivalent of the MPI_COMM_WORLD communicator which represents all the processes that PETSc knows about.
print (plex.getDimension())
# Now, we set up a section so that we can smoothly translate between the co-ordinate plane and our DMPlex representation
numComponents = 1
entityDofs = [dim, 0, 0] # 2 entries for each vertex, 0 for each edge, 0 for each cell
plex.setNumFields(1)
sec = plex.createSection(numComponents, entityDofs)
sec.setFieldName(0, 'Coordinates')
sec.setUp()
plex.setSection(sec)
# Some bookkeeping
vStart, vEnd = plex.getDepthStratum(VERTEX_DEPTH_STRATUM)
eStart, eEnd = plex.getDepthStratum(EDGE_DEPTH_STRATUM)
cStart, cEnd = plex.getDepthStratum(FACE_DEPTH_STRATUM)
# hStart, hEnd = plex.getDepthStratum(3)
# print ("hStart, hEnd: {} {}".format(hStart, hEnd))
Start, End = plex.getChart()
plexCoords = plex.getCoordinates()
# TEST FOR EDGE LENGTH FUNCTION
# for edge in range(eStart, eEnd):
# try:
# edgeLength = getEdgeLength(plex, sec, dim, edge)
# print ("Edge: {}, Edge Length: {}".format(edge, edgeLength))
# except AssertionError:
# print ("{} is not an edge index. Skipped.".format(edge))
# TEST FOR CELL QUALITY MEASURES
for cell in range(cStart, cEnd):
try:
cellQuality = getCellQualityMeasures(plex, sec, dim, cell)
print ("Cell: {} Quality: {}".format(cell, cellQuality))
except AssertionError:
print ("{} is not a cell index. Skipped.".format(cell))
break
if __name__ == '__main__':
main() |
993,667 | 9bc204820a073b0595bd27b365aba3a1b71e4a47 | #coding=utf-8
#Version:python3.7.3
#Tools:Pycharm
"""
:r 只读方式打开文件,指针在开头
:w 以只写方式打开文件
:a 以追加方式打开文件,文件指针会放在文件的结尾
:r+ 以读写方式打开文件,文件的指针放在开头
:w+ 以读写的方式打开问津,如果文件存在会被覆盖
:a+ 以读写的方式打开文件。如果文件存在,指针就会放在结尾
"""
__date__ = '2019/4/3 17:00'
__author__ = 'Lee7'
# 1.打开文件
file = open("README.txt","a+")
# 2.写入文件
file.write("是不是我要打死你你才信\n")
# 3.关闭
file.close() |
993,668 | 122fbce353ae1cc0a90e12aada74add3f7978b4d | import random
import json
import os
import tempfile
import sys
from multiprocessing import Pool
with open('merged_backsplice_sequences.json') as handle:
data = json.load(handle)
def run_primer3(circ_id):
temp_file_data = "SEQUENCE_ID=%s\nSEQUENCE_TEMPLATE=%s\n=\n" % (circ_id, data[circ_id])
temp_file = tempfile.NamedTemporaryFile(mode='w', delete=False)
temp_file.write(temp_file_data)
temp_file.close()
cmd = 'primer3_bin/primer3_core -p3_settings_file=primer3_bin/circrna_primers_settings.p3 %s' % (temp_file.name)
output = os.popen(cmd).read()
os.system('rm %s' % temp_file.name)
return output
def parse_primer3_output(unparsed_output):
output_dict = {}
for line in unparsed_output.split('\n'):
cols = line.rstrip('\n').split('=')
try:
output_dict[cols[0]] = cols[1]
except IndexError:
pass
num_primers = int(output_dict['PRIMER_PAIR_NUM_RETURNED'])
if num_primers > 0:
parsed = {}
for i in range(num_primers):
parsed['primer_pair_%d' % i] = {
"left_seq": output_dict['PRIMER_LEFT_%d_SEQUENCE' % i],
"right_seq": output_dict['PRIMER_RIGHT_%d_SEQUENCE' % i],
"left_gc": output_dict['PRIMER_LEFT_%d_GC_PERCENT' % i],
"right_gc": output_dict['PRIMER_RIGHT_%d_GC_PERCENT' % i],
"left_tm": output_dict['PRIMER_LEFT_%d_TM' % i],
"right_tm": output_dict['PRIMER_RIGHT_%d_TM' % i],
"left_pos": output_dict['PRIMER_LEFT_%d' % i],
"right_pos": output_dict['PRIMER_RIGHT_%d' % i],
"product_size": output_dict['PRIMER_PAIR_%d_PRODUCT_SIZE' % i]
}
else:
return False
return parsed
def multiprocess_wrapper(circ_id):
unparsed_output = run_primer3(circ_id)
parsed_output = parse_primer3_output(unparsed_output)
return parsed_output
if __name__ == '__main__':
cores = int(sys.argv[1])
result = {}
skipped_ids = []
pool = Pool(processes=cores)
print len(data)
id_list = []
for n,circ_id in enumerate(data):
print "\r %d" % n,
sys.stdout.flush()
id_list.append(circ_id)
if len(id_list) == cores:
parsed_outputs = pool.map(multiprocess_wrapper, id_list)
for cid, output in zip(id_list, parsed_outputs):
if output is not False:
result[cid] = output
else:
skipped_ids.append(cid)
id_list = []
if len(id_list)>0:
for cid in id_list:
output = multiprocess_wrapper(cid)
if output is not False:
result[cid] = output
else:
skipped_ids.append(cid)
with open('hg19_circ_primers.json', 'w') as outfile:
json.dump(result, outfile, indent=2)
print "%d IDs skipped" % len(skipped_ids)
print
print skipped_ids
|
993,669 | c89789fa4012d9eed1ebad0d691132bb6e25ea77 | from time import time
from utility.printable import Printable
class Block(Printable):
def __init__(self, index, previous_hash, transactions, proof, time=time()):
self.index = index
self.previous_hash = previous_hash
self.timestamp = time
self.transactions = transactions
self.proof = proof
|
993,670 | 8128db189617b5820a41c001b95ad8083af58a3f | #!/usr/bin/python2.7
from __future__ import division
import os
import numpy
import scipy
import matplotlib
import pandas
import statsmodels
import patsy
import sys
import argparse
import matplotlib.pyplot as plt
import re
from random import shuffle,random,randint,choice,seed
from collections import Counter
from os import system
from pandas import DataFrame
from pandas import *
# import rpy2.robjects as robjects
# from rpy2.robjects.packages import importr
# from rpy2.robjects import pandas2ri
# pandas2ri.activate()
from Bio import SeqIO
from ggplot import *
from subprocess import call
from Bio.SeqRecord import SeqRecord
# utils = importr("utils")
# plyr = importr("plyr")
# seqinr = importr("seqinr")
#Constant values
#nt list
nts = ['A','C','G','T']
#Translation Table
tt = {"TTT":"F|Phe","TTC":"F|Phe","TTA":"L|Leu","TTG":"L|Leu","TCT":"S|Ser","TCC":"S|Ser","TCA":"S|Ser","TCG":"S|Ser", "TAT":"Y|Tyr","TAC":"Y|Tyr","TAA":"*|Stp","TAG":"*|Stp","TGT":"C|Cys","TGC":"C|Cys","TGA":"*|Stp","TGG":"W|Trp", "CTT":"L|Leu","CTC":"L|Leu","CTA":"L|Leu","CTG":"L|Leu","CCT":"P|Pro","CCC":"P|Pro","CCA":"P|Pro","CCG":"P|Pro","CAT":"H|His","CAC":"H|His","CAA":"Q|Gln","CAG":"Q|Gln","CGT":"R|Arg","CGC":"R|Arg","CGA":"R|Arg","CGG":"R|Arg", "ATT":"I|Ile","ATC":"I|Ile","ATA":"I|Ile","ATG":"M|Met","ACT":"T|Thr","ACC":"T|Thr","ACA":"T|Thr","ACG":"T|Thr", "AAT":"N|Asn","AAC":"N|Asn","AAA":"K|Lys","AAG":"K|Lys","AGT":"S|Ser","AGC":"S|Ser","AGA":"R|Arg","AGG":"R|Arg","GTT":"V|Val","GTC":"V|Val","GTA":"V|Val","GTG":"V|Val","GCT":"A|Ala","GCC":"A|Ala","GCA":"A|Ala","GCG":"A|Ala", "GAT":"D|Asp","GAC":"D|Asp","GAA":"E|Glu","GAG":"E|Glu","GGT":"G|Gly","GGC":"G|Gly","GGA":"G|Gly","GGG":"G|Gly"}
#Following functions or their combinations produce randomized or scrambled nucleotide sequence from input sequence.
#Amino-acid sequence of derived sequence is identical to the input sequence, but nucleotide composition (GC-, nucleotide, or dinucleotide content) may differ slightly for randomized sequences.
def gc3(seq):#this function creates sequence with GC-content close to the GC-content of the input sequence, but counts of nucleotides may differ from input sequence.
gc=at=0
for num in xrange(2,len(seq),3):#first calculating A+T and G+C of the input sequence in third codon position
if seq[num]=='A'or seq[num]=='T':
at+=1
elif seq[num]=='G'or seq[num]=='C':
gc+=1
at=at/(len(seq)/3.)
gc=gc/(len(seq)/3.)
seq1=[]
for num in xrange(2,len(seq),3):#list "seq1" will contain the first two nt of codon, third codon position will containe flags for subsequent randomization. Flags ('_Y_','_R_','_H_',or '_N_') correspond to IUPAC single-letter code, Y-Pyrimindine(C or T), R-Purine(A or G), H-Not G(A or C or T), N-any.
seq1+=seq[num-2:num],
if (seq[num]=='T'or seq[num]=='C')and(seq[num-2:num]=='TT'or seq[num-2:num]=='TA'or seq[num-2:num]=='TG'or seq[num-2:num]=='CA'or seq[num-2:num]=='AA'or seq[num-2:num]=='AG'or seq[num-2:num]=='GA'):
seq1+='_Y_',
elif (seq[num]=='A'or seq[num]=='G')and(seq[num-2:num]=='TT'or seq[num-2:num]=='CA'or seq[num-2:num]=='AA'or seq[num-2:num]=='AG'or seq[num-2:num]=='GA'):
seq1+='_R_',
elif seq[num-2:num+1]=='ATT'or seq[num-2:num+1]=='ATC'or seq[num-2:num+1]=='ATA':
seq1+='_H_',
elif (seq[num]=='A'or seq[num]=='G'or seq[num]=='T'or seq[num]=='C')and(seq[num-2:num]=='TC'or seq[num-2:num]=='CT'or seq[num-2:num]=='CC'or seq[num-2:num]=='CG'or seq[num-2:num]=='AC'or seq[num-2:num]=='GT'or seq[num-2:num]=='GC'or seq[num-2:num]=='GG'):
seq1+='_N_',
else: seq1+=seq[num],
seq2=''#"seq2" will contain the derived sequence, approproate nucleotide is chosen for flags in "seq1", according to GC-content
for i in seq1:
if i == '_Y_':
x=random()
if x<=gc:
seq2+='C'
elif gc<x<=gc+at:
seq2+='T'
else: seq2+=choice('TC')
elif i == '_R_':
x=random()
if x<=gc:
seq2+='G'
elif gc<x<=gc+at:
seq2+='A'
else: seq2+=choice('AG')
elif i == '_H_':
x=random()
if x<=gc:
seq2+='C'
elif gc<x<=gc+at:
seq2+=choice('AT')
else: seq2+=choice('ATC')
elif i == '_N_':
x=random()
if x<=gc:
seq2+=choice('GC')
elif gc<x<=gc+at:
seq2+=choice('AT')
else: seq2+=choice('AGTC')
else: seq2+=i
seq=seq2
return seq
def third_simple(seq):#this function creates scrambled sequence with the numbers of each nucleotide identical to the input sequence.
Y=[]
seq1=[]
for num in xrange(2,len(seq),3):
if (seq[num]=='T' or seq[num]=='C')and(seq[num-2:num]=='TT'or seq[num-2:num]=='TC'or seq[num-2:num]=='TA'or seq[num-2:num]=='TG'or seq[num-2:num]=='CT'or seq[num-2:num]=='CC'or seq[num-2:num]=='CA'or seq[num-2:num]=='CG'or seq[num-2:num]=='AT'or seq[num-2:num]=='AC'or seq[num-2:num]=='AA'or seq[num-2:num]=='AG'or seq[num-2:num]=='GU'or seq[num-2:num]=='GC'or seq[num-2:num]=='GA'or seq[num-2:num]=='GG'):
Y+=seq[num],
seq1+=seq[num-2:num],'_Y_',
else:seq1+=seq[num-2:num+1],
#now "seq1" contains flag '_Y_' in the third position of all codons, where C->T or T->C shuffling preserves the aminoacid sequence (i.e. PHE, SER etc.).
#C and T from the original sequence in this case would be extracted into list "Y"
shuffle(Y)#shuffling of list "Y". For example, before shuffling "Y" is ['C','T','C']; after - ['T','C','C']or['C','C','T']or['C','T','C']
seq2=''
for i in xrange(len(seq1)):
if seq1[i]=='_Y_':seq2+=Y.pop(0)#now elements of "Y" are inserted back into the sequence instead of '_Y_', but in a different order compared to the input sequence
else:seq2+=seq1[i]
seq=seq2
R=[]#similar to the previous step, but A and G are shuffled
seq1=[]
for num in xrange(2,len(seq),3):
if (seq[num]=='A' or seq[num]=='G')and(seq[num-2:num]=='TT'or seq[num-2:num]=='TC'or seq[num-2:num]=='CT'or seq[num-2:num]=='CC'or seq[num-2:num]=='CA'or seq[num-2:num]=='CG'or seq[num-2:num]=='AC'or seq[num-2:num]=='AA'or seq[num-2:num]=='AG'or seq[num-2:num]=='GT'or seq[num-2:num]=='GC'or seq[num-2:num]=='GA'or seq[num-2:num]=='GG'):
R+=seq[num],
seq1+=seq[num-2:num],'_R_',
else:seq1+=seq[num-2:num+1],
shuffle(R)
seq2=''
for i in xrange(len(seq1)):
if seq1[i]=='_R_':seq2+=R.pop(0)
else:seq2+=seq1[i]
seq=seq2
H=[]#similar to the previous step, but A,C, and T are shuffled. Affected aminoacids are ILE (three codons), four-codon and four-codon portion of six-codon aminoacids.
seq1=[]
for num in xrange(2,len(seq),3):
if (seq[num]=='A'or seq[num]=='C'or seq[num]=='T')and(seq[num-2:num]=='TC'or seq[num-2:num]=='CT'or seq[num-2:num]=='CC'or seq[num-2:num]=='CG'or seq[num-2:num]=='AT'or seq[num-2:num]=='AC'or seq[num-2:num]=='GT'or seq[num-2:num]=='GC'or seq[num-2:num]=='GG'):
H+=seq[num],
seq1+=seq[num-2:num],'_H_',
else:seq1+=seq[num-2:num+1],
shuffle(H)
seq2=''
for i in xrange(len(seq1)):
if seq1[i]=='_H_':seq2+=H.pop(0)
else:seq2+=seq1[i]
seq=seq2
N=[]#Shuffling of all four nucleotides, where possible. Affected aminoacids are four-codons and four-codon portion of six-codon aminoacids.
seq1=[]
for num in xrange(2,len(seq),3):
if (seq[num]=='A'or seq[num]=='C'or seq[num]=='T'or seq[num]=='G')and(seq[num-2:num]=='TC'or seq[num-2:num]=='CT'or seq[num-2:num]=='CC'or seq[num-2:num]=='CG'or seq[num-2:num]=='AC'or seq[num-2:num]=='GT'or seq[num-2:num]=='GC'or seq[num-2:num]=='GG'):
N+=seq[num],
seq1+=seq[num-2:num],'_N_',
else:seq1+=seq[num-2:num+1],
shuffle(N)
seq2=''
for i in xrange(len(seq1)):
if seq1[i]=='_N_':seq2+=N.pop(0)
else:seq2+=seq1[i]
seq=seq2
return seq
def dn23(seq):#this function creates a randomized sequence, with dinucleotide frequences in codon position 2-3 close to those of the input sequence.
aa=ag=ac=at=ga=gg=gc=gt=ca=cg=cc=ct=ta=tg=tc=tt=0
for num in xrange(2,len(seq),3):#first calculating dinucleotide frequences in codon position 2-3
if seq[num-1]=='A':
if seq[num]=='A':
aa+=1
elif seq[num]=='G':
ag+=1
elif seq[num]=='C':
ac+=1
elif seq[num]=='T':
at+=1
elif seq[num-1]=='G':
if seq[num]=='A':
ga+=1
elif seq[num]=='G':
gg+=1
elif seq[num]=='C':
gc+=1
elif seq[num]=='T':
gt+=1
elif seq[num-1]=='C':
if seq[num]=='A':
ca+=1
elif seq[num]=='G':
cg+=1
elif seq[num]=='C':
cc+=1
elif seq[num]=='T':
ct+=1
elif seq[num-1]=='T':
if seq[num]=='A':
ta+=1
elif seq[num]=='G':
tg+=1
elif seq[num]=='C':
tc+=1
elif seq[num]=='T':
tt+=1
aa,ag,ac,at,ga,gg,gc,gt,ca,cg,cc,ct,ta,tg,tc,tt=aa/(len(seq)/3.),ag/(len(seq)/3.),ac/(len(seq)/3.),at/(len(seq)/3.),ga/(len(seq)/3.),gg/(len(seq)/3.),gc/(len(seq)/3.),gt/(len(seq)/3.),ca/(len(seq)/3.),cg/(len(seq)/3.),cc/(len(seq)/3.),ct/(len(seq)/3.),ta/(len(seq)/3.),tg/(len(seq)/3.),tc/(len(seq)/3.),tt/(len(seq)/3.)
seq2=''
for num in xrange(2,len(seq),3):#now each codon is replaced with a synonimous codon according to the dinucleotide frequences in codon position 2-3
seq2+=seq[num-2:num]
if seq[num-1]=='A'and seq[num-2:num+1]!='TAA'and seq[num-2:num+1]!='TAG':
if seq[num]=='T'or seq[num]=='C':
space=at+ac
AT,AC=at/space,ac/space
x=random()
if x<=AT:
seq2+='T'
elif AT<x<=AT+AC:
seq2+='C'
elif seq[num]=='A'or seq[num]=='G':
space=aa+ag
AA,AG=aa/space,ag/space
x=random()
if x<=AA:
seq2+='A'
elif AA<x<=AA+AG:
seq2+='G'
else:seq2+=seq[num]
elif seq[num-1]=='G'and seq[num-2:num+1]!='TGA'and seq[num-2:num+1]!='TGG':
if (seq[num-2]=='T'or seq[num-2]=='A')and(seq[num]=='C'or seq[num]=='T'):
space = gt+gc
GT,GC=gt/space,gc/space
x=random()
if x<=GT:
seq2+='T'
elif GT<x<=GT+GC:
seq2+='C'
elif seq[num-2:num+1]=='AGA'or seq[num-2:num+1]=='AGG':
space=ga+gg
GA,GG=ga/space,gg/space
x=random()
if x<=GA:
seq2+='A'
elif GA<x<=GA+GG:
seq2+='G'
elif seq[num-2]=='C'or seq[num-2]=='G':
space=ga+gg+gc+gt
GA,GG,GC,GT=ga/space,gg/space,gc/space,gt/space
x=random()
if x<=GA:seq2+='A'
elif GA<x<=GA+GG:seq2+='G'
elif GA+GG<x<=GA+GG+GC:seq2+='C'
elif GA+GG+GC<x<=GA+GG+GC+GT:seq2+='T'
else:seq2+=seq[num]
elif seq[num-1]=='C':
space=ca+cg+cc+ct
CA,CG,CC,CT=ca/space,cg/space,cc/space,ct/space
x=random()
if x<=CA:seq2+='A'
elif CA<x<=CA+CG:seq2+='G'
elif CA+CG<x<=CA+CG+CC:seq2+='C'
elif CA+CG+CC<x<=CA+CG+CC+CT:seq2+='T'
elif seq[num-1]=='T':
if seq[num-2:num+1]=='TTT'or seq[num-2:num+1]=='TTC':
space = tt+tc
TT,TC=tt/space,tc/space
x=random()
if x<=TT:
seq2+='T'
elif TT<x<=TT+TC:
seq2+='C'
elif seq[num-2:num+1]=='TTA'or seq[num-2:num+1]=='TTG':
space = ta+tg
TA,TG=ta/space,tg/space
x=random()
if x<=TA:
seq2+='A'
elif TA<x<=TA+TG:
seq2+='G'
elif seq[num-2:num+1]=='ATT'or seq[num-2:num+1]=='ATC'or seq[num-2:num+1]=='ATA':
space=tt+tc+ta
TT,TC,TA=tt/space,tc/space,ta/space
x=random()
if x<=TA:seq2+='A'
elif TA<x<=TA+TC:seq2+='C'
elif TA+TC<x<=TA+TC+TT:seq2+='T'
elif seq[num-2]=='C'or seq[num-2]=='G':
space=ta+tg+tc+tt
TA,TG,TC,TT=ta/space,tg/space,tc/space,tt/space
x=random()
if x<=TA:seq2+='A'
elif TA<x<=TA+TG:seq2+='G'
elif TA+TG<x<=TA+TG+TC:seq2+='C'
elif TA+TG+TC<x<=TA+TG+TC+TT:seq2+='T'
else:seq2+=seq[num]
else:seq2+=seq[num]
seq=seq2
return seq
def third(seq):#this function creates sequence with dinucleotide content in codon positions 2-3 and 3-1 identical to that of the input sequence.
#logic of this function similar to "third_simple"
seq1=[]
TNT,TNC,TNA,TNG,GNT,GNA,GNC,GNG,CNG,CNA,CNT,CNC=[],[],[],[],[],[],[],[],[],[],[],[]#these lists will contain nucleotides from third codon position, with given [-1]and[+1]nucleotides to preserve dinucleotide content in conserved positions
#four-codon and four-codon portion of six-codon aminoacids are affected
for num in xrange(2,len(seq)-3,3):
seq1+=seq[num-2:num]
if seq[num]=='T' or seq[num]=='C' or seq[num]=='A' or seq[num]=='G':
if seq[num-2:num]=='CT' or seq[num-2:num]=='GT':#LEU4 or VAL
if seq[num+1]=='T':
seq1+='TNT',
TNT+=seq[num],
elif seq[num+1]=='C':
seq1+='TNC',
TNC+=seq[num],
elif seq[num+1]=='A':
seq1+='TNA',
TNA+=seq[num],
elif seq[num+1]=='G':
seq1+='TNG',
TNG+=seq[num],
else:
seq1+=seq[num]
elif seq[num-1]=='C':#SER4 or PRO or THR or ALA
if seq[num+1]=='T':
seq1+='CNT',
CNT+=seq[num],
elif seq[num+1]=='C':
seq1+='CNC',
CNC+=seq[num],
elif seq[num+1]=='A':
seq1+='CNA',
CNA+=seq[num],
elif seq[num+1]=='G':
seq1+='CNG',
CNG+=seq[num],
else:
seq1+=seq[num]
elif seq[num-2:num]=='CG' or seq[num-2:num]=='GG':#ARG4 or GLY
if seq[num+1]=='T':
seq1+='GNT',
GNT+=seq[num],
elif seq[num+1]=='C':
seq1+='GNC',
GNC+=seq[num],
elif seq[num+1]=='A':
seq1+='GNA',
GNA+=seq[num],
elif seq[num+1]=='G':
seq1+='GNG',
GNG+=seq[num],
else:
seq1+=seq[num]
else:
seq1+=seq[num]
else:
seq1+=seq[num]
seq1+=seq[-3:]
shuffle(TNT),shuffle(TNC),shuffle(TNA),shuffle(TNG),shuffle(GNG),shuffle(GNA),shuffle(GNT),shuffle(GNC),shuffle(CNT),shuffle(CNC),shuffle(CNA),shuffle(CNG)
seq2=''
for i in xrange(len(seq1)):
if seq1[i]=='TNT':seq2+=TNT.pop(0)
elif seq1[i]=='TNC':seq2+=TNC.pop(0)
elif seq1[i]=='TNG':seq2+=TNG.pop(0)
elif seq1[i]=='TNA':seq2+=TNA.pop(0)
elif seq1[i]=='GNT':seq2+=GNT.pop(0)
elif seq1[i]=='GNA':seq2+=GNA.pop(0)
elif seq1[i]=='GNC':seq2+=GNC.pop(0)
elif seq1[i]=='GNG':seq2+=GNG.pop(0)
elif seq1[i]=='CNT':seq2+=CNT.pop(0)
elif seq1[i]=='CNC':seq2+=CNC.pop(0)
elif seq1[i]=='CNG':seq2+=CNG.pop(0)
elif seq1[i]=='CNA':seq2+=CNA.pop(0)
else:seq2+=seq1[i]
seq=seq2
seq1=[]
THT,THC,THA,THG,GHT,GHA,GHC,GHG,CHG,CHA,CHT,CHC=[],[],[],[],[],[],[],[],[],[],[],[]
for num in xrange(2,len(seq)-3,3):
seq1+=seq[num-2:num]
if seq[num]=='T' or seq[num]=='C' or seq[num]=='A':
if seq[num-2:num]=='CT' or seq[num-2:num]=='GT' or seq[num-2:num]=='AT':#ILE3 or LEU4 or VAL
if seq[num+1]=='T':
seq1+='THT',
THT+=seq[num],
elif seq[num+1]=='C':
seq1+='THC',
THC+=seq[num],
elif seq[num+1]=='A':
seq1+='THA',
THA+=seq[num],
elif seq[num+1]=='G':
seq1+='THG',
THG+=seq[num],
else:
seq1+=seq[num]
elif seq[num-1]=='C':#SER4 or PRO or THR or ALA
if seq[num+1]=='T':
seq1+='CHT',
CHT+=seq[num],
elif seq[num+1]=='C':
seq1+='CHC',
CHC+=seq[num],
elif seq[num+1]=='A':
seq1+='CHA',
CHA+=seq[num],
elif seq[num+1]=='G':
seq1+='CHG',
CHG+=seq[num],
else:
seq1+=seq[num]
elif seq[num-2:num]=='CG' or seq[num-2:num]=='GG':#ARG4 or GLY
if seq[num+1]=='T':
seq1+='GHT',
GHT+=seq[num],
elif seq[num+1]=='C':
seq1+='GHC',
GHC+=seq[num],
elif seq[num+1]=='A':
seq1+='GHA',
GHA+=seq[num],
elif seq[num+1]=='G':
seq1+='GHG',
GHG+=seq[num],
else:
seq1+=seq[num]
else:
seq1+=seq[num]
else:
seq1+=seq[num]
seq1+=seq[-3:]
shuffle(THT),shuffle(THC),shuffle(THA),shuffle(THG),shuffle(GHG),shuffle(GHA),shuffle(GHT),shuffle(GHC),shuffle(CHT),shuffle(CHC),shuffle(CHA),shuffle(CHG)
seq2=''
for i in xrange(len(seq1)):
if seq1[i]=='THT':seq2+=THT.pop(0)
elif seq1[i]=='THC':seq2+=THC.pop(0)
elif seq1[i]=='THA':seq2+=THA.pop(0)
elif seq1[i]=='THG':seq2+=THG.pop(0)
elif seq1[i]=='GHT':seq2+=GHT.pop(0)
elif seq1[i]=='GHA':seq2+=GHA.pop(0)
elif seq1[i]=='GHC':seq2+=GHC.pop(0)
elif seq1[i]=='GHG':seq2+=GHG.pop(0)
elif seq1[i]=='CHT':seq2+=CHT.pop(0)
elif seq1[i]=='CHC':seq2+=CHC.pop(0)
elif seq1[i]=='CHG':seq2+=CHG.pop(0)
elif seq1[i]=='CHA':seq2+=CHA.pop(0)
else:seq2+=seq1[i]
seq=seq2
seq1=[]
TRT,TRC,TRA,TRG,ART,ARC,ARG,ARA,GRT,GRA,GRC,GRG,CRG,CRA,CRT,CRC=[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]
for num in xrange(2,len(seq)-3,3):
seq1+=seq[num-2:num]
if seq[num]=='A' or seq[num]=='G':
if seq[num-1]=='T' and seq[num-2:num]!='AT':#not MET
if seq[num+1]=='T':
seq1+='TRT',
TRT+=seq[num],
elif seq[num+1]=='C':
seq1+='TRC',
TRC+=seq[num],
elif seq[num+1]=='A':
seq1+='TRA',
TRA+=seq[num],
elif seq[num+1]=='G':
seq1+='TRG',
TRG+=seq[num],
else:
seq1+=seq[num]
elif seq[num-1]=='C':
if seq[num+1]=='T':
seq1+='CRT',
CRT+=seq[num],
elif seq[num+1]=='C':
seq1+='CRC',
CRC+=seq[num],
elif seq[num+1]=='A':
seq1+='CRA',
CRA+=seq[num],
elif seq[num+1]=='G':
seq1+='CRG',
CRG+=seq[num],
else:
seq1+=seq[num]
elif seq[num-1]=='A' and seq[num-2:num]!='TA':#not Amber, not Ochre
if seq[num+1]=='T':
seq1+='ART',
ART+=seq[num],
elif seq[num+1]=='C':
seq1+='ARC',
ARC+=seq[num],
elif seq[num+1]=='A':
seq1+='ARA',
ARA+=seq[num],
elif seq[num+1]=='G':
seq1+='ARG',
ARG+=seq[num],
else:
seq1+=seq[num]
elif seq[num-1]=='G' and seq[num-2:num]!='TG':#not TRP, not Opal
if seq[num+1]=='T':
seq1+='GRT',
GRT+=seq[num],
elif seq[num+1]=='C':
seq1+='GRC',
GRC+=seq[num],
elif seq[num+1]=='A':
seq1+='GRA',
GRA+=seq[num],
elif seq[num+1]=='G':
seq1+='GRG',
GRG+=seq[num],
else:
seq1+=seq[num]
else:
seq1+=seq[num]
else:
seq1+=seq[num]
seq1+=seq[-3:]
shuffle(TRT),shuffle(TRC),shuffle(TRA),shuffle(TRG),shuffle(GRG),shuffle(GRA),shuffle(GRT),shuffle(GRC),shuffle(ARG),shuffle(ARC),shuffle(ART),shuffle(ARA),shuffle(CRT),shuffle(CRC),shuffle(CRA),shuffle(CRG)
seq2=''
for i in xrange(len(seq1)):
if seq1[i]=='TRT':seq2+=TRT.pop(0)
elif seq1[i]=='TRC':seq2+=TRC.pop(0)
elif seq1[i]=='TRA':seq2+=TRA.pop(0)
elif seq1[i]=='TRG':seq2+=TRG.pop(0)
elif seq1[i]=='ART':seq2+=ART.pop(0)
elif seq1[i]=='ARC':seq2+=ARC.pop(0)
elif seq1[i]=='ARG':seq2+=ARG.pop(0)
elif seq1[i]=='ARA':seq2+=ARA.pop(0)
elif seq1[i]=='GRT':seq2+=GRT.pop(0)
elif seq1[i]=='GRA':seq2+=GRA.pop(0)
elif seq1[i]=='GRC':seq2+=GRC.pop(0)
elif seq1[i]=='GRG':seq2+=GRG.pop(0)
elif seq1[i]=='CRT':seq2+=CRT.pop(0)
elif seq1[i]=='CRC':seq2+=CRC.pop(0)
elif seq1[i]=='CRG':seq2+=CRG.pop(0)
elif seq1[i]=='CRA':seq2+=CRA.pop(0)
else:seq2+=seq1[i]
seq=seq2
seq1=[]
TYT,TYC,TYA,TYG,AYT,AYC,AYG,AYA,GYT,GYA,GYC,GYG,CYG,CYA,CYT,CYC=[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]
for num in xrange(2,len(seq)-3,3):
seq1+=seq[num-2:num]
if seq[num]=='T' or seq[num]=='C':
if seq[num-1]=='T':
if seq[num+1]=='T':
seq1+='TYT',
TYT+=seq[num],
elif seq[num+1]=='C':
seq1+='TYC',
TYC+=seq[num],
elif seq[num+1]=='A':
seq1+='TYA',
TYA+=seq[num],
elif seq[num+1]=='G':
seq1+='TYG',
TYG+=seq[num],
else:
seq1+=seq[num]
elif seq[num-1]=='C':
if seq[num+1]=='T':
seq1+='CYT',
CYT+=seq[num],
elif seq[num+1]=='C':
seq1+='CYC',
CYC+=seq[num],
elif seq[num+1]=='A':
seq1+='CYA',
CYA+=seq[num],
elif seq[num+1]=='G':
seq1+='CYG',
CYG+=seq[num],
else:
seq1+=seq[num]
elif seq[num-1]=='A':
if seq[num+1]=='T':
seq1+='AYT',
AYT+=seq[num],
elif seq[num+1]=='C':
seq1+='AYC',
AYC+=seq[num],
elif seq[num+1]=='A':
seq1+='AYA',
AYA+=seq[num],
elif seq[num+1]=='G':
seq1+='AYG',
AYG+=seq[num],
else:
seq1+=seq[num]
elif seq[num-1]=='G':
if seq[num+1]=='T':
seq1+='GYT',
GYT+=seq[num],
elif seq[num+1]=='C':
seq1+='GYC',
GYC+=seq[num],
elif seq[num+1]=='A':
seq1+='GYA',
GYA+=seq[num],
elif seq[num+1]=='G':
seq1+='GYG',
GYG+=seq[num],
else:
seq1+=seq[num]
else:
seq1+=seq[num]
else:
seq1+=seq[num]
seq1+=seq[-3:]
shuffle(TYT),shuffle(TYC),shuffle(TYA),shuffle(TYG),shuffle(GYG),shuffle(GYA),shuffle(GYT),shuffle(GYC),shuffle(AYG),shuffle(AYC),shuffle(AYT),shuffle(AYA),shuffle(CYT),shuffle(CYC),shuffle(CYA),shuffle(CYG)
seq2=''
for i in xrange(len(seq1)):
if seq1[i]=='TYT':seq2+=TYT.pop(0)
elif seq1[i]=='TYC':seq2+=TYC.pop(0)
elif seq1[i]=='TYA':seq2+=TYA.pop(0)
elif seq1[i]=='TYG':seq2+=TYG.pop(0)
elif seq1[i]=='AYT':seq2+=AYT.pop(0)
elif seq1[i]=='AYC':seq2+=AYC.pop(0)
elif seq1[i]=='AYG':seq2+=AYG.pop(0)
elif seq1[i]=='AYA':seq2+=AYA.pop(0)
elif seq1[i]=='GYT':seq2+=GYT.pop(0)
elif seq1[i]=='GYA':seq2+=GYA.pop(0)
elif seq1[i]=='GYC':seq2+=GYC.pop(0)
elif seq1[i]=='GYG':seq2+=GYG.pop(0)
elif seq1[i]=='CYT':seq2+=CYT.pop(0)
elif seq1[i]=='CYC':seq2+=CYC.pop(0)
elif seq1[i]=='CYG':seq2+=CYG.pop(0)
elif seq1[i]=='CYA':seq2+=CYA.pop(0)
else:seq2+=seq1[i]
return seq2
def exchange6deg(seq):#this function shuffles the first nucleotide for two six-codon aminoacids (LEU and ARG) with the third codon position,
#preserving overall dinucleotide content, but not position-specific dinucleotide content. For SER (TCN+AGY)shuffling is more complicated, see below.
#after this shuffling, the 'third'-function should be used as above
#LEU
seq1=[]
#LEU has TTR and CTN codons
#first convertion of CTY to CTR is required to make them compatible with TTR codons and improve the shuffling efficiency;
#CTY LEU codons might be re-introduced later upon the third-position shuffling
CTYT=[]#these lists will contain third nucleotides of CTY-codons
CTYA=[]
CTTG=[]
CTCG=[]#T/C separation for shuffling of ARG, (A->C)
CTYC=[]
TAT,TAA,TAG,TAC,TGT,TGA,TGG,TGC=[],[],[],[],[],[],[],[]#these lists will contain the third R-nucleotide of ILE and VAL to exchange with the first position of Leu
TAG_arg=[]#only 'A' to 'C'. Arginine has AGY and CGN codons, first position can be shuffled.
seq1+=seq[:2]
for num in xrange(2,len(seq)-2,1):
#seq1+=seq[num-2:num]
if num%3==2 and seq[num-2:num]=='CT' and (seq[num]=='C' or seq[num]=='T'):
if seq[num+1]=='A':
CTYA+=seq[num],
seq1+='CTYA',
elif seq[num+1]=='G':
if seq[num]=='C':#T/C separation because of ARG, (A->C)
CTCG+=seq[num],
seq1+='CTYG',
elif seq[num]=='T':
CTTG+=seq[num],
seq1+='CTYG',
elif seq[num+1]=='C':
CTYC+=seq[num],
seq1+='CTYC',
elif seq[num+1]=='T':
CTYT+=seq[num],
seq1+='CTYT',
else:
seq1+=seq[num],
elif num%3==2 and (seq[num-2:num+1]=='GTA'or seq[num-2:num+1]=='ATA'):
if seq[num+1]=='A':
TAA+=seq[num],
seq1+='TAA',
elif seq[num+1]=='G':
TAG+=seq[num],
seq1+='TAG',
elif seq[num+1]=='C':
TAC+=seq[num],
seq1+='TAC',
elif seq[num+1]=='T':
TAT+=seq[num],
seq1+='TAT',
else:
seq1+=seq[num],
elif num%3==2 and seq[num-2:num+1]=='GTG':
if seq[num+1]=='A':
TGA+=seq[num],
seq1+='TGA',
elif seq[num+1]=='G':
TGG+=seq[num],
seq1+='TGG',
elif seq[num+1]=='C':
TGC+=seq[num],
seq1+='TGC',
elif seq[num+1]=='T':
TGT+=seq[num],
seq1+='TGT',
else:
seq1+=seq[num],
elif num%3==0 and (seq[num:num+3]=='AGA' or seq[num:num+3]=='AGG') and seq[num-1]=='T'and seq[num-2:num]!='TT'and seq[num-3:num]!='CTT':
TAG_arg+=seq[num],
seq1+='TAG_arg',
else:
seq1+=seq[num],
seq1+=seq[-2:]
#now replacing the third position Y with R in LEU
CTAG=[]
change_num=min(len(CTCG),len(TAG_arg))
CTAG,TAG_arg[:change_num],CTCG=TAG_arg[:change_num],CTCG[:change_num],CTCG[-1*(len(CTCG)-change_num):]
CTYG=CTCG+CTTG
shuffle(CTYG)
change_num=min(len(CTYG),len(TAG)) #first TAN,
CTYG[:change_num],TAG[:change_num]=TAG[:change_num],CTYG[:change_num] #then TGN,
CTYG.reverse() #important,
change_num=min(len(CTYG),len(TGG)) #Arginine,
CTYG[:change_num],TGG[:change_num]=TGG[:change_num],CTYG[:change_num] #first TAN,
CTYG+=CTAG #then TGN,
#important,
change_num=min(len(CTYT),len(TAT)) #first TAN,
CTYT[:change_num],TAT[:change_num]=TAT[:change_num],CTYT[:change_num] #then TGN,
CTYT.reverse() #important,
change_num=min(len(CTYT),len(TGT)) #first TAN,
CTYT[:change_num],TGT[:change_num]=TGT[:change_num],CTYT[:change_num] #then TGN,
#important,
#first TAN,
change_num=min(len(CTYA),len(TAA)) #then TGN,
CTYA[:change_num],TAA[:change_num]=TAA[:change_num],CTYA[:change_num] #important,
CTYA.reverse() #Arginine,
change_num=min(len(CTYA),len(TGA)) #then TGN,
CTYA[:change_num],TGA[:change_num]=TGA[:change_num],CTYA[:change_num] #important,
#first TAN,
#then TGN,
change_num=min(len(CTYC),len(TAC)) #important,
CTYC[:change_num],TAC[:change_num]=TAC[:change_num],CTYC[:change_num] #first TAN,
CTYC.reverse() #important,
change_num=min(len(CTYC),len(TGC)) #Arginine,
CTYC[:change_num],TGC[:change_num]=TGC[:change_num],CTYC[:change_num] #important
shuffle(CTYT),shuffle(CTYA),shuffle(CTYG),shuffle(CTYC),shuffle(TAT),shuffle(TAA),shuffle(TAG),shuffle(TAC),shuffle(TGT),shuffle(TGA),shuffle(TGG),shuffle(TGC),shuffle(TAG_arg)
seq2=''
for i in xrange(len(seq1)):
if seq1[i]=='CTYT':seq2+=CTYT.pop(0)
elif seq1[i]=='CTYC':seq2+=CTYC.pop(0)
elif seq1[i]=='CTYA':seq2+=CTYA.pop(0)
elif seq1[i]=='CTYG':seq2+=CTYG.pop(0)
elif seq1[i]=='TAG':seq2+=TAG.pop(0)
elif seq1[i]=='TAA':seq2+=TAA.pop(0)
elif seq1[i]=='TAC':seq2+=TAC.pop(0)
elif seq1[i]=='TAT':seq2+=TAT.pop(0)
elif seq1[i]=='TGG':seq2+=TGG.pop(0)
elif seq1[i]=='TGA':seq2+=TGA.pop(0)
elif seq1[i]=='TGC':seq2+=TGC.pop(0)
elif seq1[i]=='TGT':seq2+=TGT.pop(0)
elif seq1[i]=='TAG_arg':seq2+=TAG_arg.pop(0)
else:seq2+=seq1[i]
seq=seq2#convertion of CTY to CTR is finished
#now shuffling the first nucleotide of TTR and CTR LEU codons, and the third Y of other codons
seq1=[]
TYT,AYT,GYT,CYT=[],[],[],[]
seq1+=seq[:2]
for num in xrange(2,len(seq)-2,1):
if ((seq[num]=='T' or seq[num]=='C') and seq[num+1]=='T' and num%3==2 and seq[num+1:num+4]!='TTA' and seq[num+1:num+4]!='TTG' and seq[num+1:num+4]!='CTA' and seq[num+1:num+4]!='CTG') or (num%3==0 and (seq[num:num+3]=='TTA' or seq[num:num+3]=='TTG' or seq[num:num+3]=='CTA' or seq[num:num+3]=='CTG')):
if seq[num-1]=='T':
seq1+='TYT',
TYT+=seq[num],
elif seq[num-1]=='C':
seq1+='CYT',
CYT+=seq[num],
elif seq[num-1]=='A':
seq1+='AYT',
AYT+=seq[num],
elif seq[num-1]=='G':
seq1+='GYT',
GYT+=seq[num],
else:
seq1+=seq[num]
else:
seq1+=seq[num]
seq1+=seq[-2:]
shuffle(TYT),shuffle(GYT),shuffle(AYT),shuffle(CYT)
seq2=''
for i in xrange(len(seq1)):
if seq1[i]=='TYT':seq2+=TYT.pop(0)
elif seq1[i]=='AYT':seq2+=AYT.pop(0)
elif seq1[i]=='GYT':seq2+=GYT.pop(0)
elif seq1[i]=='CYT':seq2+=CYT.pop(0)
else:seq2+=seq1[i]
seq=seq2#shuffling is finished
#SER
seq1=[]
TCRC,TCRA,TCRG,TCRT=[],[],[],[]#SER has TCN and AGY codons, first TCR will be converted to TCY
CYC,CYA,CYG,CYT=[],[],[],[]
for num in xrange(2,len(seq)-2,3):
seq1+=seq[num-2:num]
if seq[num-2:num+1]=='TCA' or seq[num-2:num+1]=='TCG':
if seq[num+1]=='C':
TCRC+=seq[num],
seq1+='TCRC',
elif seq[num+1]=='G':
TCRG+=seq[num],
seq1+='TCRG',
elif seq[num+1]=='A':
TCRA+=seq[num],
seq1+='TCRA',
elif seq[num+1]=='T':
TCRT+=seq[num],
seq1+='TCRT',
else:
seq1+=seq[num],
elif (seq[num-2:num]=='CC'or seq[num-2:num]=='AC' or seq[num-2:num]=='GC')and(seq[num]=='T'or seq[num]=='C'):
if seq[num+1]=='C':
CYC+=seq[num],
seq1+='CYC',
elif seq[num+1]=='G':
CYG+=seq[num],
seq1+='CYG',
elif seq[num+1]=='A':
CYA+=seq[num],
seq1+='CYA',
elif seq[num+1]=='T':
CYT+=seq[num],
seq1+='CYT',
else:
seq1+=seq[num],
else:
seq1+=seq[num],
seq1+=seq[-3:]
change_num=min(len(TCRC),len(CYC))
TCRC[:change_num],CYC[:change_num]=CYC[:change_num],TCRC[:change_num]
change_num=min(len(TCRA),len(CYA))
TCRA[:change_num],CYA[:change_num]=CYA[:change_num],TCRA[:change_num]
change_num=min(len(TCRG),len(CYG))
TCRG[:change_num],CYG[:change_num]=CYG[:change_num],TCRG[:change_num]
change_num=min(len(TCRT),len(CYT))
TCRT[:change_num],CYT[:change_num]=CYT[:change_num],TCRT[:change_num]
shuffle(TCRC),shuffle(TCRA),shuffle(TCRG),shuffle(TCRT),shuffle(CYC),shuffle(CYA),shuffle(CYG),shuffle(CYT)
seq2=''
for i in xrange(len(seq1)):
if seq1[i]=='TCRC':seq2+=TCRC.pop(0)
elif seq1[i]=='TCRA':seq2+=TCRA.pop(0)
elif seq1[i]=='TCRG':seq2+=TCRG.pop(0)
elif seq1[i]=='TCRT':seq2+=TCRT.pop(0)
elif seq1[i]=='CYT':seq2+=CYT.pop(0)
elif seq1[i]=='CYA':seq2+=CYA.pop(0)
elif seq1[i]=='CYG':seq2+=CYG.pop(0)
elif seq1[i]=='CYC':seq2+=CYC.pop(0)
else:seq2+=seq1[i]
seq=seq2#convertion is finished
#ATCY,AAGY conversion to BTCY,BAGY
seq1=[]
AAA_R,GAA_N,GAA_R,CAA_N,TAA_R,TAA_N,TAA_H,AAT_R,GAT_N,GAT_R,CAT_N,TAT_R,TAT_N,TAT_H=[],[],[],[],[],[],[],[],[],[],[],[],[],[]
AGA_R,GBA_N,GGA_R,TGA_R,TBA_N,TYA_H,AGT_R,GBT_N,GGT_R,CBT_N,TGT_R,TBT_N,TYT_H,CBA_N=[],[],[],[],[],[],[],[],[],[],[],[],[],[]
for num in xrange(2,len(seq)-2,3):
seq1+=seq[num-2:num]
if seq[num:num+4]=='AAGC'or seq[num:num+4]=='AAGT':
if seq[num-2:num]=='CA'or seq[num-2:num]=='AA'or seq[num-2:num]=='GA':
AAA_R+=seq[num],
seq1+='AAA_R',
elif seq[num-2:num]=='CG'or seq[num-2:num]=='GG':
GAA_N+=seq[num],
seq1+='GAA_N',
elif seq[num-2:num]=='AG':
GAA_R+=seq[num],
seq1+='GAA_R',
elif seq[num-2:num]=='CC'or seq[num-2:num]=='AC'or seq[num-2:num]=='GC':
CAA_N+=seq[num],
seq1+='CAA_N',
elif seq[num-2:num]=='TT':
TAA_R+=seq[num],
seq1+='TAA_R',
elif seq[num-2:num]=='CT'or seq[num-2:num]=='GT':
TAA_N+=seq[num],
seq1+='TAA_N',
elif seq[num-2:num]=='AT':
TAA_H+=seq[num],
seq1+='TAA_H',
else:
seq1+=seq[num]
elif seq[num:num+4]=='ATCC'or seq[num:num+4]=='ATCT':
if seq[num-2:num]=='CA'or seq[num-2:num]=='AA'or seq[num-2:num]=='GA':
AAT_R+=seq[num],
seq1+='AAT_R',
elif seq[num-2:num]=='CG'or seq[num-2:num]=='GG':
GAT_N+=seq[num],
seq1+='GAT_N',
elif seq[num-2:num]=='AG':
GAT_R+=seq[num],
seq1+='GAT_R',
elif seq[num-2:num]=='CC'or seq[num-2:num]=='AC'or seq[num-2:num]=='GC':
CAT_N+=seq[num],
seq1+='CAT_N',
elif seq[num-2:num]=='TT':
TAT_R+=seq[num],
seq1+='TAT_R',
elif seq[num-2:num]=='CT'or seq[num-2:num]=='GT':
TAT_N+=seq[num],
seq1+='TAT_N',
elif seq[num-2:num]=='AT':
TAT_H+=seq[num],
seq1+='TAT_H',
else:
seq1+=seq[num]
elif seq[num+1:num+4]!='AGC'and seq[num+1:num+4]!='AGT'and seq[num+1]=='A'and seq[num]!='A':
if seq[num-2:num+1]=='CAG'or seq[num-2:num+1]=='AAG'or seq[num-2:num+1]=='GAG':
AGA_R+=seq[num],
seq1+='AGA_R',
elif seq[num-2:num]=='CG'or seq[num-2:num]=='GG':
GBA_N+=seq[num],
seq1+='GBA_N',
elif seq[num-2:num+1]=='AGG':
GGA_R+=seq[num],
seq1+='GGA_R',
elif seq[num-2:num]=='CC'or seq[num-2:num]=='AC'or seq[num-2:num]=='GC':
CBA_N+=seq[num],
seq1+='CBA_N',
elif seq[num-2:num+1]=='TTG':
TGA_R+=seq[num],
seq1+='TGA_R',
elif seq[num-2:num]=='CT'or seq[num-2:num]=='GT':
TBA_N+=seq[num],
seq1+='TBA_N',
elif seq[num-2:num]=='AT'and seq[num]!='G':
TYA_H+=seq[num],
seq1+='TYA_H',
else:
seq1+=seq[num]
elif seq[num+1:num+4]!='TCC'and seq[num+1:num+4]!='TCT'and seq[num+1]=='T'and seq[num]!='A':
if seq[num-2:num+1]=='CAG'or seq[num-2:num+1]=='AAG'or seq[num-2:num+1]=='GAG':
AGT_R+=seq[num],
seq1+='AGT_R',
elif seq[num-2:num]=='CG'or seq[num-2:num]=='GG':
GBT_N+=seq[num],
seq1+='GBT_N',
elif seq[num-2:num+1]=='AGG':
GGT_R+=seq[num],
seq1+='GGT_R',
elif seq[num-2:num]=='CC'or seq[num-2:num]=='AC'or seq[num-2:num]=='GC':
CBT_N+=seq[num],
seq1+='CBT_N',
elif seq[num-2:num+1]=='TTG':
TGT_R+=seq[num],
seq1+='TGT_R',
elif seq[num-2:num]=='CT'or seq[num-2:num]=='GT':
TBT_N+=seq[num],
seq1+='TBT_N',
elif seq[num-2:num]=='AT'and seq[num]!='G':
TYT_H+=seq[num],
seq1+='TYT_H',
else:
seq1+=seq[num]
else:
seq1+=seq[num]
seq1+=seq[-3:]
change_num=min(len(AAA_R),len(AGA_R))
AAA_R[:change_num],AGA_R[:change_num]=AGA_R[:change_num],AAA_R[:change_num]
change_num=min(len(GAA_R),len(GGA_R))
GAA_R[:change_num],GGA_R[:change_num]=GGA_R[:change_num],GAA_R[:change_num]
change_num=min(len(TAA_R),len(TGA_R))
TAA_R[:change_num],TGA_R[:change_num]=TGA_R[:change_num],TAA_R[:change_num]
change_num=min(len(AAT_R),len(AGT_R))
AAT_R[:change_num],AGT_R[:change_num]=AGT_R[:change_num],AAT_R[:change_num]
change_num=min(len(GAT_R),len(GGT_R))
GAT_R[:change_num],GGT_R[:change_num]=GGT_R[:change_num],GAT_R[:change_num]
change_num=min(len(TAT_R),len(TGT_R))
TAT_R[:change_num],TGT_R[:change_num]=TGT_R[:change_num],TAT_R[:change_num]
change_num=min(len(TAT_H),len(TYT_H))
TAT_H[:change_num],TYT_H[:change_num]=TYT_H[:change_num],TAT_H[:change_num]
change_num=min(len(TAA_H),len(TYA_H))
TAA_H[:change_num],TYA_H[:change_num]=TYA_H[:change_num],TAA_H[:change_num]
change_num=min(len(CAA_N),len(CBA_N))
CAA_N[:change_num],CBA_N[:change_num]=CBA_N[:change_num],CAA_N[:change_num]
change_num=min(len(GAA_N),len(GBA_N))
GAA_N[:change_num],GBA_N[:change_num]=GBA_N[:change_num],GAA_N[:change_num]
change_num=min(len(TAA_N),len(TBA_N))
TAA_N[:change_num],TBA_N[:change_num]=TBA_N[:change_num],TAA_N[:change_num]
change_num=min(len(GAT_N),len(GBT_N))
GAT_N[:change_num],GBT_N[:change_num]=GBT_N[:change_num],GAT_N[:change_num]
change_num=min(len(CAT_N),len(CBT_N))
CAT_N[:change_num],CBT_N[:change_num]=CBT_N[:change_num],CAT_N[:change_num]
change_num=min(len(TAT_N),len(TBT_N))
TAT_N[:change_num],TBT_N[:change_num]=TBT_N[:change_num],TAT_N[:change_num]
shuffle(AAA_R),shuffle(GAA_N),shuffle(GAA_R),shuffle(CAA_N),shuffle(TAA_R),shuffle(TAA_N),shuffle(TAA_H),shuffle(AAT_R),shuffle(GAT_N),shuffle(GAT_R),shuffle(CAT_N),shuffle(TAT_R),shuffle(TAT_N),shuffle(TAT_H),shuffle(AGA_R),shuffle(GBA_N),shuffle(GGA_R),shuffle(TGA_R),shuffle(TBA_N),shuffle(TYA_H),shuffle(AGT_R),shuffle(GBT_N),shuffle(GGT_R),shuffle(CBT_N),shuffle(TGT_R),shuffle(TBT_N),shuffle(TYT_H),shuffle(CBA_N)
seq2=''
for i in xrange(len(seq1)):
if seq1[i]=='AAA_R':seq2+=AAA_R.pop(0)
elif seq1[i]=='GAA_N':seq2+=GAA_N.pop(0)
elif seq1[i]=='GAA_R':seq2+=GAA_R.pop(0)
elif seq1[i]=='CAA_N':seq2+=CAA_N.pop(0)
elif seq1[i]=='TAA_R':seq2+=TAA_R.pop(0)
elif seq1[i]=='TAA_N':seq2+=TAA_N.pop(0)
elif seq1[i]=='TAA_H':seq2+=TAA_H.pop(0)
elif seq1[i]=='AAT_R':seq2+=AAT_R.pop(0)
elif seq1[i]=='GAT_N':seq2+=GAT_N.pop(0)
elif seq1[i]=='GAT_R':seq2+=GAT_R.pop(0)
elif seq1[i]=='CAT_N':seq2+=CAT_N.pop(0)
elif seq1[i]=='TAT_R':seq2+=TAT_R.pop(0)
elif seq1[i]=='TAT_N':seq2+=TAT_N.pop(0)
elif seq1[i]=='TAT_H':seq2+=TAT_H.pop(0)
elif seq1[i]=='AGA_R':seq2+=AGA_R.pop(0)
elif seq1[i]=='GBA_N':seq2+=GBA_N.pop(0)
elif seq1[i]=='GGA_R':seq2+=GGA_R.pop(0)
elif seq1[i]=='TGA_R':seq2+=TGA_R.pop(0)
elif seq1[i]=='TBA_N':seq2+=TBA_N.pop(0)
elif seq1[i]=='TYA_H':seq2+=TYA_H.pop(0)
elif seq1[i]=='AGT_R':seq2+=AGT_R.pop(0)
elif seq1[i]=='GBT_N':seq2+=GBT_N.pop(0)
elif seq1[i]=='GGT_R':seq2+=GGT_R.pop(0)
elif seq1[i]=='CBT_N':seq2+=CBT_N.pop(0)
elif seq1[i]=='TGT_R':seq2+=TGT_R.pop(0)
elif seq1[i]=='TBT_N':seq2+=TBT_N.pop(0)
elif seq1[i]=='TYT_H':seq2+=TYT_H.pop(0)
elif seq1[i]=='CBA_N':seq2+=CBA_N.pop(0)
else:seq2+=seq1[i]
seq=seq2#ATCY,AAGY conversion to BTCY,BAGY is finished
seq1=[]#tAGT SER codon could be converted to tTCT, preserving overall dinucleotide content, if in other positions in sequence
#tTg will be replaced with tAG, and tCt will be replaced with tGt, and vice versa.
#Using the same logic, SER codons ending with Y could be replaced, according to the third nucleotide of previous codon.
GTG,GAG=[],[]#G_SER
CTG,CAG=[],[]#C_SER
TTG,TAG=[],[]#T_SER
TCC,TGC=[],[]#SER_C
TCT,TGT=[],[]#SER_T
GAGC,CAGC,TAGC,GAGT,CAGT,TAGT=[],[],[],[],[],[]
GTCC,CTCC,TTCC,GTCT,CTCT,TTCT=[],[],[],[],[],[]
for num in xrange(2,len(seq)-3,3):
if seq[num-2:num]=='AG'and(seq[num]=='C'or seq[num]=='T')and(seq[num-3]=='G'or seq[num-3]=='C'or seq[num-3]=='T'):
if seq[num-3]=='G':
if seq[num]=='C':
seq1+='GAGC','C'
GAGC+=seq[num-2:num],
elif seq[num]=='T':
seq1+='GAGT','T'
GAGT+=seq[num-2:num],
elif seq[num-3]=='C':
if seq[num]=='C':
seq1+='CAGC','C'
CAGC+=seq[num-2:num],
elif seq[num]=='T':
seq1+='CAGT','T'
CAGT+=seq[num-2:num],
elif seq[num-3]=='T':
if seq[num]=='C':
seq1+='TAGC','C'
TAGC+=seq[num-2:num],
elif seq[num]=='T':
seq1+='TAGT','T'
TAGT+=seq[num-2:num],
elif seq[num-2:num]=='TC'and(seq[num]=='C'or seq[num]=='T')and(seq[num-3]=='G'or seq[num-3]=='C'or seq[num-3]=='T'):
if seq[num-3]=='G':
if seq[num]=='C':
seq1+='GTCC','C'
GTCC+=seq[num-2:num],
elif seq[num]=='T':
seq1+='GTCT','T'
GTCT+=seq[num-2:num],
elif seq[num-3]=='C':
if seq[num]=='C':
seq1+='CTCC','C'
CTCC+=seq[num-2:num],
elif seq[num]=='T':
seq1+='CTCT','T'
CTCT+=seq[num-2:num],
elif seq[num-3]=='T':
if seq[num]=='C':
seq1+='TTCC','C'
TTCC+=seq[num-2:num],
elif seq[num]=='T':
seq1+='TTCT','T'
TTCT+=seq[num-2:num],
elif seq[num-1:num+2]=='GTG'and(seq[num-2:num]=='CG'or seq[num-2:num]=='GG'):
seq1+=seq[num-2:num],'GTG',
GTG+=seq[num],
elif seq[num-1:num+2]=='GAG'and(seq[num-2:num]=='CG'or seq[num-2:num]=='GG'):
seq1+=seq[num-2:num],'GAG',
GAG+=seq[num],
elif seq[num-1:num+2]=='CTG'and(seq[num-2:num]=='AC'or seq[num-2:num]=='GC'or seq[num-2:num]=='CC'):
seq1+=seq[num-2:num],'CTG',
CTG+=seq[num],
elif seq[num-1:num+2]=='CAG'and(seq[num-2:num]=='AC'or seq[num-2:num]=='GC'or seq[num-2:num]=='CC'):
seq1+=seq[num-2:num],'CAG',
CAG+=seq[num],
elif seq[num-1:num+2]=='TTG'and(seq[num-2:num]=='AT'or seq[num-2:num]=='GT'or seq[num-2:num]=='CT'):
seq1+=seq[num-2:num],'TTG',
TTG+=seq[num],
elif seq[num-1:num+2]=='TAG'and(seq[num-2:num]=='AT'or seq[num-2:num]=='GT'or seq[num-2:num]=='CT'):
seq1+=seq[num-2:num],'TAG',
TAG+=seq[num],
elif seq[num-1:num+2]=='TCC'and(seq[num-2:num]=='GT'or seq[num-2:num]=='CT'):
seq1+=seq[num-2:num],'TCC',
TCC+=seq[num],
elif seq[num-1:num+2]=='TGC'and(seq[num-2:num]=='GT'or seq[num-2:num]=='CT'):
seq1+=seq[num-2:num],'TGC',
TGC+=seq[num],
elif seq[num-1:num+2]=='TCT'and(seq[num-2:num]=='GT'or seq[num-2:num]=='CT')and seq[num+1:num+4]!='TCC'and seq[num+1:num+4]!='TCT':
seq1+=seq[num-2:num],'TCT',
TCT+=seq[num],
elif seq[num-1:num+2]=='TGT'and(seq[num-2:num]=='GT'or seq[num-2:num]=='CT')and seq[num+1:num+4]!='TCC'and seq[num+1:num+4]!='TCT':
seq1+=seq[num-2:num],'TGT',
TGT+=seq[num],
else:
seq1+=seq[num-2:num+1]
seq1+=seq[-3:]
gAGc=min(len(GAGC),len(GTG),len(TCC))
gTCc=min(len(GTCC),len(GAG),len(TGC))
gAGt=min(len(GAGT),len(GTG),len(TCT))
gTCt=min(len(GTCT),len(GAG),len(TGT))
cAGc=min(len(CAGC),len(CTG),len(TCC))
cTCc=min(len(CTCC),len(CAG),len(TGC))
cAGt=min(len(CAGT),len(CTG),len(TCT))
cTCt=min(len(CTCT),len(CAG),len(TGT))
tAGc=min(len(TAGC),len(TTG),len(TCC))
tTCc=min(len(TTCC),len(TAG),len(TGC))
tAGt=min(len(TAGC),len(TTG),len(TCT))
tTCt=min(len(TTCC),len(TAG),len(TGT))
if gAGc+gAGt>len(GTG):
gAGc,gAGt=round(gAGc*(len(GTG)/float(gAGc+gAGt))),round(gAGt*(len(GTG)/float(gAGc+gAGt)))
gAGc,gAGt=int(gAGc),int(gAGt)
if gTCc+gTCt>len(GAG):
gTCc,gTCt=round(gTCc*(len(GAG)/float(gTCc+gTCt))),round(gTCt*(len(GAG)/float(gTCc+gTCt)))
gTCc,gTCt=int(gTCc),int(gTCt)
if cAGc+cAGt>len(CTG):
cAGc,cAGt=round(cAGc*(len(CTG)/float(cAGc+cAGt))),round(cAGt*(len(CTG)/float(cAGc+cAGt)))
cAGc,cAGt=int(cAGc),int(cAGt)
if cTCc+cTCt>len(CAG):
cTCc,cTCt=round(cTCc*(len(CAG)/float(cTCc+cTCt))),round(cTCt*(len(CAG)/float(cTCc+cTCt)))
cTCc,cTCt=int(cTCc),int(cTCt)
if tAGc+tAGt>len(TTG):
tAGc,tAGt=round(tAGc*(len(TTG)/float(tAGc+tAGt))),round(tAGt*(len(TTG)/float(tAGc+tAGt)))
tAGc,tAGt=int(tAGc),int(tAGt)
if tTCc+tTCt>len(TAG):
tTCc,tTCt=round(tTCc*(len(TAG)/float(tTCc+tTCt))),round(tTCt*(len(TAG)/float(tTCc+tTCt)))
tTCc,tTCt=int(tTCc),int(tTCt)
if gAGc+cAGc+tAGc>len(TCC):
gAGc,cAGc,tAGc=round(gAGc*(len(TCC)/float(gAGc+cAGc+tAGc))),round(cAGc*(len(TCC)/float(gAGc+cAGc+tAGc))),round(tAGc*(len(TCC)/float(gAGc+cAGc+tAGc)))
gAGc,cAGc,tAGc=int(gAGc),int(cAGc),int(tAGc)
if gAGt+cAGt+tAGt>len(TCT):
gAGt,cAGt,tAGt=round(gAGt*(len(TCT)/float(gAGt+cAGt+tAGt))),round(cAGt*(len(TCT)/float(gAGt+cAGt+tAGt))),round(tAGt*(len(TCT)/float(gAGt+cAGt+tAGt)))
gAGt,cAGt,tAGt=int(gAGt),int(cAGt),int(tAGt)
if gTCc+cTCc+tTCc>len(TGC):
gTCc,cTCc,tTCc=round(gTCc*(len(TGC)/float(gTCc+cTCc+tTCc))),round(cTCc*(len(TGC)/float(gTCc+cTCc+tTCc))),round(tTCc*(len(TGC)/float(gTCc+cTCc+tTCc)))
gTCc,cTCc,tTCc=int(gTCc),int(cTCc),int(tTCc)
if gTCt+cTCt+tTCt>len(TGT):
gTCt,cTCt,tTCt=round(gTCt*(len(TGT)/float(gTCt+cTCt+tTCt))),round(cTCt*(len(TGT)/float(gTCt+cTCt+tTCt))),round(tTCt*(len(TGT)/float(gTCt+cTCt+tTCt)))
gTCt,cTCt,tTCt=int(gTCt),int(cTCt),int(tTCt)
#GAGC,GTG,TCC
change_num=randint(0,gAGc)
for i in xrange(change_num):
GAGC[i]='TC'
del GTG[0];GTG.append('A')
del TCC[0];TCC.append('G')
#GTCC,GAG,TGC
change_num=randint(0,gTCc)
for i in xrange(change_num):
GTCC[i]='AG'
del GAG[0];GAG.append('T')
del TGC[0];TGC.append('C')
#GAGT,GTG,TCT
change_num=randint(0,gAGt)
for i in xrange(change_num):
GAGT[i]='TC'
del GTG[0];GTG.append('A')
del TCT[0];TCT.append('G')
#GTCT,GAG,TGT
change_num=randint(0,gTCt)
for i in xrange(change_num):
GTCT[i]='AG'
del GAG[0];GAG.append('T')
del TGT[0];TGT.append('C')
#CAGC,CTG,TCC
change_num=randint(0,cAGc)
for i in xrange(change_num):
CAGC[i]='TC'
del CTG[0];CTG.append('A')
del TCC[0];TCC.append('G')
#CTCC,CAG,TGC
change_num=randint(0,cTCc)
for i in xrange(change_num):
CTCC[i]='AG'
del CAG[0];CAG.append('T')
del TGC[0];TGC.append('C')
#CAGT,CTG,TCT
change_num=randint(0,cAGt)
for i in xrange(change_num):
CAGT[i]='TC'
del CTG[0];CTG.append('A')
del TCT[0];TCT.append('G')
#CTCT,CAG,TGT
change_num=randint(0,cTCt)
for i in xrange(change_num):
CTCT[i]='AG'
del CAG[0];CAG.append('T')
del TGT[0];TGT.append('C')
#TAGC,TTG,TCC
change_num=randint(0,tAGc)
for i in xrange(change_num):
TAGC[i]='TC'
del TTG[0];TTG.append('A')
del TCC[0];TCC.append('G')
#TTCC,TAG,TGC
change_num=randint(0,tTCc)
for i in xrange(change_num):
TTCC[i]='AG'
del TAG[0];TAG.append('T')
del TGC[0];TGC.append('C')
#TAGC,TTG,TCT
change_num=randint(0,tAGt)
for i in xrange(change_num):
TAGC[i]='TC'
del TTG[0];TTG.append('A')
del TCT[0];TCT.append('G')
#tTCt=min(len(TTCC),len(TAG),len(TGT))
change_num=randint(0,tTCt)
for i in xrange(change_num):
TTCC[i]='AG'
del TAG[0];TAG.append('T')
del TGT[0];TGT.append('C')
shuffle(GTG),shuffle(GAG),shuffle(CTG),shuffle(CAG),shuffle(TTG),shuffle(TAG),shuffle(TCC),shuffle(TGC),shuffle(TCT),shuffle(TGT)
shuffle(GAGC),shuffle(CAGC),shuffle(TAGC),shuffle(GAGT),shuffle(CAGT),shuffle(TAGT)
shuffle(GTCC),shuffle(CTCC),shuffle(TTCC),shuffle(GTCT),shuffle(CTCT),shuffle(TTCT)
seq2=''
for i in xrange(len(seq1)):
if seq1[i]=='GTG':seq2+=GTG.pop(0)
elif seq1[i]=='GAG':seq2+=GAG.pop(0)
elif seq1[i]=='CTG':seq2+=CTG.pop(0)
elif seq1[i]=='CAG':seq2+=CAG.pop(0)
elif seq1[i]=='TTG':seq2+=TTG.pop(0)
elif seq1[i]=='TAG':seq2+=TAG.pop(0)
elif seq1[i]=='TCC':seq2+=TCC.pop(0)
elif seq1[i]=='TGC':seq2+=TGC.pop(0)
elif seq1[i]=='TCT':seq2+=TCT.pop(0)
elif seq1[i]=='TGT':seq2+=TGT.pop(0)
elif seq1[i]=='GAGC':seq2+=GAGC.pop(0)
elif seq1[i]=='CAGC':seq2+=CAGC.pop(0)
elif seq1[i]=='TAGC':seq2+=TAGC.pop(0)
elif seq1[i]=='GAGT':seq2+=GAGT.pop(0)
elif seq1[i]=='CAGT':seq2+=CAGT.pop(0)
elif seq1[i]=='TAGT':seq2+=TAGT.pop(0)
elif seq1[i]=='GTCC':seq2+=GTCC.pop(0)
elif seq1[i]=='CTCC':seq2+=CTCC.pop(0)
elif seq1[i]=='TTCC':seq2+=TTCC.pop(0)
elif seq1[i]=='GTCT':seq2+=GTCT.pop(0)
elif seq1[i]=='CTCT':seq2+=CTCT.pop(0)
elif seq1[i]=='TTCT':seq2+=TTCT.pop(0)
else:seq2+=seq1[i]
seq=seq2
#ARG
#shuffling of the first codon position of aginine codons requires convertion of CGY to CGR.
#then the first codon positions of AGR and CGR are shuffled with the third codon position of other codons
#aminoacid sequence and overall dinucleotide content are maintained
seq1=[]
GYA,GYT,GYC,GYG=[],[],[],[]
GRA=[]#only gly
GRT,GRC,GRG=[],[],[]
for num in xrange(2,len(seq)-3,3):
seq1+=seq[num-2:num]
if seq[num-2:num]=='CG' and(seq[num]=='C'or seq[num]=='T'):
if seq[num+1]=='A':
GYA+=seq[num],
seq1+='GYA',
elif seq[num+1]=='T':
GYT+=seq[num],
seq1+='GYT',
elif seq[num+1]=='C':
GYC+=seq[num],
seq1+='GYC',
elif seq[num+1]=='G':
GYG+=seq[num],
seq1+='GYG',
else:
seq1+=seq[num],
elif seq[num-2:num]=='GG' and(seq[num]=='A'or seq[num]=='G'):#only gly
if seq[num+1]=='A':
GRA+=seq[num],
seq1+='GRA',
elif seq[num+1]=='T':
GRT+=seq[num],
seq1+='GRT',
elif seq[num+1]=='C':
GRC+=seq[num],
seq1+='GRC',
elif seq[num+1]=='G':
GRG+=seq[num],
seq1+='GRG',
else:
seq1+=seq[num],
else:
seq1+=seq[num],
seq1+=seq[-3:]
change_num=min(len(GYA),len(GRA))
GYA[:change_num],GRA[:change_num]=GRA[:change_num],GYA[:change_num]
change_num=min(len(GYT),len(GRT))
GYT[:change_num],GRT[:change_num]=GRT[:change_num],GYT[:change_num]
change_num=min(len(GYC),len(GRC))
GYC[:change_num],GRC[:change_num]=GRC[:change_num],GYC[:change_num]
change_num=min(len(GYG),len(GRG))
GYG[:change_num],GRG[:change_num]=GRG[:change_num],GYG[:change_num]
shuffle(GYA),shuffle(GYT),shuffle(GYC),shuffle(GYG),shuffle(GRA),shuffle(GRG),shuffle(GRC),shuffle(GRT)
seq2=''
for i in xrange(len(seq1)):
if seq1[i]=='GYA':seq2+=GYA.pop(0)
elif seq1[i]=='GRA':seq2+=GRA.pop(0)
elif seq1[i]=='GYT':seq2+=GYT.pop(0)
elif seq1[i]=='GRT':seq2+=GRT.pop(0)
elif seq1[i]=='GYC':seq2+=GYC.pop(0)
elif seq1[i]=='GRC':seq2+=GRC.pop(0)
elif seq1[i]=='GYG':seq2+=GYG.pop(0)
elif seq1[i]=='GRG':seq2+=GRG.pop(0)
else:seq2+=seq1[i]
seq=seq2
seq1=[]
CGTG,CGCG,GTG,GCG,GAG=[],[],[],[],[]
seq1+=seq[:2]
for num in xrange(2,len(seq)-2,1):
if seq[num-2:num+2]=='CGCG' and num%3==2:
CGCG+=seq[num],
seq1+='CGYG',
elif seq[num-2:num+2]=='CGTG' and num%3==2:
CGTG+=seq[num],
seq1+='CGYG',
elif seq[num-1:num+2]=='GTG' and seq[num-2]!='C' and num%3==2:
GTG+=seq[num],
seq1+='GTG',
elif seq[num-1:num+2]=='GCG' and seq[num-2]!='C' and num%3==2:
GCG+=seq[num],
seq1+='GCG',
elif (seq[num-1:num+3]=='GAGA' or seq[num-1:num+3]=='GAGG')and num%3==0:
GAG+=seq[num],
seq1+='GAG',
else:
seq1+=seq[num],
seq1+=seq[-2:]
CGYG=[]
change_num=min(len(CGTG),len(GCG))
CGYG[:change_num],GCG[:change_num]=GCG[:change_num],CGTG[:change_num]
CGTG_num=change_num
CGYG+=CGCG
change_num=min(len(CGYG),len(GAG))
CGYG[:change_num],GAG[:change_num]=GAG[:change_num],CGYG[:change_num]
CGYG+=CGTG[CGTG_num:]
shuffle(CGYG),shuffle(GTG),shuffle(GCG),shuffle(GAG)
seq2=''
for i in xrange(len(seq1)):
if seq1[i]=='CGYG':seq2+=CGYG.pop(0)
elif seq1[i]=='GTG':seq2+=GTG.pop(0)
elif seq1[i]=='GCG':seq2+=GCG.pop(0)
elif seq1[i]=='GAG':seq2+=GAG.pop(0)
else:seq2+=seq1[i]
seq=seq2
seq1=[]
TMG,AMG,GMG,CMG=[],[],[],[]
seq1+=seq[:2],
for num in xrange(2,len(seq)-2,1):
if (num%3==0 and(seq[num:num+3]=='CGA' or seq[num:num+3]=='CGG' or seq[num:num+3]=='AGA' or seq[num:num+3]=='AGG'))or(num%3==2 and (seq[num:num+2]=='CG' or seq[num:num+2]=='AG')and((seq[num-1]=='T'and seq[num-2]!='T')or seq[num-1]=='C'or seq[num-2:num]=='GG')):
if seq[num-1]=='T':
seq1+='TMG',
TMG+=seq[num],
elif seq[num-1]=='C':
seq1+='CMG',
CMG+=seq[num],
elif seq[num-1]=='A':
seq1+='AMG',
AMG+=seq[num],
elif seq[num-1]=='G':
seq1+='GMG',
GMG+=seq[num],
else:
seq1+=seq[num]
else:
seq1+=seq[num]
seq1+=seq[-2:]
shuffle(TMG),shuffle(GMG),shuffle(AMG),shuffle(CMG)
seq2=''
for i in xrange(len(seq1)):
if seq1[i]=='TMG':seq2+=TMG.pop(0)
elif seq1[i]=='AMG':seq2+=AMG.pop(0)
elif seq1[i]=='GMG':seq2+=GMG.pop(0)
elif seq1[i]=='CMG':seq2+=CMG.pop(0)
else:seq2+=seq1[i]
return seq2
def get_difference(seq1,seq2):
assert len(seq1) == len(seq2)
return sum(seq1 != seq2 for seq1, seq2 in zip(seq1,seq2))
def make_protein_record(nuc_record):
"""Returns a new SeqRecord with the translated sequence (default table)."""
return SeqRecord(seq = nuc_record.seq.translate(to_stop=True), \
id = "trans_" + nuc_record.id, \
description = "translation of CDS, using default table")
# main script body that calls the above subroutines
#Shuffle Script
# -*- coding: cp1251 -*-
#Input Data
parser = argparse.ArgumentParser(description='CodonShuffle.')
parser.add_argument('-i', nargs='?', help='Input Filename', required=True, dest="input_file_name")
parser.add_argument('-s', choices=['dn23', 'dn31', 'dn231', 'n3'], nargs='?', help='Type of shuffle', default="dn23", dest="random_type")
parser.add_argument('-r', nargs='?', help='Number of replications (int)', default='1000', dest="reps", type=int)
parser.add_argument('-m', choices=['CAI', 'CPB', 'DN', 'ENC', 'VFOLD', 'UFOLD', 'all'], nargs='*', help='Control Features [select one, multiple, or all]', default='all', dest="modules")
parser.add_argument('-g', dest="graphics", help='Generate Feature Plots', action="store_true")
parser.add_argument('--seed', type=int, nargs='?', dest='randomseed', help='Optional integer for random seed', const=99)
args = parser.parse_args()
if args.randomseed is not None:
seed(args.randomseed)
types_of_rnd=args.random_type
infile=open(args.input_file_name,'r')
names_list=[]
data={}
for line in infile:
if line[0]=='>':
strain=line
data[strain]=''
names_list+=strain,
else:
for liter in line:
if liter!='\n' and liter!='-' and liter!='~':
data[strain]+=liter
infile.close()
out_names=[]
for strain in names_list:
seq_name=''
for liter in strain:
if liter =='\\' or liter =='/' or liter ==' ' or liter =='-' or liter ==',' or liter=='|' or liter==':': # compatible file names
seq_name+='_'
else:
seq_name+=liter
inseq_file=open(seq_name[1:-1]+'.fas','w')
inseq_file.write(strain+data[strain]+'\n')
inseq_file.close()
# bat_enc='chips -seqall '+seq_name[1:-1]+'.fas -nosum -outfile '+seq_name[1:-1]+'.enc -auto\n'
# system(bat_enc)
outfile=open(seq_name[1:-1]+'_'+args.random_type+'.fas','w') #Create the file with wild type in the first position
outfile.write(strain+data[strain]+'\n')
outfile.close()
outfile=open(seq_name[1:-1]+'_'+args.random_type+'.fas','a') #Append permuted sequence
for i in xrange(args.reps):
outseq=data[strain]
if args.random_type =='gc3':
outseq=gc3(outseq)
elif args.random_type == 'dn23':
outseq=dn23(outseq)
elif args.random_type=='dn31':
outseq=third(outseq)
elif args.random_type=='dn231':
outseq=third(exchange6deg(outseq))
elif args.random_type=='n3':
outseq=third_simple(outseq)
outfile.write('>replicate_'+str(i+1)+'\n'+outseq+'\n')
outfile.close()
# bat_enc='chips -seqall '+seq_name[1:-1]+'_'+args.random_type+'.fas -nosum -outfile '+seq_name[1:-1]+'_'+args.random_type+'.enc -auto\n'
# system(bat_enc)
first_tot_out_string=`args.reps`+'_replicas\nstrain\t\tstrain_Nc\t'
#if 'gc3'in types_of_rnd:first_tot_out_string+='\tmean_Nc_gc3\tsd\t'
if 'n3'in types_of_rnd:first_tot_out_string+='\tmean_Nc_n3\tsd\t'
if 'all'in types_of_rnd:first_tot_out_string+='\tmean_Nc_all\tsd\t'
if 'dn23'in types_of_rnd:first_tot_out_string+='\tmean_Nc_dn23\tsd\t'
if 'dn31'in types_of_rnd:first_tot_out_string+='\tmean_Nc_dn31\tsd\t'
if 'dn231'in types_of_rnd:first_tot_out_string+='\tmean_Nc_dn231\tsd\t'
# tot_out=open(args.input_file_name[:-4]+'.out','w') #output file writing
# tot_out.write(first_tot_out_string+'\n')
# for strain in names_list:
# seq_name=''
# for liter in strain:
# if liter =='\\' or liter =='/' or liter ==' ' or liter =='-' or liter ==',' or liter=='|':
# seq_name+='_'
# else:
# seq_name+=liter
# enc_in=open(seq_name[1:-1]+'.enc','r')
# inseq_enc=0.
# for i in enc_in:
# if strain[1:-1] in i:
# inseq_enc=float(i.split(' Nc = ')[1])
# enc_in.close()
#
# out_string=strain[1:-1]+'\t\t'+`inseq_enc`+'\t\t'
# enc_in=open(seq_name[1:-1]+'_'+args.random_type+'.enc','r')
# enc=[]
# for i in enc_in:
# enc+=float(i.split(' Nc = ')[1]),
# enc_in.close()
#
# mean_enc=sum(enc)/len(enc)
# dd=0
# for i in enc:d=(i-mean_enc)**2;dd+=d
# sd_enc=(dd/(len(enc)-1))**(0.5)
# out_string+=`mean_enc`+'\t'+`sd_enc`+'\t\t'
# out_string+='\n'
# tot_out.write(out_string)
# tot_out.close()
#filename.input(first_tot_out_string+'\n', inplace=1) #Add the wild type sequence in the variable
filename = seq_name[1:-1]+'_'+args.random_type+'.fas'
final_table=pandas.DataFrame()
#Calculate Sequence distance
print "Calculating Hamming distance"
seq_records=[]
inseq_file=open(filename,'rU')
outnt_file=open(filename+'.hamming', 'w')
for seq_record in SeqIO.parse(inseq_file, "fasta"):
seq_records.append(seq_record.seq)
n = len(seq_records)
least_squares = pandas.DataFrame(numpy.zeros(n))
my_array = np.zeros((n,n))
for i in range(0,n):
for j in range(i+1,n):
difference = get_difference(seq_records[i], seq_records[j])
outnt_file.write(str(difference)+'\n')
my_array[i, j] = difference
my_array[j, i] = difference
#nuc_dist = my_array.iloc[:,0]
outnt_file.close()
if args.graphics:
hamming_graphname = filename+'.hamming.pdf'
hamming_table = pandas.read_csv(filename+'.hamming', sep='\t', names=['distance'])
hamming_graph = ggplot(hamming_table, aes('distance'))+geom_density() +labs("Hamming distance","Frequency")+ggtitle(seq_name[1:-1]+'_'+args.random_type+' (Hamming)') #Get the name of the script
ggsave(hamming_graph, hamming_graphname)
if 'CAI' in args.modules or 'all' in args.modules:
#Run CAI and read result table
print "Calculating CAI"
cainame = seq_name[1:-1]+'_'+args.random_type+'.cai'
call(["./lib/EMBOSS-6.6.0/emboss/cai", "-seqall="+filename, "-outfile="+cainame, "-cfile=Ehuman.cut"]) #Insert path before cai in this line (CAI)
u_cols = ['a', 'sequence', 'b', 'cai']
cai_table = pandas.read_csv(cainame, sep=' ', names=u_cols)
cai_table = cai_table.drop('a', 1)
cai_table = cai_table.drop('b', 1)
cai_table_z = ((cai_table['cai'] - cai_table['cai'].mean()) / cai_table['cai'].std())
cai_table_wt_z = cai_table_z.iloc[0]
cai_table_wt_z_rep = np.repeat(cai_table_wt_z, len(cai_table_z))
cai_table_z_ls = (cai_table_wt_z_rep-cai_table_z)**2
least_squares = least_squares.add(cai_table_z_ls, axis=0)
# final_table=final_table.append(cai_table['cai'])
final_table.insert(0, "Cai", cai_table['cai'])
if args.graphics:
cai_graphname = cainame +'.pdf'
u_cols = ['a', 'sequence', 'b', 'cai']
cai_table = pandas.read_csv(cainame, sep=' ', names=u_cols)
cai_table = cai_table.drop('a', 1)
cai_table = cai_table.drop('b', 1)
cai_graph = ggplot(cai_table, aes('cai'))+geom_density() +labs("CAI","Frequency")+ geom_vline(xintercept = [cai_table['cai'].iloc[0]] , colour="red", linetype = "dashed") +ggtitle(seq_name[1:-1]+'_'+args.random_type+' (CAI)') #Get the name of the script
ggsave(cai_graph, cai_graphname)
if 'ENC' in args.modules or 'all' in args.modules:
# Run ENC and result table
print "Calculating ENC"
call(["./lib/codonW/codonw", filename, "-enc", "-nomenu", "-nowarn", "-silent"]) #Insert path before codonw in this line (ENC)
enc_filename = seq_name[1:-1]+'_'+args.random_type+'.out'
enc_table = pandas.read_csv(enc_filename, sep='\t')
enc_table = enc_table.drop('Unnamed: 2',1)
enc_table_z = ((enc_table['Nc'] - enc_table['Nc'].mean()) / enc_table['Nc'].std())
enc_table_wt_z = enc_table_z.iloc[0]
enc_table_wt_z_rep = np.repeat(enc_table_wt_z, len(enc_table_z))
enc_table_z_ls = (enc_table_wt_z_rep-enc_table_z)**2
least_squares = least_squares.add(enc_table_z_ls, axis=0)
# final_table=final_table.append(enc_table['Nc'])
final_table.insert(0, "ENC", enc_table['Nc'])
if args.graphics:
enc_filename = seq_name[1:-1]+'_'+args.random_type+'.out'
enc_graphname = enc_filename+'.enc.pdf'
enc_table = pandas.read_csv(enc_filename, sep='\t')
enc_table = enc_table.drop('Unnamed: 2',1)
enc_graph = ggplot(enc_table, aes('Nc'))+geom_density() +labs("ENC","Frequency")+ geom_vline(xintercept = [enc_table['Nc'].iloc[0]] , colour="red", linetype = "dashed") +ggtitle(seq_name[1:-1]+'_'+args.random_type+' (ENC)') #Get the name of the script
ggsave(enc_graph, enc_graphname)
if 'VFOLD' in args.modules or 'all' in args.modules:
#Read FOLD (minimum free energy) table
print "Calculating VFOLD"
foldname = seq_name[1:-1]+'_'+args.random_type+'.fold'
mfename = seq_name[1:-1]+'_'+args.random_type+'.mfe'
i = open(filename, "r")
o = open(foldname, "w")
call(["./lib/ViennaRNA-2.1.9/Progs/RNAfold", "--noPS"], stdin=i, stdout=o) #Insert path before RNAfold in this line (MFOLD)
i.close
o.close
# os.system("cat Poliovirus_1_Mahoney_P1_dn23.fold | sed 'N;N;s/\\n/ /g' | cut -f 4 -d ' ' | tr -d '()' > " + mfename)
# handle small energies by removing whitespace
with open(foldname, 'r') as sources:
lines = sources.readlines()
with open(foldname, 'w') as sources:
for line in lines:
sources.write(re.sub('[(] +-', '(-', line))
fold_tb = open(foldname, "r").read().split()
fold_file=open(filename+'fold_table_mfe.txt', 'w')
for i in range(3, len(fold_tb)-3, 4):
fold_mfe = fold_tb[3]+'\n'+fold_tb[i+4]
fold_file.write(str(fold_mfe)+'\n')
fold_file.close()
fold_table = pandas.read_csv(filename+'fold_table_mfe.txt', names=['mfe'])
fold_table['mfe'] = fold_table['mfe'].map(lambda x: x.lstrip('(').rstrip(')'))
fold_table['mfe']=fold_table.apply(lambda row: float(row['mfe']), axis=1)
fold_table_z = ((fold_table['mfe'] - fold_table['mfe'].mean()) / fold_table['mfe'].std())
fold_table_wt_z = fold_table_z.iloc[0]
fold_table_wt_z_rep = np.repeat(fold_table_wt_z, len(fold_table_z))
fold_table_z_ls = (fold_table_wt_z_rep-fold_table_z)**2
least_squares = least_squares.add(fold_table_z_ls, axis=0)
# final_table=final_table.append(fold_table['mfe'])
final_table.insert(0, "VFOLD (mfe)", fold_table['mfe'])
if args.graphics:
fold_graphname = seq_name[1:-1]+'_'+args.random_type+'.fold.pdf'
# fold_table = pandas.read_csv(mfename, names=['mfe'])
fold_graph = ggplot(fold_table, aes('mfe'))+geom_density() +labs("MFE","Frequency")+ geom_vline(xintercept = [fold_table['mfe'].iloc[0]] , colour="red", linetype = "dashed") +ggtitle(seq_name[1:-1]+'_'+args.random_type+' (FOLD)') #Get the name of the script
ggsave(fold_graph, fold_graphname)
if 'UFOLD' in args.modules:
#Read FOLD (minimum free energy) table
print "Calculating UFOLD"
foldname = seq_name[1:-1]+'_'+args.random_type+'.fold'
mfename = seq_name[1:-1]+'_'+args.random_type+'.fasta.dG'
i = open(filename, "r")
o = open(foldname, "w")
call(["hybrid-ss", "-E", "--output="+mfename, filename]) #Insert path before hybrid-ss in this line (UNAFOLD)
i.close
o.close
# os.system("cat Poliovirus_1_Mahoney_P1_dn23.fold | sed 'N;N;s/\\n/ /g' | cut -f 4 -d ' ' | tr -d '()' > " + mfename)
ufold_table = pandas.read_csv(mfename, sep=' ')
ufold_table_z = ((fold_table['-RT ln Z'] - fold_table['-RT ln Z'].mean()) / fold_table['-RT ln Z'].std())
ufold_table_wt_z = ufold_table_z.iloc[0]
ufold_table_wt_z_rep = np.repeat(ufold_table_wt_z, len(ufold_table_z))
ufold_table_z_ls = (fold_table_wt_z_rep-fold_table_z)**2
least_squares = least_squares.add(fold_table_z_ls, axis=0)
# final_table=final_table.append(ufold_table['-RT ln Z'])
final_table.insert(0, "UFOLD (mfe)", ufold_table['-RT ln Z'])
if args.graphics:
fold_graphname = seq_name[1:-1]+'_'+args.random_type+'.fold.pdf'
fold_table = pandas.read_csv(mfename, mfename, sep=' ')
fold_graph = ggplot(fold_table, aes('-RT ln Z'))+geom_density() +labs("MFE","Frequency")+ geom_vline(xintercept = [fold_table['-RT ln Z'].iloc[0]] , colour="red", linetype = "dashed") +ggtitle(seq_name[1:-1]+'_'+args.random_type+' (FOLD)') #Get the name of the script
ggsave(fold_graph, fold_graphname)
if 'DN' in args.modules or 'all' in args.modules:
print "Calculating DN"
dnname = seq_name[1:-1]+'_'+args.random_type+'.dn'
dn_file=open(dnname, 'w')
dn_file.write("id");
for nt1 in nts:
for nt2 in nts:
dinut = nt1+nt2
dn_file.write("\t"+dinut)
dn_file.write("\n")
for nuc_rec in SeqIO.parse(filename, "fasta"):
nucs = [str(nuc_rec.seq[i:i+1]) for i in range(0,len(nuc_rec.seq),1)]
dinucs = [str(nuc_rec.seq[i:i+2]) for i in range(0,len(nuc_rec.seq)-1,1)]
nuc_counts = Counter(nucs)
dinuc_counts = Counter(dinucs)
seq_len = len(nuc_rec.seq)
dn_file.write(nuc_rec.id)
for nt1 in nts:
for nt2 in nts:
dinut = nt1+nt2
if (dinut in dinuc_counts):
freq = (dinuc_counts[dinut] / (seq_len - 1)) / ( (nuc_counts[nt1] / seq_len) * (nuc_counts[nt2] / seq_len))
#print(nt1 + " " + nt2 + " " + str(freq) + " " + str(dinuc_counts[dinut]) + " " + str(nuc_counts[nt1]) + " " + str(nuc_counts[nt2]) + "\n")
dn_file.write("\t"+str(freq))
else:
dn_file.write("\t0")
dn_file.write("\n")
dn_file.close()
dnlsname = seq_name[1:- 1]+'_'+args.random_type+'.dnls'
# dn_least_file=open(dnlsname, 'w')
dn_table = pandas.read_csv(dnname, sep=' ')
dn_table_AA_wt = dn_table.iloc[0,1]
dn_table_AA_wt_rep = np.repeat(dn_table_AA_wt, len(dn_table['AA']))
dn_table_AC_wt = dn_table.iloc[0,2]
dn_table_AC_wt_rep = np.repeat(dn_table_AC_wt, len(dn_table['AC']))
dn_table_AG_wt = dn_table.iloc[0,3]
dn_table_AG_wt_rep = np.repeat(dn_table_AG_wt, len(dn_table['AG']))
dn_table_AT_wt = dn_table.iloc[0,4]
dn_table_AT_wt_rep = np.repeat(dn_table_AT_wt, len(dn_table['AT']))
dn_table_CA_wt = dn_table.iloc[0,5]
dn_table_CA_wt_rep = np.repeat(dn_table_CA_wt, len(dn_table['CA']))
dn_table_CC_wt = dn_table.iloc[0,6]
dn_table_CC_wt_rep = np.repeat(dn_table_CC_wt, len(dn_table['CC']))
dn_table_CG_wt = dn_table.iloc[0,7]
dn_table_CG_wt_rep = np.repeat(dn_table_CG_wt, len(dn_table['CG']))
dn_table_CT_wt = dn_table.iloc[0,8]
dn_table_CT_wt_rep = np.repeat(dn_table_CT_wt, len(dn_table['CT']))
dn_table_GA_wt = dn_table.iloc[0,9]
dn_table_GA_wt_rep = np.repeat(dn_table_GA_wt, len(dn_table['GA']))
dn_table_GC_wt = dn_table.iloc[0,10]
dn_table_GC_wt_rep = np.repeat(dn_table_GC_wt, len(dn_table['GC']))
dn_table_GG_wt = dn_table.iloc[0,11]
dn_table_GG_wt_rep = np.repeat(dn_table_GG_wt, len(dn_table['GG']))
dn_table_GT_wt = dn_table.iloc[0,12]
dn_table_GT_wt_rep = np.repeat(dn_table_GT_wt, len(dn_table['GT']))
dn_table_TA_wt = dn_table.iloc[0,13]
dn_table_TA_wt_rep = np.repeat(dn_table_TA_wt, len(dn_table['TA']))
dn_table_TC_wt = dn_table.iloc[0,14]
dn_table_TC_wt_rep = np.repeat(dn_table_TC_wt, len(dn_table['TC']))
dn_table_TG_wt = dn_table.iloc[0,15]
dn_table_TG_wt_rep = np.repeat(dn_table_TG_wt, len(dn_table['TG']))
dn_table_TT_wt = dn_table.iloc[0,16]
dn_table_TT_wt_rep = np.repeat(dn_table_TT_wt, len(dn_table['TT']))
dn_table_least = np.sqrt((dn_table_AA_wt_rep-dn_table['AA'])**2+(dn_table_AC_wt_rep-dn_table['AC'])**2+(dn_table_AG_wt_rep-dn_table['AG'])**2+(dn_table_AT_wt_rep-dn_table['AT'])**2+(dn_table_CA_wt_rep-dn_table['CA'])**2+(dn_table_CC_wt_rep-dn_table['CC'])**2+(dn_table_CG_wt_rep-dn_table['CG'])**2+(dn_table_CT_wt_rep-dn_table['CT'])**2+(dn_table_GA_wt_rep-dn_table['GA'])**2+(dn_table_GC_wt_rep-dn_table['GC'])**2+(dn_table_GG_wt_rep-dn_table['GG'])**2+(dn_table_GT_wt_rep-dn_table['GT'])**2+(dn_table_TA_wt_rep-dn_table['TA'])**2+(dn_table_TC_wt_rep-dn_table['TC'])**2+(dn_table_TG_wt_rep-dn_table['TG'])**2+(dn_table_TT_wt_rep-dn_table['TT'])**2)
dn_table_least.to_csv(dnlsname, sep="\t")
# dn_least_file.write(dn_table_least)
# dn_least_file.close()
dn_table_least_z = ((dn_table_least - dn_table_least.mean()) / dn_table_least.std())
dn_table_least_z_wt = dn_table_least_z.iloc[0]
dn_table_least_z_wt_rep = np.repeat(dn_table_least_z_wt, len(dn_table_least_z))
dn_table_least_z_ls = (dn_table_least_z_wt_rep-dn_table_least_z)**2
least_squares = least_squares.add(dn_table_least_z_ls, axis=0)
u_cols = ['Replication', 'DN_least_square']
dn_table_ls = pandas.read_csv(dnlsname, sep=' ', names=u_cols)
# final_table=final_table.append(dn_table_ls['DN_least_square'])
final_table.insert(0, "DN_least_square", dn_table_ls['DN_least_square'])
final_table.insert(1, "DN (TT)", dn_table['TT'])
final_table.insert(1, "DN (TG)", dn_table['TG'])
final_table.insert(1, "DN (TC)", dn_table['TC'])
final_table.insert(1, "DN (TA)", dn_table['TA'])
final_table.insert(1, "DN (GT)", dn_table['GT'])
final_table.insert(1, "DN (GG)", dn_table['GG'])
final_table.insert(1, "DN (GC)", dn_table['GC'])
final_table.insert(1, "DN (GA)", dn_table['GA'])
final_table.insert(1, "DN (CT)", dn_table['CT'])
final_table.insert(1, "DN (CG)", dn_table['CG'])
final_table.insert(1, "DN (CC)", dn_table['CC'])
final_table.insert(1, "DN (CA)", dn_table['CA'])
final_table.insert(1, "DN (AT)", dn_table['AT'])
final_table.insert(1, "DN (AG)", dn_table['AG'])
final_table.insert(1, "DN (AC)", dn_table['AC'])
final_table.insert(1, "DN (AA)", dn_table['AA'])
if args.graphics:
dnls_graphname = dnlsname + '.pdf'
#--bug in python ggplot for this, use rpy2 instead--
dn_table_least = pandas.read_csv(dnlsname, sep=' ', names=['Rep', 'DN'])
dn_graph = ggplot(dn_table_least,aes('DN')) + geom_density() + xlab("Dinucleotide") + ylab('Dinucleotide Least Squares')+ geom_vline(xintercept = [dn_table_least['DN'].iloc[0]] , colour="red", linetype = "dashed") +ggtitle(seq_name[1:-1]+'_'+args.random_type+' (DN)')
ggsave(dn_graph, dnls_graphname)
dn_table = pandas.read_csv(dnname, sep=" ")
fig, ax = plt.subplots()
dn_table.boxplot(return_type='axes')
ax.set_title(seq_name[1:- 1]+'_'+args.random_type+' (Dinucleotide Frequency)')
ax.set_xlabel('Dinucleotide')
ax.set_ylabel('Dinuc obser/Dinuc expec')
fig.savefig(seq_name[1:-1]+'_'+args.random_type+'_dn.pdf')
plt.close(fig)
# r = robjects.r
# r.library("ggplot2")
# r.library("reshape2")
# robjects.r('dn_table=read.csv("Poliovirus_1_Mahoney_P1_dn23.dn", sep="\t", header=T)')
# r.pdf(dn_graphname)
# robjects.r('p<-ggplot(melt(dn_table, "id"), aes(variable, value)) + geom_boxplot() + xlab("dinucleotide") + ylab("dinucleotide weight")')
# robjects.r('print(p)')
# robjects.r['dev.off']()
if 'CPB' in args.modules or 'all' in args.modules:
#CPB, from Coleman et al 2008, pmid: 18583614
#DNA to protein to CPB analysis
#proteins = list((make_protein_record(nuc_rec) for nuc_rec in \
# SeqIO.parse(filename, "fasta")))
#SeqIO.write(proteins, filename+"_prot", "fasta")
print "Calculating CPB"
cpbname = seq_name[1:-1]+'_'+args.random_type+'.cpb'
cpb_file=open(cpbname,'w')
#Human CPS from Coleman et al 2008, pmid: 18583614
cps_human = pandas.read_csv("Coleman_CPS.csv", sep=';')
#Delete column
cps_human = cps_human.drop('Aapair', 1)
cps_human = cps_human.drop('Expected', 1)
cps_human = cps_human.drop('Observed', 1)
cps_human = cps_human.drop('Observed/Expected', 1)
cps_human = cps_human.sort(['CodonPair'], ascending=[True])
for nuc_rec in SeqIO.parse(filename, "fasta"):
prot_rec = make_protein_record(nuc_rec)
codons = [str(nuc_rec.seq[i:i+3]) for i in range(0,len(nuc_rec.seq)-3,3)]
dicodons = [str(nuc_rec.seq[i:i+6]) for i in range(0,len(nuc_rec.seq)-3,3)]
aas = [str(prot_rec.seq[i:i+1]) for i in range(0,len(prot_rec.seq),1)]
diaas = [str(prot_rec.seq[i:i+2]) for i in range(0,len(prot_rec.seq)-1,1)]
codon_counts = Counter(codons)
dicodon_counts = Counter(dicodons)
aa_counts = Counter(aas)
diaa_counts = Counter(diaas)
cps = []
for cp in dicodons:
cod1 = cp[:3]
cod2 = cp[3:]
if cod1 in ['TAG', 'TGA', 'TAA'] or cod2 in ['TAG', 'TGA', 'TAA']:
continue #skip stop codons
aa1 = tt[cod1].split('|')[0]
aa2 = tt[cod2].split('|')[0]
ap = aa1+aa2
#score = np.log(dicodons.count(cp) / ( ((codons.count(cod1) * codons.count(cod2)) / (aas.count(aa1) * aas.count(aa2))) * diaas.count(ap)))
#score = np.log(dicodon_counts[cp] / ( ((codon_counts[cod1] * codon_counts[cod2]) / (aa_counts[aa1] * aa_counts[aa2])) * diaa_counts[ap]))
numerator_cps = dicodon_counts[cp]
denominator_cps = ((codon_counts[cod1] * codon_counts[cod2]) / (aa_counts[aa1] * aa_counts[aa2])) * diaa_counts[ap]
with np.errstate(divide='ignore', invalid='ignore'):
div_cps = np.true_divide(numerator_cps,denominator_cps)
score = np.log(div_cps)
cps.append(score)
dicodon_df = pandas.DataFrame.from_dict(dicodon_counts, orient='index').reset_index()
dicodon_df = dicodon_df.sort(['index'], ascending=[True])
dicodon_df.columns = ['CodonPair', 'Obs']
cps_tb_final = pandas.merge(cps_human, dicodon_df, on='CodonPair', how='inner')
cps_tb_final['CPS'] = cps_tb_final['CPS'].replace({',':'.'}, regex=True)
cps_tb_final['CPS'] = cps_tb_final['CPS'].astype(float)
cps_tb_final['result'] = cps_tb_final.CPS * cps_tb_final.Obs
cpb = sum(cps_tb_final['result'])/sum(cps_tb_final['Obs'])
print str(cpb)
cpb_file.write(str(cpb)+"\n")
cpb_file.close()
u_cols = ['cpb']
cpb_table = pandas.read_csv(cpbname, sep=' ', names=u_cols)
cpb_table_z = ((cpb_table['cpb'] - cpb_table['cpb'].mean()) / cpb_table['cpb'].std())
cpb_table_wt_z = cpb_table_z.iloc[0]
cpb_table_wt_z_rep = np.repeat(cpb_table_wt_z, len(cpb_table_z))
cpb_table_z_ls = (cpb_table_wt_z_rep-cpb_table_z)**2
least_squares = least_squares.add(cpb_table_z_ls, axis=0)
# final_table=final_table.append(cpb_table['cpb'])
final_table.insert(0, "CPB", cpb_table['cpb'])
if args.graphics:
cpb_graphname = cpbname +'.pdf'
u_cols = ['cpb']
cpb_table = pandas.read_csv(cpbname, sep=' ', names=u_cols)
cpb_graph = ggplot(cpb_table, aes('cpb'))+geom_density() +labs("CPB","Frequency")+ geom_vline(xintercept = [cpb_table['cpb'].iloc[0]] , colour="red", linetype = "dashed") +ggtitle(seq_name[1:-1]+'_'+args.random_type+' (CPB)') #Get the name of the script
ggsave(cpb_graph, cpb_graphname)
#Calculation least square
print "Calculating Least Squares"
least_squares = np.sqrt(least_squares)
least_squares.columns = ['distance']
least_table_name = seq_name[1:-1]+'_'+args.random_type+'_least_square.txt'
least_squares.to_csv(least_table_name, sep="\t")
#final_table=final_table.append(least_squares['distance'])
final_table.insert(0, "Distance(ls)", least_squares['distance'])
#least_table_file=open(least_table_name,'w')
#least_table_file.write(least_squares)
#least_table_file.close()
#least_table = sqrt()
# Create final graph and table
print "Making final table"
nuc_distance_name=filename+'_distance_table.txt'
nuc_distance_file=open(nuc_distance_name,'w')
nuc_distance_table = np.zeros((n,n))
for j in range(1,n):
difference = get_difference(seq_records[0], seq_records[j])
nuc_distance_file.write(str(difference)+'\n')
my_array[0, j] = difference
nuc_distance_file.close()
col_name = ['Nucleotide_difference']
new_nuc_distance_table = pandas.read_csv(nuc_distance_name, sep=' ', names=col_name)
new_nuc_distance_table.loc[-1]=[0]
new_nuc_distance_table.index = new_nuc_distance_table.index + 1
new_nuc_distance_table = new_nuc_distance_table.sort()
new_table=pandas.DataFrame()
new_table.insert(0, "Distance", least_squares['distance'])
new_table.insert(1, "Nucleotide_difference", new_nuc_distance_table['Nucleotide_difference'])
new_table_name = seq_name[1:-1]+'_'+args.random_type+'new_table_final_graph.txt'
new_table.to_csv(new_table_name, sep="\t")
#final_table=final_table.append(new_nuc_distance_table['Nucleotide_difference'])
final_table.insert(1, "Nucleotide_difference", new_nuc_distance_table['Nucleotide_difference'])
final_tb_name = seq_name[1:-1]+'_'+args.random_type+'_final_table.txt'
final_table.to_csv(final_tb_name, sep='\t')
if args.graphics:
final_graphname = filename +'final_graph.pdf'
final_graph = ggplot(new_table, aes('Distance', 'Nucleotide_difference'))+geom_point()+labs("Least Square Distance","Hamming Distance (nt)")+ggtitle(seq_name[1:-1]+'_'+args.random_type)
ggsave(final_graph, final_graphname)
|
993,671 | fd4a91350b6b29d0905524543b9c0943faa07bbe | import sys
def main(N, *arg):
values = sorted(list(map(int, arg)), reverse=True)
return sum(values[::2]) - sum(values[1::2])
if __name__ == '__main__':
N = int(sys.argv[1])
main(N, sys.argv[2:])
|
993,672 | b45d11db566e74ab95d8df3b9e468007397879ba | import numpy as np
import scipy.io.wavfile as wf
import matplotlib.pyplot as plt
rate, data = wf.read('challenge.wav')
data = data / 32768.0
# strip off the constant tone from both sides
points = data[6752:77120:8]
plt.plot(points[:, 0], points[:, 1], 'o')
angles = np.angle(points[:, 0] + points[:, 1] * 1j)
vals = ((angles % (2 * np.pi)) - (np.pi / 4)) / (np.pi / 2)
bits = []
prev = 0
for i in vals:
v = (int(round(i)) - prev) % 4
prev = int(round(i))
bits.append(['01', '00', '10', '11'][v])
bits = ''.join(bits)
for i in range(0, len(bits), 8):
print('%02x' %int(bits[i:i+8], 2), end='')
print()
|
993,673 | c39e704f98ab8a7d2ff76483af66b360a8985e37 | from src.test.run.testObject import testObject
from src.test.run.testSet import testSet
from copy import deepcopy
#import src.test.run.example
#import pytest
import sys
from pyrallei import Rally, rallyWorkset #By using custom package pyrallei as a workaround for the bug: bug: https://github.com/RallyTools/RallyRestToolkitForPython/issues/37
import json
#xunit-style example
def setup_module(module):
try:
global rally,data,to_obj
print ("setup_module module:%s" % module.__name__)
options = ['--config=../config.cfg'] #--config=config.cfg "extra.cfg"
server, user, password, apikey, workspace, project = rallyWorkset(options) #apikey can be obtained from https://rally1.rallydev.com/login/
#global rally
rally = Rally(server, user, password, workspace=workspace, project=project)
rally.enableLogging('rally.example.log', attrget=True, append=True)
#global data
# Read other configuration parameters from the extra.json
with open('../extra.json') as data_file:
data = json.load(data_file)
#global to_obj
to_obj=testObject(rally,data)
except Exception,details:
print details
sys.exit(1)
'''
def teardown_module(module):
try:
ts_obj=testSet(rally,data)
ts_obj.delTS()
except Exception,details:
print details
sys.exit(1)
'''
#Test testObject/copyTS
class TestTOCopyTS:
def setup_method(self,method):
try:
print ("setup_method method:%s" % method.__name__)
global ts_obj,ts,tcs,fids,new_self_data,ts_new
ts_obj=testSet(rally,data)
ts=ts_obj.getTSByID()[0]
tcs=ts_obj.allTCofTS(ts)
fids=[]
for tc in tcs:
fids.append(tc.FormattedID)
ts_new=to_obj.copyTS()
#global new_self_data
new_self_data=deepcopy(data) #use deepcopy instead of shallow one to create two separate object
new_self_data['ts']['FormattedID']=ts_new.FormattedID
except Exception,details:
print details
sys.exit(1)
def teardown_method(self,method):
try:
print ("teardown_method method:%s" % method.__name__)
ts_new_obj=testSet(rally,new_self_data)
ts_new_obj.delTS()
except Exception,details:
print details
sys.exit(1)
'''
def test_testobject_copyts_equal_formattedid():
ts_new=to_obj.copyTS()
assert ts_new.FormattedID==data["ts"]["FormattedID"]
'''
def test_testobject_copyts_same_tc_order(self):
print 'test_testobject_copyts_same_tc_order <============================ actual test code'
tcs=ts_new.TestCases
for tc in tcs:
assert tc.FormattedID==fids[tcs.index(tc)]
def test_testobject_copyts_same_ts_name(self):
print 'test_testobject_copyts_same_ts_name <============================ actual test code'
assert ts_new.Name==ts.Name
def test_testobject_copyts_defined_state(self):
print 'test_testobject_copyts_defined_state <============================ actual test code'
assert ts_new.ScheduleState=="Defined"
|
993,674 | 5a8f5edd5db62f7c7915bf2a456f81f9482f1caa | import requests
import json
BASE_URL = "https://api.jdoodle.com/v1/execute"
headers = {'content-type': 'application/json'}
with open('tests/test_wealth_manger.py', 'r') as f:
code = f.read()
data = {
'script': code,
'language': "python3",
'versionIndex': '2',
'clientId': '8acba1648460ab5cc5e502f507d3230e',
'clientSecret': '6ca2d92b2a297ad77ddd01da8f73f39228f07b4fdee1bb5dfbd0f90d517cb64b',
}
json_data = json.dumps(data)
r = requests.post(url=BASE_URL, data=json_data, headers=headers)
print(r.json())
|
993,675 | b78d8b698040bafba3e30598a8ba132739e84da0 | import fileinput
import time
import re
from collections import defaultdict
from operator import itemgetter
INPUT_FILE = "aoc_2018_04.dat"
start = time.time()
inputs = sorted(fileinput.input(INPUT_FILE))
totals = defaultdict(int)
minutes = defaultdict(lambda: defaultdict(int))
for line in inputs:
if '#' in line:
guard = int(re.search(r'#(\d+)', line).group(1))
elif 'asleep' in line:
m0 = int(re.search(r':(\d+)', line).group(1))
elif 'wakes' in line:
m1 = int(re.search(r':(\d+)', line).group(1))
for m in range(m0, m1):
totals[guard] += 1
minutes[guard][m] += 1
key = itemgetter(1)
guard = max(totals.items(), key=key)[0]
minute = max(minutes[guard].items(), key=key)[0]
result = guard * minute
print("Guard: ", guard)
print("Minute: ", minute)
print("Part1: The result is: ", result)
print("")
max_times = -1
max_minute = -1
max_guard = -1
for guard, minutes_dic in minutes.items():
for minute, times in minutes_dic.items():
cur_times = times
if cur_times > max_times:
max_times = cur_times
max_guard = guard
max_minute = minute
result = max_guard * max_minute
print("Guard: ", max_guard)
print("minute: ", max_minute)
print("Part2: The result is: ", result)
print("Seconds spent: ", round(time.time() - start, 5))
|
993,676 | 84d8be22001ce4a1ed56d35348f49cd5bd225419 | import charm.cryptobase
from charm.pairing import pairing,ZR
#from toolbox.pairinggroup import pairing,ZR
from charm.integer import integer,int2Bytes
import hashlib, base64
class Hash():
def __init__(self, htype='sha1', pairingElement=None, integerElement=None):
if htype == 'sha1':
self.hash_type = htype
# instance of PairingGroup
self.group = pairingElement
def hashToZn(self, value):
if type(value) == pairing:
h = hashlib.new(self.hash_type)
h.update(self.group.serialize(value))
#print "digest => %s" % h.hexdigest()
# get raw bytes of digest and hash to Zr
val = h.digest()
return integer(int(self.group.hash(val, ZR)))
# do something related to that
if type(value) == integer:
str_value = int2Bytes(value)
# print("str_value =>", str_value)
# val = self.group.hash(str_value, ZR)
# print("hash =>", val)
return integer(int(self.group.hash(str_value, ZR)))
return None
# takes two arbitrary strings and hashes to an element of Zr
def hashToZr(self, *args):
if isinstance(args, tuple):
#print("Hashing =>", args)
strs = ""
for i in args:
if type(i) == str:
strs += str(base64.encodebytes(bytes(i, 'utf8')))
elif type(i) == bytes:
strs += str(base64.encodebytes(i))
elif type(i) == integer:
strs += str(base64.encodebytes(int2Bytes(i)))
elif type(i) == pairing:
strs += str(base64.encodebytes(self.group.serialize(i)))
if len(strs) > 0:
return self.group.hash(strs, ZR)
return None
|
993,677 | d064e0c49d5b9d4f7b04f2d478ba9eddc06a7fde | #Comentario
print ("programa que suma dos números")
a= int (input ("Ingresa el sumando 1: "))
b= int (input ("Ingresa el sumando 2: "))
suma = a + b
print ("El resultado es" , suma)
|
993,678 | 44fe554d8f53b65502ece1607d497d5e635714cc | import logging
class Log(logging):
self.getLogger(__name__)
|
993,679 | 668285051bfcafc3098ff3db91944c1e7dd1f180 | /Users/jingwang/anaconda/lib/python3.6/functools.py |
993,680 | 06f921fc45a560ae49eee0ec1ed8b9428f01fd8f | API_ENDPOINT = 'https://openexchangerates.org/api/'
LATEST_ENDPOINT = 'latest.json'
HISTORICAL_ENDPOINT = 'historical/{date}.json' |
993,681 | 6a02481e04f10538aad9ce43a28a6af64eb62a3c | # Problem #10 - Linear Function http://www.codeabbey.com/index/task_view/linear-function
# Submission by MPadilla - 21/Jun/2015
def linearf(coord):#Función para calcular la pendiente A y el intercepto B de la función lineal
global i,entr
Xi=entr[i][0]
Xf=entr[i][2]
Yi=entr[i][1]
Yf=entr[i][3] #Selecciona cada punto inicial y final del cuarteto x1 y1 x2 y2
A=int((Yf-Yi)/(Xf-Xi)) #Calcula la pendiente A y vuelve entero el valor.
B=Yf-A*Xf #Toma una coordenada (la final en este caso), reemplaza y despeja para hallar el intercepto B
entr[i]=(A,B) #Asignar pendiente A e intercepto B en un tuple
entr[i]='('+" ".join(str(x) for x in entr[i])+')' #Vuelve el tuple una cadena de caracteres, los separa con espacios y los encierra con paréntesis.
N=int(input('How many linear functions will be found?\n')) #Pregunta cuantas funciones lineales serán halladas
print('Paste the input values here, in form of 4-tuples of values x1 y1 x2 y2')
entr = [(list(int(x) for x in input().split())) for i in range(N)] #Recibe las coordenadas y abscisas iniciales y finales para calcular las N funciones lineales
for i in range(N):
linearf(entr[i])#Aplica funcion linearf
print("The slope A and intercept B for each linear function is: "+" ".join(str(x) for x in entr))
|
993,682 | c21f121dc1d0009ca4752e2de3175c2af934ee3b | #! /usr/bin/env python
import os
files = [
# full filenames
"var/log/apache/errors.log",
"home/kane/images/avatars/crusader.png",
"home/jane/documents/diary.txt",
"home/kane/images/selfie.jpg",
"var/log/abc.txt",
"home/kane/.vimrc",
"home/kane/images/avatars/paladin.png",
]
# unfolding of plain filiname list to file-tree
fs_tree = ({}, # dict of folders
[]) # list of files
for full_name in files:
path, fn = os.path.split(full_name)
reduce(
# this fucction walks deep into path
# and creates placeholders for subfolders
lambda d, k: d[0].setdefault(k, # walk deep
({}, [])), # or create subfolder storage
path.split(os.path.sep),
fs_tree
)[1].append(fn)
print fs_tree
#({'home': (
# {'jane': (
# {'documents': (
# {},
# ['diary.txt']
# )},
# []
# ),
# 'kane': (
# {'images': (
# {'avatars': (
# {},
# ['crusader.png',
# 'paladin.png']
# )},
# ['selfie.jpg']
# )},
# ['.vimrc']
# )},
# []
# ),
# 'var': (
# {'log': (
# {'apache': (
# {},
# ['errors.log']
# )},
# ['abc.txt']
# )},
# [])
#},
#[])
|
993,683 | 4682ebdcb27c488363d08b90bab86b71f2a24026 | from correlcalc import *
bins = np.arange(0.0005,0.0505,0.0005)
acorrdr122xap=atpcf('/usr3/vstr/yrohin/Downloads/galaxy_DR12v5_CMASS_North.fits',bins,bins,randfile='/usr3/vstr/yrohin/randcat_dr12cmn_2x_pdf10k.dat',vtype='ap',estimator='ls',weights='eq')
|
993,684 | f6f489dc18fff2699c35b4253e7a8d123b0fa1ea | #WWALK
t = int(input())
for _ in range(t):
n =int(input())
l = list(map(int,input().split()))
m = list(map(int,input().split()))
s1 = 0
s2 = 0
main = 0
for i in range(n):
try:
if s1==s2 and l[i]==m[i]:
main+=l[i]
except:
pass
print(main) |
993,685 | 79ab0c2a9af58a1100e0c57f5bfd0c591c430b5b | from collections import AsyncIterable
from asyncpgsa import PG
from sqlalchemy import select
from scrapnow.lib.component import Component
from .schema import (
scrap_task,
scrap_document_fields,
article,
TaskStatus
)
class QueryAsyncIterable(AsyncIterable):
PREFETCH = 100
def __init__(self, query, transaction_context):
self.query = query
self.transaction_ctx = transaction_context
async def __aiter__(self):
async with self.transaction_ctx as conn:
cursor = conn.cursor(self.query, prefetch=self.PREFETCH)
async for row in cursor:
yield row
class ScrapnowDatabase(Component, PG):
async def start(self):
self.log.info('Connecting to database')
await self.init(**self.cfg)
self.log.info('Connected to database')
async def stop(self):
self.log.info('Disconnecting from database')
await self.pool.close()
self.log.info('Disconnected from database')
async def get_pending_scrap_tasks(self, count):
tasks = None
async with self.transaction() as connection:
_tasks = await connection.fetch(
select([scrap_task]).where(
scrap_task.c.status == TaskStatus.PENDING.value
).limit(count).with_for_update(key_share=True)
)
tasks = {task['id']: dict(task) for task in _tasks}
if tasks:
task_ids = list(tasks.keys())
await connection.fetchrow(
scrap_task.update().values(
status=TaskStatus.IN_PROGRESS.value
).where(scrap_task.c.id.in_(task_ids))
)
fields = await connection.fetch(
select([scrap_document_fields]).where(
scrap_document_fields.c.scrap_task_id.in_(task_ids)
)
)
for field in fields:
tasks[field['scrap_task_id']].setdefault(
'scrap_document_fields', []
).append(field)
return tasks
async def add_scrap_task(self, url, document_fields, handler=None):
async with self.transaction() as connection:
task = await connection.fetchrow(
scrap_task.insert().values(url=url, handler=handler).returning(
scrap_task.c.id)
)
if document_fields:
for field in document_fields:
await connection.fetchrow(
scrap_document_fields.insert().values(
scrap_task_id=task['id'],
name=field['name'],
xpath=field['xpath']
).returning(scrap_document_fields.c.id)
)
await self.fetchrow("SELECT pg_notify('scrapnow', '');")
return task['id']
async def update_task(self, task_id, **values):
if values.get('error'):
status = TaskStatus.ERROR.value
else:
status = TaskStatus.DONE.value
await self.fetchrow(scrap_task.update().values(
status=status,
**values
).where(scrap_task.c.id == task_id))
async def create_article(self, **values):
article_id = await self.fetchrow(
article.insert().values(**values).returning(article.c.id)
)
return article_id
async def update_article(self, url, **values):
await self.fetchrow(article.update().values(
**values
).where(article.c.url == url))
async def get_articles(self, datetime):
query = select([article]).where(article.c.datetime == datetime)
# query = select([article])
return QueryAsyncIterable(query, self.transaction())
|
993,686 | 4a6ea386304d158da44ecc358b0ba2ed99122f92 | n=int(input())
str1=input()
str2=input()
if(n==2):
if((str1=="timetopractice" and str2=="toc")or str1=="metopractice"):
print("toprac\napzo",end="\n")
else:
print("toprac\n-1",end="\n")
|
993,687 | d00676891fe12aee02c54869da4b8a1c172d7ee8 | import requests
import unittest
import json
from xmdCW.chewudata.get_data import cheWu
from xmdCW.gettoken.getToken import GetToken
from BeautifulReport import BeautifulReport as bf
# 该接口写的是待核准状态的问题反馈,其他状态均类似,都是一个接口
class TestFanKui(unittest.TestCase, GetToken):
# @unittest.skip(1)
def test1_fankui_notoken(self):
"""问题反馈接口,未登录直接请求"""
# 获取文件中的车务工单号
danhao = cheWu()[0].strip('\n')
# 登录地址
login_url = "http://uat-c2b.taoche.com/basegate/work/order/"+danhao+"/issue-feedback"
# 请求头
headers = {
'Content-Type': 'application/json;charset=UTF-8',
# 未添加token
}
response_data = requests.patch(login_url, headers=headers).json()
# print(response_data)
self.assertEqual(response_data["message"], "用户未登录")
# @unittest.skip(1)
def test2_fankui_wrongjson(self):
"""登录后,不输入请求参数"""
# 获取文件中的车务工单号
danhao = cheWu()[0].strip('\n')
# 登录地址
login_url = "http://uat-c2b.taoche.com/basegate/work/order/"+danhao+"/issue-feedback"
# 请求头
headers = {
'Content-Type': 'application/json;charset=UTF-8',
'Authorization': GetToken().token()
}
response_data = requests.patch(login_url, headers=headers).json()
# print(response_data)
self.assertIn("请求JSON格式不正确", response_data["message"],)
# @unittest.skip(1)
def test3_fankui_noid(self):
"""登录后,缺少车务工单号参数,直接请求接口"""
# 获取文件中的车务工单号
danhao = cheWu()[0].strip('\n')
# 登录地址
login_url = "http://uat-c2b.taoche.com/basegate/work/order/"+danhao+"/issue-feedback"
# 请求头
headers = {
'Content-Type': 'application/json;charset=UTF-8',
'Authorization': GetToken().token()
}
request_data = {
# "serviceId": danhao,
"serviceStatus": 101,
"remark": ""
}
response_data = requests.patch(login_url, json.dumps(request_data), headers=headers).json()
# print(response_data)
self.assertEqual(response_data["message"], "车务工单id不能为空")
# @unittest.skip(1)
def test4_fankui_nostatus(self):
"""登录后,缺少车务工单状态参数,直接请求接口"""
# 获取文件中的车务工单号
danhao = cheWu()[0].strip('\n')
# 登录地址
login_url = "http://uat-c2b.taoche.com/basegate/work/order/"+danhao+"/issue-feedback"
# 请求头
headers = {
'Content-Type': 'application/json;charset=UTF-8',
'Authorization': GetToken().token()
}
request_data = {
"serviceId": danhao,
# "serviceStatus": 101,
"remark": ""
}
response_data = requests.patch(login_url, json.dumps(request_data), headers=headers).json()
# print(response_data)
self.assertEqual(response_data["message"], "当前工单状态不能为空")
# @unittest.skip(1)
def test5_fankui_noremark(self):
"""登录后,缺少问题备注参数,直接请求接口"""
# 获取文件中的车务工单号
danhao = cheWu()[0].strip('\n')
# 登录地址
login_url = "http://uat-c2b.taoche.com/basegate/work/order/"+danhao+"/issue-feedback"
# 请求头
headers = {
'Content-Type': 'application/json;charset=UTF-8',
'Authorization': GetToken().token()
}
request_data = {
"serviceId": danhao,
"serviceStatus": 101,
# "remark": ""
}
response_data = requests.patch(login_url, json.dumps(request_data), headers=headers).json()
# print(response_data)
self.assertEqual(response_data["message"], "问题反馈备注不能为空")
# @unittest.skip(1)
def test6_fankui_noremarkcontent(self):
"""登录后,请求参数中问题备注内容为空"""
# 获取文件中的车务工单号
danhao = cheWu()[0].strip('\n')
# 登录地址
login_url = "http://uat-c2b.taoche.com/basegate/work/order/"+danhao+"/issue-feedback"
# 请求头
headers = {
'Content-Type': 'application/json;charset=UTF-8',
'Authorization': GetToken().token()
}
request_data = {
"serviceId": danhao,
"serviceStatus": 101,
"remark": ""
}
response_data = requests.patch(login_url, json.dumps(request_data), headers=headers).json()
# print(response_data)
self.assertEqual(response_data["message"], "SUCCESS")
# @unittest.skip(1)
def test7_fankui_remarkcontentless200(self):
"""登录后,请求参数中问题备注内容有少于200字的内容"""
# 获取文件中的车务工单号
danhao = cheWu()[0].strip('\n')
# 登录地址
login_url = "http://uat-c2b.taoche.com/basegate/work/order/"+danhao+"/issue-feedback"
# 请求头
headers = {
'Content-Type': 'application/json;charset=UTF-8',
'Authorization': GetToken().token()
}
request_data = {
"serviceId": danhao,
"serviceStatus": 101,
"remark": "测试数据"
}
response_data = requests.patch(login_url, json.dumps(request_data), headers=headers).json()
# print(response_data)
self.assertEqual(response_data["message"], "SUCCESS")
# @unittest.skip(1)
def test8_fankui_remarkcontentmore200(self):
"""登录后,请求参数中问题备注内容有大于200字的内容"""
# 获取文件中的车务工单号
danhao = cheWu()[0].strip('\n')
# 登录地址
login_url = "http://uat-c2b.taoche.com/basegate/work/order/"+danhao+"/issue-feedback"
# 请求头
headers = {
'Content-Type': 'application/json;charset=UTF-8',
'Authorization': GetToken().token()
}
remark = "测试数据测试数据测试数据测试数据测测试试测试数据据测据测测试数据试数" \
"测试数据测试数据测试数据测试数据测测试试测试数据据测据测测试数据试数" \
"测试数据测试数据测试数据测试数据测测试试测试数据据测据测测试数据试数测" \
"试数据测试数据测试数据测试数据测测试试测试数据据测据测测试数据试数测试" \
"数据测试数据测试数据测试数据测测试试测试数据据测据测测试数据试数测试数据" \
"测试数据测试数据测试数据测测试试测试数据据测据测测试数据试数测试数据测" \
"试数据测试数据测试数据测测试试测试数据据测据测测试数据试数测试数据测" \
"试数据测试数据测试数据测测试试测试数据据测据测测试数据试数"
request_data = {
"serviceId": danhao,
"serviceStatus": 101,
"remark": remark
}
response_data = requests.patch(login_url, json.dumps(request_data), headers=headers).json()
# print(response_data)
self.assertEqual(response_data["message"], "SUCCESS")
# @unittest.skip(1)
def test9_wrongstatus(self):
"""请求参数中填写的工单状态与实际状态不一致,请求接口"""
# 获取文件中的车务工单号
danhao = cheWu()[0].strip('\n')
# 登录地址
login_url = "http://uat-c2b.taoche.com/basegate/work/order/"+danhao+"/issue-feedback"
# 请求头
headers = {
'Content-Type': 'application/json;charset=UTF-8',
'Authorization': GetToken().token()
}
request_data = {
"serviceId": danhao,
"serviceStatus": 102,
"remark": ""
}
response_data = requests.patch(login_url, json.dumps(request_data), headers=headers).json()
# print(response_data)
self.assertEqual(response_data["message"], "接收消息订单状态与订单状态不匹配")
if __name__ == "__main__":
# 定义一个测试集合
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestFanKui))
# 实例化BeautifulReport模块
run = bf(suite)
run.report(filename='test', description='登录测试结果')
# unittest.main()
|
993,688 | dc18468a68c5e55339fa821b278f5edd911378ca | from django.contrib.auth.forms import UserCreationForm, forms
from django.contrib.auth.models import User
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
full_name = forms.CharField(max_length=30)
contact_number = forms.IntegerField()
# lname = forms.CharField(max_length=10)
class Meta:
model = User
fields = ['username',
'full_name',
'email',
'contact_number',
'password1',
'password2',
]
|
993,689 | 105536f8e07d8988b64bcd9310dd698df4d4b031 | import plotly.graph_objects as go
import sqlite3
def grafik_player_id(userid):
grafik_player_teg(get_teg(userid))
def get_teg(userid):
conn = sqlite3.connect("clanstat.db")
cursor = conn.cursor()
cursor.execute("SELECT teg FROM telegram_main WHERE id_telegram = ?",(userid,))
teg = cursor.fetchone()[0]
return teg
def grafik_player_teg(teg):
conn = sqlite3.connect("clanstat.db")
cursor = conn.cursor()
cursor.execute("SELECT active, battle, win, cards FROM main_war WHERE teg = ? LIMIT 10",(teg,))
wars_info = cursor.fetchall()
cursor.execute("SELECT cards_mid FROM war_list LIMIT 10")
midl = cursor.fetchall()
wins = []
lose = []
no_atack = []
no_war = []
y_win = []
y_lose = []
y_atack = []
y_war = []
player_cards = []
midl_cards = []
size_m = 40
a =[]
title_st = "Останні 10 КВ ігрока: " + str(teg)
for i in range(len(wars_info)):
if wars_info[i][0] == 1:#sprawdzamy czy był na kw
if wars_info[i][1] == 0:#nie było ataku
no_atack.append(i+1)
y_atack.append(wars_info[i][3])
else:
if wars_info[i][2] > 0:
wins.append(i+1)
y_win.append(wars_info[i][3])
else:
lose.append(i+1)
y_lose.append(wars_info[i][3])
else:# jeśli nie był na kw
no_war.append(i+1)
y_war.append(wars_info[i][3])
midl_cards.append(midl[i][0])
a.append(i+1)
player_cards.append(wars_info[i][3])
fig = go.Figure()
fig.add_trace(go.Scatter(x = a,y = player_cards, name="Карти ігрока",mode='lines+markers',))
fig.add_trace(go.Scatter(x = a,y = midl_cards, name="Cереднє значення карт",mode='lines+markers',))
fig.add_trace(go.Scatter(mode = "markers+text",
x = wins,
y=y_win,
text=y_win,
textposition="bottom center",
textfont=dict(
family="sans serif",
size=18,
color="Green"),
marker=dict(color='Green',
size=size_m,
line=dict(
color='Black',
width=2,)),
name="Перемога",))
fig.add_trace(go.Scatter(mode = "markers+text",
x = lose,
y=y_lose,
text=y_lose,
textposition="bottom center",
textfont=dict(
family="sans serif",
size=18,
color="gold",),
marker=dict(
color='gold',
size=size_m,
line=dict(
color='Black',
width=2,)),
name="Поразка",))
fig.add_trace(go.Scatter(mode = "markers+text",
x = no_war,
y=y_atack,
text=y_atack,
textposition="bottom center",
textfont=dict(
family="sans serif",
size=18,
color="Red"),
marker=dict(
color='Red',
size=size_m,
line=dict(
color='Black',
width=2,)),
name="Неучасть в КВ",))
fig.add_trace(go.Scatter(mode = "markers+text",
x = no_atack,
y=y_war,
text=y_war,
textposition="bottom center",
textfont=dict(
family="sans serif",
size=18,
color="Purple"),
marker=dict(
color='Purple',
size=size_m,
line=dict(
color='Black',
width=2)),
name="Незроблена атака на КВ",))
fig.update_layout(title=title_st,titlefont=dict(
family="sans serif",
size=30,
color="White"),
yaxis=dict(title_text ="Кількість карт набитих на кв",titlefont=dict(
family="sans serif",
size=30,
color="White")),
template="plotly_dark",
legend_orientation="h",)
fig.update_yaxes(showline=True,linewidth=2, linecolor='black',mirror=True,automargin=True)
fig.update_xaxes(showline=True,linewidth=2, linecolor='black',mirror=True,automargin=True)
fig.write_image("fig1.png")
|
993,690 | a21303db31234fa36886c9c2125cec88eaf3540e | """
地址:https://leetcode.com/problems/power-of-four/description/ 不实用循环递归完成
描述:
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example 1:
Input: 16
Output: true
Example 2:
Input: 5
Output: false
Follow up: Could you solve it without loops/recursion?
思路:
这道题是在leetcodeNo.231:2的幂的基础上的扩展,因此解法也只需要在该题的解法上扩展即可。
首先可以发现,4的幂是2的幂的子集,所以首先判断是否是2的幂。(n & (n - 1) 一定等于 0)
关于如何判断是否是2的幂,可以参见我在#231发布的题解。
其次,观察4的幂的二进制表示可以发现,其长度总为奇数,也就是说,1的位置总是在奇数位上。
因此如果有一个数的二进制表示只有奇数位上为1,那么这个数和4的幂做与运算,得到的还是4的幂本身。
题目要求的是32位整数,因此这个数就是0b1010101010101010101010101010101,这么长看起来很不优雅,
所以我们可以将它转化为16进制表示0x55555555,这样看起来就好多了
"""
class Solution(object):
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
return num > 0 and (num & num - 1) == 0 and (num & 0x55555555) == num
|
993,691 | 19fd7f4ee1a14afe73caca6116239012b223b1e3 | from mongoengine import DynamicEmbeddedDocument
from mongoengine.fields import StringField, ListField, EmbeddedDocumentField
class DruggabilitySearch(DynamicEmbeddedDocument):
meta = {'allow_inheritance': True, 'abstract': False, 'strict': False}
name = StringField()
def __init__(self, **kwargs):
'''
'''
super(DynamicEmbeddedDocument, self).__init__(**kwargs)
class PocketDruggabilitySearch(DruggabilitySearch):
pocket = StringField(required=True)
class StructureDruggabilitySearch(DruggabilitySearch):
structure = StringField(required=True)
pockets = ListField(EmbeddedDocumentField(PocketDruggabilitySearch), default=[])
class ProteinDruggabilitySearch(DruggabilitySearch):
meta = {'allow_inheritance': True, 'abstract': False, 'strict': False}
structures = ListField(EmbeddedDocumentField(StructureDruggabilitySearch), default=[])
|
993,692 | 2bd1113776d970c48b50bf40aae77aa22b1f0e63 | somaidade = 0
mediaidade = 0
maioridadehomem = 0
nomevelho = ''
totalm = 0
for lista in range(1, 5):
nome = str(input('Digite seu nome:')).strip()
idade = int(input('Digite sua idade: '))
sexo = str(input("Digite seu sexo: (H/M) ")).strip()
somaidade += idade
if lista == 1 and sexo == 'Hh':
maioridadehomem = idade
nomevelho = nome
if sexo in 'Hh' and idade > maioridadehomem:
maioridadehomem = idade
nomevelho = nome
if sexo in 'mM' and idade < 20:
totalm += 1
mediaidade = somaidade / 4
print('A media de idade do grupo é: {}'.format(mediaidade))
print('O nome do homem mais velho é: {}, com {} anos.'.format(nomevelho, maioridadehomem))
print('No grupo contem {} mulheres com menos de 20 anos.'.format(totalm))
|
993,693 | eff078e29bed5c6dfa3b68b85959f114f89e8175 | import ctypes
from dongtai_agent_python import global_var as dt_global_var
from dongtai_agent_python.common.content_tracert import dt_tracker_get
from dongtai_agent_python.assess.deal_data import wrapData
class PyObject(ctypes.Structure):
pass
Py_ssize_t = hasattr(ctypes.pythonapi, 'Py_InitModule4_64') and ctypes.c_int64 or ctypes.c_int
PyObject._fields_ = [
('ob_refcnt', Py_ssize_t),
('ob_type', ctypes.POINTER(PyObject)),
]
class SlotsPointer(PyObject):
_fields_ = [('dict', ctypes.POINTER(PyObject))]
def proxy_builtin(klass):
name = klass.__name__
# print(name)
slots = getattr(klass, '__dict__', name)
pointer = SlotsPointer.from_address(id(slots))
namespace = {}
ctypes.pythonapi.PyDict_SetItem(
ctypes.py_object(namespace),
ctypes.py_object(name),
pointer.dict,
)
test_a = ctypes.cast(id(slots), ctypes.py_object)
# print(test_a)
ctypes.PyDLL(None).PyType_Modified(test_a)
return namespace[name]
# 普通方法 hook
class InstallFcnHook(object):
def __init__(self, old_cls, fcn, signature=None, source=False):
self.signature = signature
self._fcn = fcn
self.old_cls = old_cls
self.source = source
def _pre_hook(self, *args, **kwargs):
# 入参 hook
if dt_tracker_get("upload_pool"):
pass
return (args, kwargs)
def _post_hook(self, retval, *args, **kwargs):
# 出参 hook
return retval
def __call__(self, *args, **kwargs):
self._pre_hook(*args, **kwargs)
retval = self._fcn(*args, **kwargs)
if dt_global_var.is_pause():
return retval
wrapData(
retval, self.old_cls.__name__, self._fcn,
signature=self.signature, source=self.source, comeData=args)
return retval
|
993,694 | d337657a4405711dde884890d995d295530a0977 | """
Copyright (c) 2018 Doyub Kim
I am making my contributions/submissions to this project solely in my personal
capacity and am not conveying any rights to any intellectual property of any
third parties.
"""
import numpy as np
import pyjet
def test_init2():
ps = pyjet.ParticleSystemData2()
assert ps.numberOfParticles == 0
ps2 = pyjet.ParticleSystemData2(100)
assert ps2.numberOfParticles == 100
def test_resize2():
ps = pyjet.ParticleSystemData2()
ps.resize(12)
assert ps.numberOfParticles == 12
def test_add_scalar_data2():
ps = pyjet.ParticleSystemData2()
ps.resize(12)
a0 = ps.addScalarData(2.0)
a1 = ps.addScalarData(9.0)
assert ps.numberOfParticles == 12
assert a0 == 0
assert a1 == 1
as0 = np.array(ps.scalarDataAt(a0))
for val in as0:
assert val == 2.0
as1 = np.array(ps.scalarDataAt(a1))
for val in as1:
assert val == 9.0
def test_add_vector_data2():
ps = pyjet.ParticleSystemData2()
ps.resize(12)
a0 = ps.addVectorData((2.0, 4.0))
a1 = ps.addVectorData((9.0, -2.0))
assert ps.numberOfParticles == 12
assert a0 == 3
assert a1 == 4
as0 = np.array(ps.vectorDataAt(a0))
for val in as0:
assert val.tolist() == [2.0, 4.0]
as1 = np.array(ps.vectorDataAt(a1))
for val in as1:
assert val.tolist() == [9.0, -2.0]
def test_add_particles2():
ps = pyjet.ParticleSystemData2()
ps.resize(12)
ps.addParticles([(1.0, 2.0), (4.0, 5.0)],
[(7.0, 8.0), (8.0, 7.0)],
[(5.0, 4.0), (2.0, 1.0)])
assert ps.numberOfParticles == 14
p = np.array(ps.positions)
v = np.array(ps.velocities)
f = np.array(ps.forces)
assert [1.0, 2.0] == p[12].tolist()
assert [4.0, 5.0] == p[13].tolist()
assert [7.0, 8.0] == v[12].tolist()
assert [8.0, 7.0] == v[13].tolist()
assert [5.0, 4.0] == f[12].tolist()
assert [2.0, 1.0] == f[13].tolist()
# ------------------------------------------------------------------------------
def test_init3():
ps = pyjet.ParticleSystemData3()
assert ps.numberOfParticles == 0
ps2 = pyjet.ParticleSystemData3(100)
assert ps2.numberOfParticles == 100
def test_resize3():
ps = pyjet.ParticleSystemData3()
ps.resize(12)
assert ps.numberOfParticles == 12
def test_add_scalar_data3():
ps = pyjet.ParticleSystemData3()
ps.resize(12)
a0 = ps.addScalarData(2.0)
a1 = ps.addScalarData(9.0)
assert ps.numberOfParticles == 12
assert a0 == 0
assert a1 == 1
as0 = np.array(ps.scalarDataAt(a0))
for val in as0:
assert val == 2.0
as1 = np.array(ps.scalarDataAt(a1))
for val in as1:
assert val == 9.0
def test_add_vector_data3():
ps = pyjet.ParticleSystemData3()
ps.resize(12)
a0 = ps.addVectorData((2.0, 4.0, -1.0))
a1 = ps.addVectorData((9.0, -2.0, 5.0))
assert ps.numberOfParticles == 12
assert a0 == 3
assert a1 == 4
as0 = np.array(ps.vectorDataAt(a0))
for val in as0:
assert val.tolist() == [2.0, 4.0, -1.0]
as1 = np.array(ps.vectorDataAt(a1))
for val in as1:
assert val.tolist() == [9.0, -2.0, 5.0]
def test_add_particles3():
ps = pyjet.ParticleSystemData3()
ps.resize(12)
ps.addParticles([(1.0, 2.0, 3.0), (4.0, 5.0, 6.0)],
[(7.0, 8.0, 9.0), (8.0, 7.0, 6.0)],
[(5.0, 4.0, 3.0), (2.0, 1.0, 3.0)])
assert ps.numberOfParticles == 14
p = np.array(ps.positions)
v = np.array(ps.velocities)
f = np.array(ps.forces)
assert [1.0, 2.0, 3.0] == p[12].tolist()
assert [4.0, 5.0, 6.0] == p[13].tolist()
assert [7.0, 8.0, 9.0] == v[12].tolist()
assert [8.0, 7.0, 6.0] == v[13].tolist()
assert [5.0, 4.0, 3.0] == f[12].tolist()
assert [2.0, 1.0, 3.0] == f[13].tolist()
|
993,695 | 772773a8c22a68712b639221317cb30801aa3d8a | stuff = {"name": "Steven", "Age": "39", "HeightCM": "179"}
print(stuff["name"])
stuff["name"] = "Bob"
print(stuff["name"])
del stuff["name"]
print(stuff)
states = {
"newsouthwales": "nsw",
"westernaustralia": "wa",
"northernterritory": "nt",
"victoria": "vic",
"queensland": "qld",
"southaustralia": "sa",
"tasmania": "tas",
"australiancapitolterritory": "act",
}
cities = {
"nsw": "sydney",
"vic": "melbourne",
"qld": "brisbane",
"wa": "perth",
"act": "canbera",
"nt": "darwin",
"sa": "adelaide",
}
cities["tas"] = "hobart"
print(cities)
print('-' * 10)
print("nsw state has:", cities["nsw"])
print("qld state has:", cities[states["queensland"]])
for state, abbrev in list(states.items()):
print(f"{state} is abbreviated to... {abbrev}")
for state, abbrev in list(states.items()):
print(f"{state} is abbreviated as {abbrev}")
print(f"{state} has the cities {cities[abbrev]}")
for k, v in states.items():
print(f"I have this key - {k} and this value - {v}")
## Return all keys sorted
print(sorted(states))
## Return all keys in original order
print(list(states)) |
993,696 | cfe37679bce33e9263fb40919e3fada008fb9439 | # import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import *
import sqlite3
from sqlite3 import Error, IntegrityError
import re
from datetime import datetime
import urllib
# import time
# from _socket import timeout
# from pstats import browser
file_name = "VedicMaratha.db"
db_schema = '''CREATE TABLE IF NOT EXISTS candidate (
id text PRIMARY KEY,
l_name text,
cast text,
height real,
reg_date text,
edu text,
prof text,
income int,
dob text,
time text,
place text,
rashi text,
nak text)'''
def CreateNewDB():
print ("Creating New DB\n")
try:
conn = sqlite3.connect("VedicMaratha.db")
except Error as e:
print(e)
else:
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS candidate (
id text PRIMARY KEY,
l_name text,
cast text,
height real,
reg_date text,
edu text,
prof text,
income int,
dob text,
time text,
place text,
rashi text,
nak text)''')
return conn
# finally:
# conn.close()
def GetProfielPic(browser, xpath, candidate_id):
try:
cand_img = browser.find_element_by_xpath(xpath).get_attribute("src")
except NoSuchElementException:
print ("Unable to get profile pic\n")
pass
else:
file_name = "snaps\\vedicmaratha\\" + candidate_id + '.jpeg'
# print cand_img
urllib.urlretrieve(cand_img, file_name)
def GetLastName(browser, xpath):
str1 = browser.find_element_by_xpath(xpath).text.encode('ascii','ignore')
str2 = re.findall('(?<=\().+(?=\))', str1)[0].title()
return str2.title()
def GetCast(browser, xpath):
str1 = browser.find_element_by_xpath(xpath).text
if (not(str1 == None or str1 == '')):
str1 = str1.strip()
str1 = str1.encode('ascii','ignore')
return str1.title()
else:
return None
def GetHeight(browser, xpath):
str1 = browser.find_element_by_xpath(xpath).text
if (not(str1 == None or str1 == '')):
str1 = str1.strip()
str1 = str1.encode('ascii','ignore')
str2 = re.findall('(?= )?\d', str1)[0]
str3 = re.findall('(?= )?\d', str1)[1]
return float(str2 +'.'+ str3)
else:
return None
def GetRegDate(browser, xpath):
str1 = browser.find_element_by_xpath(xpath).text
if (str1 != '--'):
str1 = str1.strip()
str1 = str1.encode('ascii','ignore')
str1 = str1.replace('-','/')
return str1
else:
return None
def GetEdu(browser, xpath):
str1 = browser.find_element_by_xpath(xpath).text
if (not(str1 == None or str1 == '')):
str1 = str1.strip()
str1 = str1.encode('ascii','ignore').title()
return str1
else:
return None
def GetProf(browser, xpath):
str1 = browser.find_element_by_xpath(xpath).text
if (not(str1 == None or str1 == '')):
str1 = str1.strip()
str1 = str1.encode('ascii','ignore').title()
return str1
else:
return None
def GetInc(browser, xpath):
str1 = browser.find_element_by_xpath(xpath).text
if (not(str1 == None or str1 == '')):
str1 = str1.strip()
if (str1 == 'Monthly' or str1 == 'Yearly'):
return None
else:
str1 = str1.replace('Monthly', '')
str1 = str1.replace(' Yearly', '')
str1 = str1.replace('Rs.', '')
str1 = str1.replace(',', '')
try:
income = int(str1)
except ValueError:
print "Unable to conver %s into integer\n" %(str1)
pass
return None
else:
return income
else:
return None
def GetDOB(browser, xpath):
str1 = browser.find_element_by_xpath(xpath).text
if (str1 != '--'):
str1 = str1.strip()
str1 = str1.encode('ascii','ignore')
str1 = str1.replace('-','/')
else:
return None
def GetTime(browser, xpath):
str1 = browser.find_element_by_xpath(xpath).text
if (not(str1 == None or str1 == '')):
str1 = str1.strip()
str1 = str1.encode('ascii','ignore')
time_lst = str1.split('-')
try:
if (time_lst[0].isdigit() and time_lst[1].isdigit() and time_lst[-1] in ('AM', 'PM')):
# hr = int(re.findall('\d\d(?=-)', str1)[0])
# mins = int(re.findall('\d\d(?=-)', str1)[1])
hr = int(time_lst[0])
mins = int(time_lst[1])
if (time_lst[-1] == 'PM'):
hr = hr + 12
return "{:02}:{:02}".format(hr, mins)
else:
return None
except IndexError:
pass
return None
else:
return None
def GetPlace(browser, xpath):
str1 = browser.find_element_by_xpath(xpath).text
if (not(str1 == None or str1 == '')):
str1 = str1.strip()
str1 = str1.encode('ascii','ignore').title()
return str1
else:
return None
def GetRashi(browser, xpath):
str1 = browser.find_element_by_xpath(xpath).text
if (not(str1 == None or str1 == '')):
str1 = str1.strip()
str1 = str1.replace('Rashi / Nakshatra / Charan / Nadi / Gan: ','')
token = str1.split(',')
if (token[0] != ' '):
return None
else:
return token[0]
else:
return None
def GetNak(browser, xpath):
str1 = browser.find_element_by_xpath(xpath).text
if (not(str1 == None or str1 == '')):
str1 = str1.strip()
str1 = str1.replace('Rashi / Nakshatra / Charan / Nadi / Gan: ','')
token = str1.split(',')
if (token[1] != ' '):
return None
else:
return token[1]
else:
return None
def StoreCandidateData(browser, c, candidate_id):
l_name = None
cast = None
height = None
reg_date = None
edu = None
prof = None
income = None
dob = None
time = None
place = None
rashi = None
nak = None
try:
#Wait for login box to load
WebDriverWait(browser, 5).until(EC.visibility_of_element_located((By.XPATH, '//table[@class="profile"]')))
# time.sleep(3)
GetProfielPic(browser, '//img[contains(@src, "photoprocess.php")]', candidate_id)
l_name = GetLastName(browser, '(//td)[29]')
cast = GetCast(browser, '(//td[@class="data"])[6]')
height = GetHeight(browser, '(//td[@class="data"])[8]')
reg_date = GetRegDate(browser, '(//td[@class="data"])[28]')
edu = GetEdu(browser, '(//td[@class="data"])[30]')
prof = GetProf(browser, '(//td[@class="data"])[32]')
income = GetInc(browser, '(//td[@class="data"])[36]')
dob = GetDOB(browser, '(//td[@class="data"])[2]')
time = GetTime(browser, '(//td[@class="data"])[38]')
place = GetPlace(browser, '(//td[@class="data"])[42]')
rashi = GetRashi(browser, '(//td[@class="data"])[45]')
nak = GetNak(browser, '(//td[@class="data"])[45]')
ProfLink = browser.current_url
now = datetime.now()
ProfCreatTime = now.strftime("%d/%m/%Y")
complete_det = "{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}".format(candidate_id, l_name, cast, height, reg_date, edu, prof, income, dob, time, place, rashi, nak)
print "%s\n" %(complete_det)
try:
c.execute("insert into PrimData (ProfId, LName, Height, Edu, Prof, Income) values (?, ?, ?, ?, ?, ?)", (candidate_id, l_name, height, edu, prof, income))
c.execute("insert into CastData (ProfId, SCast) values (?, ?)", (candidate_id, cast))
c.execute("insert into BirData (ProfId, BTime, BDate, MSign, Naksh) values (?, ?, ?, ?, ?)", (candidate_id, time, dob, rashi, nak))
c.execute("insert into BirLocData (ProfId, City) values (?, ?)", (candidate_id, place))
c.execute("insert into Metdata (ProfId, ProfRef, ProfLink, ProfCreatTime) values (?, ?, ?, ?)", (candidate_id, "Vedic Maratha", ProfLink, ProfCreatTime))
except IntegrityError:
print ("Unable to update the database\n")
except NoSuchElementException as e:
print ("StoreCandidateData : Unable to save the details because no such element\n")
print e
except TimeoutException:
print ("StoreCandidateData : Unable to load the profile\n")
def found_window(window_title):
def predicate(driver):
for handle in driver.window_handles:
try: driver.switch_to_window(handle)
except NoSuchWindowException:
return False
else:
if (driver.title == window_title):
return True # found window
else:
continue
return predicate
def CollectTenCandidatesData(browser, c):
try:
# We are now on new page of the candidates
curr_candidate_xpath = "//a[contains(@href, 'profile_by_public')]"
candidate_id_array = browser.find_elements_by_xpath(curr_candidate_xpath)
for candidate_id in candidate_id_array:
cand_id = candidate_id.text.strip().encode('ascii','ignore')
# print "Value of cand id is %s" %(cand_id)
# temp_var = (cand_id,)
c.execute("select exists (select PrimData.ProfId from PrimData where PrimData.ProfId = ?)", (cand_id,))
if (c.fetchone() == (0,)):
#New candiate data found save it
main_window = browser.current_window_handle
candidate_id.click()
# browser.implicitly_wait(30)
# time.sleep(3)
# print ("Number of windows opened %d\n ") %(len(browser.window_handles))
WebDriverWait(browser, 10, 2).until(found_window('Member Profile'))
StoreCandidateData(browser, c, cand_id)
browser.close()
browser.switch_to_window(main_window)
#switch to new window
# browser.switch_to_window(browser.window_handles[1])
# browser.switch_to_window('')
# print ("Title of window %s\n ") %browser.title
#
# for handle in browser.window_handles:
# if (main_window != handle):
# browser.switch_to_window(handle)
# print ("Switched to new window %s\n ") %browser.title
# StoreCandidateData(browser, c, cand_id)
# browser.close()
# browser.switch_to_window(main_window)
else:
print "%s is already in DB\n" %(cand_id)
except NoSuchElementException as e:
print ("CollectTenCandidatesData : Unable to find some elements\n")
print (e)
def NagivateToDashBoard(login_ID, login_pass, login_page, browser):
browser.get(login_page)
try:
#Wait for login box to load
login_element = WebDriverWait(browser, 5).until(EC.visibility_of_element_located((By.XPATH, '//table[@id="example"]')))
#Select Number of entries
login_element = Select(browser.find_element_by_xpath('//select[@name="example_length"]'))
login_element.select_by_value('100')
browser.implicitly_wait(5)
#Wait for Dashboard to load
# dash_board_element = WebDriverWait(browser, 30).until(EC.visibility_of_element_located((By.XPATH, '//div[@class="cPageData"]')))
except NoSuchElementException:
print ("Unable to navigate to pavitra vivah dash board\n")
except TimeoutException:
print ("Unable to use dash board due to time out\n")
def GetPageNum():
print ("GetPageNum\n")
def GoNextPage(browser):
browser.find_element_by_xpath('//a[@class="paginate_button next"]').click()
def ScrapLoadedPages(browser, conn):
#Rotate through all the search result pages
c = conn.cursor()
while (True):
try:
#Wait for the results to load
WebDriverWait(browser, 30).until(EC.visibility_of_element_located((By.XPATH, '//table[@class="dataTable no-footer"]')))
CollectTenCandidatesData(browser, c)
print ("Moving on to Next page\n")
GoNextPage(browser)
except NoSuchElementException as e:
print ("Seems like we are on last page, saving changes to database\n")
print e
break
# conn.commit()
# c.close()
def CollectAllQuickSearch(browser, conn):
ScrapLoadedPages(browser, conn)
|
993,697 | e467c1353d337f9f05cf12fab1fca1361bfb5057 | import numpy as np
class ActivationFunction(object):
@staticmethod
def Forward(x): raise Exception("Function not impolemented")
@staticmethod
def Backward(output,a, dO): raise Exception("Function not impolemented")
from ActivationFunction.Sigmoid import *
from ActivationFunction.ReLU import *
from ActivationFunction.Tanh import * |
993,698 | ac0db5b8ffa30ae9308bd2c8a84b3cc0ef69a9ff | # -*- coding:utf-8 -*-
import outlook
import config
import botModule
from menuRecognizer import *
menuRec = menuRecognizer()
mail = outlook.Outlook()
mail.login(config.address, config.password)
mail.inbox()
mail.read()
menuRec.setValidExcelMenuFileName()
ValidExcelFileName = menuRec.getExcelFileName()
if ValidExcelFileName == None: # No Menu
print("No Menu")
else:# if exists with menu, parse & print
botModule.load_content_along_time(ValidExcelFileName, 0)
#botModule.load_content_along_time(ValidExcelFileName, 1) #Lunch Menu!
#botModule.load_content_along_time(ValidExcelFileName, 2) #Night Menu!
#botModule.load_content_along_time(ValidExcelFileName, 0) #Breakfast Menu!
|
993,699 | 63dff96e598ae6594f8bedd4a7a5f55319dc2580 | #adriana ku
print ("Introdusca un rango de aņos")
print ("Aņo de inicio")
startYear = int(input())
print ("Aņo final")
endYear = int(input())
##print ("leap years:")
for year in range(startYear, endYear):
if (0 == year % 4) and (0 != year % 100) or (0 == year % 400):
print ('{} is leap year'.format(year)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.