seq_id stringlengths 4 11 | text stringlengths 113 2.92M | repo_name stringlengths 4 125 ⌀ | sub_path stringlengths 3 214 | file_name stringlengths 3 160 | file_ext stringclasses 18
values | file_size_in_byte int64 113 2.92M | program_lang stringclasses 1
value | lang stringclasses 93
values | doc_type stringclasses 1
value | stars int64 0 179k ⌀ | dataset stringclasses 3
values | pt stringclasses 78
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
2309854719 | import os
import subprocess
import sys
import tempfile
from contextlib import contextmanager
from os import mkdir, chdir
from pathlib import Path
from subprocess import check_call, PIPE
from tempfile import TemporaryDirectory
from typing import Union, Iterator, Optional, Iterable, Any
@contextmanager
def using_cwd(new_cwd: Union[Path, str]) -> Iterator[None]:
"""
Context manager for switching working directory temporarily.
>>> with tempfile.TemporaryDirectory() as tempdir:
... original_cwd = Path.cwd()
... with using_cwd(tempdir):
... assert Path.cwd() == Path(tempdir)
... assert Path.cwd() == original_cwd
"""
old_cwd = Path.cwd()
try:
os.chdir(new_cwd)
yield
finally:
os.chdir(old_cwd)
@contextmanager
def using_temp_cwd() -> Iterator[Path]:
"""
Context manager that executes its body in a temporary directory.
The context manager yields the temporary directory as Path object.
>>> original_cwd = Path.cwd()
>>> with using_temp_cwd() as tmpdir_path:
... assert isinstance(tmpdir_path, Path)
... assert Path.cwd() != original_cwd
... assert tmpdir_path.exists()
>>> assert not tmpdir_path.exists()
"""
with TemporaryDirectory() as tmpdir:
with using_cwd(tmpdir):
yield Path(tmpdir)
def shell(*args, **kwargs) -> Optional[int]:
"""
Wrapper around subprocess.call, that enables shell and suppresses the return value,
unless it is non-zero.
For easier use in doctests, where the return value adds unnecessary verbosity.
It also redirects stdout to the print command, so doctest is aware of it.
"""
if "stdout" not in kwargs:
kwargs["stdout"] = PIPE
process = subprocess.Popen(*args, shell=True, **kwargs)
if process.stdout is not None: # e.g. for stdout=DEVNULL
for line in process.stdout:
line: bytes
sys.stdout.write(line.decode(sys.getdefaultencoding(), errors="replace"))
exit_code = process.wait()
if exit_code == 0:
return None
else:
return exit_code
def create_files(*filenames: str, cwd: Path = None):
"""
Create empty files at the given names.
If cwd is given, create them relative to that root.
A path ending in / can be used to create an empty directory.
>>> tempdir = tempfile.TemporaryDirectory(prefix="create_files.")
>>> create_files("readme.md", "src/main.c", "src/main.h", "test/", cwd=tempdir.name)
>>> ls(tempdir.name, recursive=True)
readme.md
src/main.c
src/main.h
test/
"""
cwd: Path = (
Path.cwd() if cwd is None else
Path(cwd))
for filename in filenames:
full_path = cwd / filename
full_path.parent.mkdir(parents=True, exist_ok=True)
if filename.endswith("/"):
full_path.mkdir(exist_ok=True)
else:
full_path.touch(exist_ok=True)
def make_temporary_directory(*args, **kwargs) -> Path:
"""Wrapper around TemporaryDirectory, that keeps the directory
alive until the end of execution and returns it as a Path object."""
obj = TemporaryDirectory(*args, **kwargs)
make_temporary_directory.items.add(obj)
return Path(obj.name)
make_temporary_directory.items = set()
def chdir2tmp(*args, **kwargs) -> None:
"""
Create a temporary directory for the runtime of the program, and chdir to it.
Parameters the same as C(tempfile.TemporaryDirectory).
"""
tmpdir = make_temporary_directory(*args, **kwargs)
os.chdir(tmpdir)
def ls(
root: Optional[Union[str, Path]] = None,
recursive: bool = False,
) -> None:
"""
Print all the files in the directory for use in testing.
Consider an example directory
>>> chdir2tmp(prefix="dir_tree.")
>>> create_files("a.txt", "test/", "src/b.txt", "src/c.txt")
By default, the files in the current directory are printed,
with subdirectories indicated by trailing /.
>>> ls()
a.txt
src/
test/
With the 'recursive' option, the whole directory tree is printed.
>>> ls(recursive=True)
a.txt
src/b.txt
src/c.txt
test/
Paths are always printed relative to the root path
>>> oldpwd = Path.cwd()
>>> chdir("..")
>>> ls(oldpwd)
a.txt
src/
test/
"""
root: Path = (
Path.cwd() if root is None else
Path(root))
def print_recursively(path: Path):
path_string: str = str(path.relative_to(root)).replace(os.sep, "/")
if not path.is_dir():
print(path_string)
else:
entries = sorted(path.glob("*"))
if entries and recursive:
for entry in entries:
print_recursively(entry)
else:
print(path_string + "/")
for entry in root.glob("*"):
print_recursively(entry)
def lstree(root: Optional[Union[str, Path]] = None):
"""
Render the directory tree under root to stdout.
>>> chdir2tmp()
>>> create_files("main.c", "lib/string.c", "lib/string.h", "test/a.t", "test/b.t", "empty/")
>>> lstree()
|- empty/
|- lib/
| |- string.c
| '- string.h
|- main.c
'- test/
|- a.t
'- b.t
"""
root: Path = (
Path.cwd() if root is None else
Path(root))
assert root.is_dir()
def recur(directory: Path, prefix0: str = "", prefix1: str = ""):
assert directory.is_dir()
entries = sorted(directory.glob("*"))
for idx, entry in enumerate(entries):
is_last: bool = idx == len(entries) - 1
if not entry.is_dir():
if is_last:
print(prefix1 + " '- " + entry.name)
else:
print(prefix1 + " |- " + entry.name)
else:
if is_last:
print(prefix1 + " '- " + entry.name + "/")
recur(entry, prefix0=prefix1 + " '- ", prefix1=prefix1 + " ")
else:
print(prefix1 + " |- " + entry.name + "/")
recur(entry, prefix0=prefix1 + " |- ", prefix1=prefix1 + " | ")
recur(root)
| kbauer/zgit | zgit/lib/testutil.py | testutil.py | py | 6,397 | python | en | code | 0 | github-code | 13 |
41037588436 | ciphertext = bytes.fromhex('104e137f425954137f74107f525511457f5468134d7f146c4c')
plaintext = None
# Prova tutte le possibili chiavi non stampabili
for key in range(256):
# Esegui l'operazione di XOR tra il testo cifrato e la chiave
candidate = bytes([b ^ key for b in ciphertext])
# Se il risultato decifrato contiene solo caratteri ASCII stampabili,
# abbiamo trovato la chiave corretta
if all(32 <= b <= 126 for b in candidate):
plaintext = candidate.decode()
break
if plaintext:
print("Il messaggio decifrato è:", plaintext)
print("La flag è:", 'flag{' + plaintext + '}')
else:
print("Non è stato possibile decifrare il messaggio.")
# FLAG ==> flag{0n3_byt3_T0_ru1e_tH3m_4Ll} | EngJohn12/CYBERCHALLENGE-CODE | Crypto05-XOR2.py | Crypto05-XOR2.py | py | 731 | python | it | code | 0 | github-code | 13 |
71675584339 |
from django.contrib.gis.db import models
class Region(models.Model):
idreg = models.FloatField(null=True)
id = models.BigIntegerField(primary_key=True)
province = models.CharField(max_length=254,null=True)
region = models.CharField(max_length=254,null=True)
geom = models.MultiPolygonField(srid=4326,null=True)
# Auto-generated `LayerMapping` dictionary for WorldBorder model
regionborder_mapping = {
'idreg': 'IDREG',
'id': 'ID',
'province': 'PROVINCE',
'region': 'REGION',
'geom': 'MULTIPOLYGON',
}
| Oviane16/sig | world/models.py | models.py | py | 544 | python | en | code | 0 | github-code | 13 |
37124717124 | from odoo import fields, models, api, _
from odoo.exceptions import Warning
import random
from odoo.tools import float_is_zero
import json
from odoo.exceptions import UserError, ValidationError
from collections import defaultdict
class pos_config(models.Model):
_inherit = 'pos.config'
def _get_default_location(self):
return self.env['stock.warehouse'].search([('company_id', '=', self.env.user.company_id.id)],
limit=1).lot_stock_id
pos_display_stock = fields.Boolean(string='Display Stock in POS')
pos_stock_type = fields.Selection(
[('onhand', 'Qty on Hand'),('available', 'Qty Available')], default='onhand', string='Stock Type', help='Seller can display Different stock type in POS.')
pos_allow_order = fields.Boolean(string='Allow POS Order When Product is Out of Stock')
pos_deny_order = fields.Char(string='Deny POS Order When Product Qty is goes down to')
stock_position = fields.Selection(
[('top_right', 'Top Right'), ('top_left', 'Top Left'), ('bottom_right', 'Bottom Right')], default='top_left', string='Stock Position')
show_stock_location = fields.Selection([
('all', 'All Warehouse'),
('specific', 'Current Session Warehouse'),
], string='Show Stock Of', default='all')
stock_location_id = fields.Many2one(
'stock.location', string='Stock Location',
domain=[('usage', '=', 'internal')], required=True, default=_get_default_location)
color_background = fields.Char(
string='Color',)
font_background = fields.Char(
string='Font Color',)
low_stock = fields.Float(
string='Product Low Stock',default=0.00)
class ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
pos_display_stock = fields.Boolean(related="pos_config_id.pos_display_stock",readonly=False)
pos_stock_type = fields.Selection(related="pos_config_id.pos_stock_type", readonly=False,string='Stock Type', help='Seller can display Different stock type in POS.')
pos_allow_order = fields.Boolean(string='Allow POS Order When Product is Out of Stock',readonly=False,related="pos_config_id.pos_allow_order")
pos_deny_order = fields.Char(string='Deny POS Order When Product Qty is goes down to',readonly=False,related="pos_config_id.pos_deny_order")
show_stock_location = fields.Selection(string='Show Stock Of',readonly=False, related="pos_config_id.show_stock_location")
stock_location_id = fields.Many2one(
'stock.location', string='Stock Location',
domain=[('usage', '=', 'internal')], required=True, related="pos_config_id.stock_location_id",readonly=False)
stock_position = fields.Selection(related="pos_config_id.stock_position", readonly=False,string='Stock Position',required=True)
color_background = fields.Char(string='Background Color',readonly=False,related="pos_config_id.color_background")
font_background = fields.Char(string='Font Color',readonly=False,related="pos_config_id.font_background")
low_stock = fields.Float(string='Product Low Stock',readonly=False,related="pos_config_id.low_stock")
class pos_order(models.Model):
_inherit = 'pos.order'
location_id = fields.Many2one(
comodel_name='stock.location',
related='config_id.stock_location_id',
string="Location", store=True,
readonly=True,
)
class stock_quant(models.Model):
_inherit = 'stock.move'
@api.model
def sync_product(self, prd_id):
notifications = []
ssn_obj = self.env['pos.session'].sudo()
prod_fields = ssn_obj._loader_params_product_product()['search_params']['fields']
prod_obj = self.env['product.product'].sudo()
product = prod_obj.with_context(display_default_code=False).search_read([('id', '=', prd_id)],prod_fields)
product_id = prod_obj.search([('id', '=', prd_id)])
res = product_id._compute_quantities_dict(self._context.get('lot_id'), self._context.get('owner_id'), self._context.get('package_id'), self._context.get('from_date'), self._context.get('to_date'))
product[0]['qty_available'] = res[product_id.id]['qty_available']
if product :
categories = ssn_obj._get_pos_ui_product_category(ssn_obj._loader_params_product_category())
product_category_by_id = {category['id']: category for category in categories}
product[0]['categ'] = product_category_by_id[product[0]['categ_id'][0]]
vals = {
'id': [product[0].get('id')],
'product': product,
'access':'pos.sync.product',
}
notifications.append([self.env.user.partner_id,'product.product/sync_data',vals])
if len(notifications) > 0:
self.env['bus.bus']._sendmany(notifications)
return True
@api.model
def create(self, vals):
res = super(stock_quant, self).create(vals)
notifications = []
for rec in res:
rec.sync_product(rec.product_id.id)
return res
def write(self, vals):
res = super(stock_quant, self).write(vals)
notifications = []
for rec in self:
rec.sync_product(rec.product_id.id)
return res
class ProductInherit(models.Model):
_inherit = 'product.product'
quant_text = fields.Text('Quant Qty', compute='_compute_avail_locations', store=True)
def get_low_stock_products(self,low_stock):
products=self.search([('detailed_type', '=' ,'product')]);
product_list=[]
for product in products:
if product.qty_available <= low_stock:
product_list.append(product.id)
return product_list
@api.depends('stock_quant_ids', 'stock_quant_ids.product_id', 'stock_quant_ids.location_id',
'stock_quant_ids.quantity')
def _compute_avail_locations(self):
notifications = []
for rec in self:
final_data = {}
rec.quant_text = json.dumps(final_data)
if rec.type == 'product':
quants = self.env['stock.quant'].sudo().search(
[('product_id', 'in', rec.ids), ('location_id.usage', '=', 'internal')])
for quant in quants:
loc = quant.location_id.id
if loc in final_data:
last_qty = final_data[loc][0]
final_data[loc][0] = last_qty + quant.quantity
else:
final_data[loc] = [quant.quantity, 0, 0]
rec.quant_text = json.dumps(final_data)
return True
class StockPicking(models.Model):
_inherit = 'stock.picking'
@api.model
def _create_picking_from_pos_order_lines(self, location_dest_id, lines, picking_type, partner=False):
"""We'll create some picking based on order_lines"""
pickings = self.env['stock.picking']
stockable_lines = lines.filtered(
lambda l: l.product_id.type in ['product', 'consu'] and not float_is_zero(l.qty,
precision_rounding=l.product_id.uom_id.rounding))
if not stockable_lines:
return pickings
positive_lines = stockable_lines.filtered(lambda l: l.qty > 0)
negative_lines = stockable_lines - positive_lines
if positive_lines:
pos_order = positive_lines[0].order_id
location_id = pos_order.location_id.id
vals = self._prepare_picking_vals(partner, picking_type, location_id, location_dest_id)
positive_picking = self.env['stock.picking'].create(vals)
positive_picking._create_move_from_pos_order_lines(positive_lines)
try:
with self.env.cr.savepoint():
positive_picking._action_done()
except (UserError, ValidationError):
pass
pickings |= positive_picking
if negative_lines:
if picking_type.return_picking_type_id:
return_picking_type = picking_type.return_picking_type_id
return_location_id = return_picking_type.default_location_dest_id.id
else:
return_picking_type = picking_type
return_location_id = picking_type.default_location_src_id.id
vals = self._prepare_picking_vals(partner, return_picking_type, location_dest_id, return_location_id)
negative_picking = self.env['stock.picking'].create(vals)
negative_picking._create_move_from_pos_order_lines(negative_lines)
try:
with self.env.cr.savepoint():
negative_picking._action_done()
except (UserError, ValidationError):
pass
pickings |= negative_picking
return pickings
| lequipeur/main | bi_pos_stock/models/bi_pos_stock.py | bi_pos_stock.py | py | 8,945 | python | en | code | 1 | github-code | 13 |
34114273374 | from typing import List
ALPHA_LOWER = "abcdefghijklmnopqrstuvwxyz"
ALPHA_CAPITAL = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
ALPHA_ALL = ALPHA_LOWER + ALPHA_CAPITAL
NUM = "0123456789"
ALPHA_NUM = ALPHA_ALL + NUM
def group_by_word(line: str, seperator=" ", brackets=None) -> List[str]:
"""Groups a string by words and contents within brackets"""
line = line.strip()
line += seperator # This makes it easer to find the last word
_assert_valid_seperator(seperator)
if brackets is not None:
_assert_valid_brackets(seperator, brackets)
start_bracket, end_bracket = brackets
words = []
while len(line) > 0:
if brackets is not None:
first_seperator = line.find(seperator)
first_start_bracket = line.find(start_bracket)
if first_start_bracket != -1 and first_start_bracket < first_seperator:
end_string = f"{end_bracket}{seperator}"
else:
end_string = seperator
else:
end_string = seperator
# Find the closing string
end = line.find(end_string)
if end == -1:
raise ValueError("Not a valid string, could not find a closing bracket")
word = line[: end + len(end_string) - 1]
words.append(word)
line = line[end + len(end_string) :]
return words
def is_variable_name(variable):
if not isinstance(variable, str):
return False # Should be a string
if variable[0] not in ALPHA_ALL:
return False # Should start with a letter
if not set(variable) < set(ALPHA_NUM + "_"):
return False # Should only contain letters, digits and underscore
return True
def is_number(number):
# Allow for negative numbers
if number.startswith("-"):
number = number[1:]
return len(number) > 0 and set(number) <= set(NUM)
def is_float(value):
if not value.count(".") == 1:
return False
parts = value.split(".")
# Both int_part and dec_part cannot be zero
if all(len(part) == 0 for part in parts):
return False
return all(len(part) == 0 or is_number(part) for part in parts)
def rspaces(val, min_chars=4):
val = str(val)
return " " * (min_chars - len(val)) + val
def _assert_valid_seperator(seperator):
if not isinstance(seperator, str):
raise TypeError("seperator should be a string")
if len(seperator) == 0:
raise ValueError("seperator should contain at least one character")
def _assert_valid_brackets(seperator, brackets):
if not isinstance(brackets, str):
raise TypeError("brackets should be a string")
if not (len(brackets) == 2 and len(set(brackets)) == 2):
raise ValueError("brackets should be two unique characters")
if seperator in brackets:
raise ValueError("seperator should not be part of brackets")
| QuTech-Delft/netqasm | netqasm/util/string.py | string.py | py | 2,858 | python | en | code | 17 | github-code | 13 |
4067530302 | import torch
import torch.nn.functional as F
@torch.no_grad()
def evaluate(model, dataset, split_idx, eval_func, criterion, args, result=None):
if result is not None:
out = result
else:
model.eval()
out = model(dataset.graph['node_feat'], dataset.graph['edge_index'])
train_acc = eval_func(
dataset.label[split_idx['train']], out[split_idx['train']])
valid_acc = eval_func(
dataset.label[split_idx['valid']], out[split_idx['valid']])
test_acc = eval_func(
dataset.label[split_idx['test']], out[split_idx['test']])
out = F.log_softmax(out, dim=1)
valid_loss = criterion(
out[split_idx['valid']], dataset.label.squeeze(1)[split_idx['valid']])
return train_acc, valid_acc, test_acc, valid_loss, out
| qitianwu/DIFFormer | image and text/eval.py | eval.py | py | 788 | python | en | code | 248 | github-code | 13 |
32270275683 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 20 11:10:24 2021
@author: sarak
"""
# Change order of keys in dictionary - OrderedDict
def main():
from collections import OrderedDict
d = OrderedDict()
d['a'] = 1
d['b'] = 2
d['c'] = 3
d['d'] = 4
print(d)
d.move_to_end('a')
print(d)
d.move_to_end('d', last= False)
print(d)
for key in d.keys():
print(key)
# OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
# OrderedDict([('b', 2), ('c', 3), ('d', 4), ('a', 1)])
# OrderedDict([('d', 4), ('b', 2), ('c', 3), ('a', 1)])
# d
# b
# c
# a
if __name__ == '__main__':
main()
| sara-kassani/1000_Python_example | 07_dictionary/18_ordereddict_change_order_keys.py | 18_ordereddict_change_order_keys.py | py | 765 | python | en | code | 1 | github-code | 13 |
21603468145 |
class SimMIM(nn.Module):
def __init__(self, in_chans, encoder, encoder_stride):
super().__init__()
self.encoder = encoder
self.encoder_stride = encoder_stride
self.decoder = nn.Sequential(
nn.Conv2d(
# in_channels=self.encoder.num_features[-1],
in_channels=self.encoder.num_features,
out_channels=self.encoder_stride ** 2 * 3, kernel_size=1),
nn.PixelShuffle(self.encoder_stride),
)
self.in_chans = self.encoder.in_chans
self.patch_size = self.encoder.patch_size
def forward(self, x, mask):
features = self.encoder(x, mask)
x_rec = self.decoder(features[-1])
return x_rec
class SSL(nn.Module):
def __init__(self, cfg, encoder_cfg, decoder_cfg, seg_cfg, stride=32):
super().__init__()
encoder_cfg.pop('model_name')
# self.s = SwinTransformerForSimMIM(**encoder_cfg)
self.s = SwinTransformerForSimMIM(img_size=192,
win_size=6,
embed_dim=128,
depths=[2, 2, 18, 2],
num_heads=[4,8,16,32],
**encoder_cfg)
# self.s = VisionTransformerForSimMIM(norm_layer=partial(nn.LayerNorm, eps=1e-6), **encoder_cfg)
self.sm = SimMIM(3, self.s, stride)
# self.p = torch.nn.Parameter(torch.ones(1))
def forward(self, batch):
x = batch['xb']
mask = batch['mask']
# print(mask.shape, x.shape)
r = self.sm(x, mask) # B,C,H,W
# r = self.p * x
cls = torch.zeros(1).cuda()
return dict(yb=r, cls=cls)
| bakeryproducts/hmib | src/mim/nn.py | nn.py | py | 1,772 | python | en | code | 0 | github-code | 13 |
44275143122 | import tensorflow as tf
from tf_bodypix.api import download_model, load_model, BodyPixModelPaths
import cv2
from matplotlib import pyplot as plt
import numpy as np
import urllib.request
import sys
import os
import time
import json
# -------------------input url to return image-------------------#
def url_to_image(url):
resp = urllib.request.urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
return image
path = "\public\images"
finalpath = os.getcwd() + path
os.chdir(finalpath)
img = url_to_image(sys.argv[1])
# -------------------import tensorflow library-------------------#
bodypix_model = load_model(
download_model(BodyPixModelPaths.MOBILENET_FLOAT_50_STRIDE_16)
)
# -------------------resize-------------------#
scale = img.shape[0] / 500
width = int(img.shape[1] / scale)
height = 500
dim = (width, height)
resized = cv2.resize(img, dim, interpolation=cv2.INTER_AREA)
# -------------------mask-------------------#
result = bodypix_model.predict_single(resized)
mask = result.get_mask(threshold=0.1).numpy().astype(np.uint8)
mask[mask > 0] = cv2.GC_PR_FGD
mask[mask == 0] = cv2.GC_BGD
# -------------------define bg fg array---------------------#
fgModel = np.zeros((1, 65), dtype="float")
bgModel = np.zeros((1, 65), dtype="float")
# -------------------run grabCut---------------------#
start = time.time()
(mask, bgModel, fgModel) = cv2.grabCut(
resized, mask, None, bgModel, fgModel, iterCount=5, mode=cv2.GC_INIT_WITH_MASK
)
end = time.time()
# -------------------post-process mask---------------------#
outputMask = np.where((mask == cv2.GC_BGD) | (mask == cv2.GC_PR_BGD), 0, 1)
outputMask = (outputMask * 255).astype("uint8")
cv2.imwrite("testimage.jpg", outputMask)
# -------------------measurements---------------------#
newimage = cv2.imread("testimage.jpg")
lineimage = cv2.imread("testimage.jpg")
# -------------------input different height---------------------#
width = newimage.shape[1]
def findMeasurements(height):
leftboundary = [0]
rightboundary = [0]
widths = []
blackwidths = []
measurements = []
j = 0
k = 0
continued = True
while continued:
# find left boundary
for i in range(rightboundary[j], width):
if (newimage[height, i][0] == 255) & continued:
leftboundary.append(i)
k += 1
break
if i == width - 1:
continued = False
# find right boundary
for i in range(leftboundary[k], width):
if (newimage[height, i][0] == 0) & continued:
rightboundary.append(i)
j += 1
break
if i == width - 1:
continued = False
for i in range(1, len(rightboundary)):
widths.append(rightboundary[i] - leftboundary[i])
for i in range(1, len(leftboundary)):
blackwidths.append(leftboundary[i] - rightboundary[i - 1])
blackwidths.append(width - rightboundary[-1])
for i in range(1, len(leftboundary)):
cv2.line(
lineimage,
(leftboundary[i], height),
(rightboundary[i], height),
(255, 0, 0),
5,
)
measurements.append(widths)
measurements.append(blackwidths)
measurements.append(leftboundary)
measurements.append(rightboundary)
return measurements
def findMax(width):
max = [0, 0]
max[0] = width[0]
for i in range(0, len(width)):
if width[i] > max[0]:
max[0] = width[1]
max[1] = i
return max
levels = [int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4])]
# create 2d arrays of measurements
smeasure = findMeasurements(levels[0])
wmeasure = findMeasurements(levels[1])
hmeasure = findMeasurements(levels[2])
# include max values to measurement array
smeasure.append(findMax(smeasure[0]))
wmeasure.append(findMax(wmeasure[0]))
hmeasure.append(findMax(hmeasure[0]))
# cv2.imwrite("newimage.jpg", newimage)
cv2.imwrite("lineimage.jpg", lineimage)
# -------------------check accuracy---------------------#
swthres = 0.55
shthres = 0.80
hwthres = 0.55
def checkAccuracy(smeasure, wmeasure, hmeasure):
# 0 represents accurate, 1 represents inaccurate
accuracy = [0, 0, 0]
max = [smeasure[4][0], wmeasure[4][0], hmeasure[4][0]]
for i in range(0, 3):
# check if the value is equal zero
if max[i] == 0:
accuracy[i] = 1
# compare left and right boundaries of assumed swh,
# i assume that the smaller(left) or larger(right) measurement is the correct one
if max[0] / max[1] < swthres or max[0] / max[2] < shthres:
accuracy[0] = 1
if max[1] / max[0] < swthres or max[1] / max[2] < hwthres:
accuracy[1] = 1
if max[2] / max[0] < shthres or max[2] / max[1] < hwthres:
accuracy[2] = 1
return accuracy
accuracy = checkAccuracy(smeasure, wmeasure, hmeasure)
# -------------------make corrections---------------------#
def makeCorrections(accuracy, measure, width):
corrected = measure
newmax = measure[4]
newwidths = []
if accuracy == 1:
white = measure[0]
black = measure[1]
maxI = newmax[1]
wrongBlack = [0, 0]
left = [black[maxI], maxI]
right = [black[maxI + 1], maxI + 1]
if left[1] == 0:
wrongBlack = right
elif right[1] == len(black) - 1:
wrongBlack = left
# check if left or right black has a larger value
else:
if left[0] < right[0]:
wrongBlack = left
else:
wrongBlack = right
# corrections to max val and corrected array
if wrongBlack == left:
# corrections to max val
newmax[0] = newmax[0] + left[0] + white[maxI - 1]
newmax[1] = maxI - 1
# corrections to blackwidths
corrected[1].pop(left[1])
# corrections to left/right boundary
corrected[2].pop(maxI + 1)
corrected[3].pop(maxI)
else:
newmax[0] = newmax[0] + right[0] + white[maxI + 1]
newmax[1] = maxI
corrected[1].pop(right[1])
corrected[2].pop(maxI + 2)
corrected[3].pop(maxI + 1)
# corrections to widths
for i in range(1, len(corrected[3])):
newwidths.append(corrected[3][i] - corrected[2][i])
# make final changes to corrected array
corrected[0] = newwidths
corrected[4] = newmax
return corrected
# -----loop accuracy and corrections-----#
while accuracy != [0, 0, 0]:
smeasure = makeCorrections(accuracy[0], smeasure, width)
wmeasure = makeCorrections(accuracy[1], wmeasure, width)
hmeasure = makeCorrections(accuracy[2], hmeasure, width)
accuracy = checkAccuracy(smeasure, wmeasure, hmeasure)
# create a corrected array for bodyshape calculator
corrected = [smeasure[4], wmeasure[4], hmeasure[4]]
swratio = corrected[0][0] / corrected[1][0]
whratio = corrected[1][0] / corrected[2][0]
# -------------------calc body shapes---------------------#
def bodyShape(corrected, gender):
shoulder = corrected[0][0]
waist = corrected[1][0]
hip = corrected[2][0]
swratio = shoulder / waist
whratio = waist / hip
shratio = shoulder / hip
# used for rectangle comparison (within 5% of each other)
# find largest values
rmax = findMax(corrected)[0]
# include other vals
rvals = []
for i in corrected:
if i != max:
rvals.append(i)
# used for hourglass comparison (hips and shoulders within 5% of each other)
if shoulder > hip:
hgval = [shoulder, hip]
else:
hgval = [hip, shoulder]
# determine body shape
if gender:
if shratio <= 0.96:
# male-oval
if whratio > 0.9:
shape = 4
# male-triangle
else:
shape = 1
# male-inverted-triangle
elif swratio > 1.6:
shape = 0
# male-trapezoid
elif swratio > 1.5:
shape = 3
# rectangle
else:
shape = 2
else:
# female-inverted-triangle
if shoulder / hip > 1.05:
shape = 0
# female-pear
elif hip / shoulder >= 1.05:
shape = 1
# female-rectangle
elif swratio < 1.33 and rvals[0] > 0.95 * rmax and rvals[1] > 0.95 * rmax:
shape = 2
# female-hourglass
elif swratio >= 1.33 and whratio <= 0.75 and hgval[1] >= 0.95 * hgval[0]:
shape = 3
# female-apple
else:
shape = 4
return shape
def capitalise(string):
if string == "true":
return True
return False
x = {
"bodyshape": bodyShape(corrected, capitalise(sys.argv[5])),
"shoulder": corrected[0][0],
"waist": corrected[1][0],
"hips": corrected[2][0],
"swratio": round(float(swratio), 2),
"whratio": round(float(whratio), 2),
}
y = json.dumps(x)
print(y)
| Bobowoo2468/SwiftTailorServer | bodyshape.py | bodyshape.py | py | 9,146 | python | en | code | 0 | github-code | 13 |
33175450027 | from crontab import CronTab
from datetime import datetime, timedelta # for the current time and adding time
import pytz # to enale comparison of datetime and astral time, astral is ofset, datetime is naive
from astral import LocationInfo # to get the location info
from astral.sun import sun # to get the sunrise time
# ofset setting
utc=pytz.UTC
now = utc.localize(datetime.now())
my_cron = CronTab(user='pi')
# set Astral location for Whitley Bay
city = LocationInfo("Whitley Bay", "England", "Europe/London", 55.0464, 1.4513)
# get today's sunrise time
s = sun(city.observer, date=datetime.date(datetime.now()))
print("Today's sunrise is at:")
print(s['sunrise'])
job = my_cron.new(command='nohup python3 /home/pi/justpics.py &')
job.hour.on(2)
job.minute.on(10)
my_cron.write()
for job in my_cron:
print(job) | llewmihs/sunrise300 | Development/crontabtest.py | crontabtest.py | py | 863 | python | en | code | 1 | github-code | 13 |
11364007352 | import sys
from pprint import pprint
import random
import numpy as np
import tensorflow as tf
import optuna
from optuna.integration.tfkeras import TFKerasPruningCallback
gpus = tf.config.experimental.list_physical_devices('GPU')
tf.config.experimental.set_memory_growth(gpus[0], True)
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Input, LeakyReLU, Dropout
from tensorflow.keras.utils import to_categorical
num_classes = 10
image_size = 784
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
training_data = training_images.reshape(training_images.shape[0], image_size)
test_data = test_images.reshape(test_images.shape[0], image_size)
training_labels = to_categorical(training_labels, num_classes)
test_labels = to_categorical(test_labels, num_classes)
def objective(trial):
pruner = TFKerasPruningCallback(trial, 'loss')
model = Sequential()
model.add(Input(shape=(image_size,)))
n_layers = trial.suggest_categorical('layers', [1, 2, 3, 4])
alpha = trial.suggest_uniform('alpha', 0.001, 0.05)
dropout_rate = trial.suggest_uniform('dropout', 0.0, 0.3)
dropout_start = trial.suggest_int('start', 0, n_layers)
for index in range(n_layers):
if index > dropout_start:
model.add(Dropout(rate=dropout_rate))
n_units = trial.suggest_categorical('layer_%d' % index, [16, 32, 64, 128, 256])
model.add(Dense(units=n_units))
model.add(LeakyReLU(alpha=alpha))
model.add(Dense(units=num_classes, activation='softmax'))
model.compile(optimizer="adam", loss='categorical_crossentropy', metrics=['accuracy'])
history = model.fit(training_data, training_labels,
batch_size=128,
epochs=15,
verbose=0,
validation_split=.2,
shuffle=True,
callbacks=[pruner])
print('metrics: {:.4f} {:.4f} {:.4f} {:.4f}'.format(history.history['accuracy'][-1],
history.history['loss'][-1],
history.history['val_accuracy'][-1],
history.history['val_loss'][-1]), file=sys.stderr)
sys.stderr.flush()
return history.history['accuracy'][-1]
study = optuna.create_study(direction='maximize')
study.optimize(objective, n_trials=1000) | atobe/intro_to_dl_shared | search_mnist.py | search_mnist.py | py | 2,224 | python | en | code | 0 | github-code | 13 |
17332305061 | """US07"""
from datetime import date
import Error
months = {'JAN': 1, 'FEB': 2, 'MAR': 3, 'APR': 4, 'MAY': 5, 'JUN': 6,
'JUL': 7, 'AUG': 8, 'SEP': 9, 'OCT': 10, 'NOV': 11, 'DEC': 12}
def less_than_150(member, errors):
"""
The age of an individual should less than 150 years
:param member: dict
:return: bool
"""
if not member:
return errors
birth_date = parse_date(member['Birthday'])
if birth_date == -1:
return errors
#last_date could be the death date or today
last_date = parse_date(member['Death']) if member['Death'] != 'NA' else date.today()
#inspect if the indi elder than 150 years old
age = last_date.year - birth_date.year - ((last_date.month, last_date.day) < (birth_date.month, birth_date.day))
#print(age)
if age >= 150:
us07Err = Error.Error(Error.ErrorEnum.US07)
us07Err.alterErrMsg(age, member['ID'])
errors.add(us07Err)
return errors
def parse_date(string):
date_list = string.split()
if date_list[0] == '??':
date_list[0] = 1
try:
valid_date = date(int(date_list[2]), months[date_list[1]], int(date_list[0]))
except:
return -1
return valid_date
| EricLin24/SSW555-DriverlessCar | lessthan_150.py | lessthan_150.py | py | 1,225 | python | en | code | 0 | github-code | 13 |
2752044885 | '''
*********** Curso de programación acelerada en Python ************
Date 04-08-2022
File: sesion2/ejercicio13.py
Autor: Adriana Romero
Action: Permita ingresar un valor del 1 al
10 y nos muestre la tabla de multiplicar del mismo.
'''
numero = int(input("Introduce un valor: "))
for i in range(0, 11):
resultado = i*numero
print(("%d x %d = %d") % (numero, i, resultado)) | Adri2246/Curso-de-programacion-acelerada-en-python | Sesion2/ejercicio17.py | ejercicio17.py | py | 379 | python | es | code | 0 | github-code | 13 |
17585447427 | import os
import csv
import pandas as pd
from datetime import datetime
def is_file_empty(file_name):
"""
Check if file is empty by reading first character in it
"""
# open ile in read mode
with open(file_name, 'r') as read_obj:
# read first character
one_char = read_obj.read(1)
# if not fetched then file is empty
if not one_char:
return True
return False
def get_last_timestamp():
df = pd.DataFrame(pd.read_csv('data/processed/airquality_data_to_use.csv'))
last_row = df.iloc[-1]
last_timestamp = last_row['timestamp']
return last_timestamp
def main():
# set up file to be read & appended to
processed_file = 'data/processed/airquality_data_to_use.csv'
with open(processed_file, 'a+', encoding='UTF8') as f_out:
writer = csv.writer(f_out)
# grab the last date in the old file to compare
prev_file_last_timestamp = get_last_timestamp()
print('prev last timestamp: ' + prev_file_last_timestamp)
# only write the header if the csv is empty to begin with (should only happen once)
if is_file_empty(processed_file):
header = ['timestamp', 'pm1_cf', 'pm25_cf', 'pm10_cf', 'pm1', 'pm25', 'pm10']
writer.writerow(header)
# grab the raw data that was uploaded from the raspberry pi
f_in = open("data/raw/airquality_data.csv","r")
# read in the lines one by one
lines = f_in.readlines()
for line in lines:
# don't work with empty lines
# if len(line.strip()) != 0 :
try:
line = line.replace("\n","")
line = line[27:-3].split("), (")
unformattedDateObject, pm1_cf, pm25_cf, pm10_cf, pm1, pm25, pm10 = line[0], line[1], line[2], line[3], line[4], line[5], line[6]
# remove labels
pm1_cf, pm25_cf, pm10_cf, pm1, pm25, pm10 = pm1_cf[10:], pm25_cf[11:], pm10_cf[11:], pm1[7:], pm25[8:], pm10[8:-1]
# get date back into a datetime object
dateLst = unformattedDateObject[18:-1].split(", ")
year, month, day, hour, minute, second, microsecond = int(dateLst[0]), int(dateLst[1]), int(dateLst[2]), int(dateLst[3]), int(dateLst[4]), int(dateLst[5]), int(dateLst[6])
newDateObject = datetime(year, month, day, hour, minute, second, microsecond)
# don't rewrite existing data, only append new data
if newDateObject < datetime.strptime(prev_file_last_timestamp, '%Y-%m-%d %H:%M:%S.%f'):
continue
row = [newDateObject, pm1_cf, pm25_cf, pm10_cf, pm1, pm25, pm10]
print(row)
#add data to csv
writer.writerow(row)
except IndexError:
continue
if __name__ == "__main__":
# raw_file_in = 'data/raw/airquality_data.csv'
# main()
# get_last_timestamp()
main()
| hfmandell/air-quality-rover-raspi | process_pm_data.py | process_pm_data.py | py | 3,024 | python | en | code | 1 | github-code | 13 |
39792204322 | import numpy as np
import palantir
import pandas as pd
def compactness(ad, low_dim_embedding="X_pca", SEACells_label="SEACell"):
"""Compute compactness of each metacell.
Compactness is defined is the average variance of diffusion components across cells that constitute a metcell.
:param ad: (Anndata) Anndata object
:param low_dim_embedding: (str) `ad.obsm` field for constructing diffusion components
:param SEACell_label: (str) `ad.obs` field for computing diffusion component variances
:return: `pd.DataFrame` with a dataframe of compactness per metacell
"""
import palantir
components = pd.DataFrame(ad.obsm[low_dim_embedding]).set_index(ad.obs_names)
dm_res = palantir.utils.run_diffusion_maps(components)
dc = palantir.utils.determine_multiscale_space(dm_res, n_eigs=10)
return pd.DataFrame(
dc.join(ad.obs[SEACells_label]).groupby(SEACells_label).var().mean(1)
).rename(columns={0: "compactness"})
def separation(
ad, low_dim_embedding="X_pca", nth_nbr=1, cluster=None, SEACells_label="SEACell"
):
"""Compute separation of each metacell.
Separation is defined is the distance to the nearest neighboring metacell.
:param ad: (Anndata) Anndata object
:param low_dim_embedding: (str) `ad.obsm` field for constructing diffusion components
:param nth_nbr: (int) Which neighbor to use for computing separation
:param SEACell_label: (str) `ad.obs` field for computing diffusion component variances
:return: `pd.DataFrame` with a separation of compactness per metacell
"""
components = pd.DataFrame(ad.obsm[low_dim_embedding]).set_index(ad.obs_names)
dm_res = palantir.utils.run_diffusion_maps(components)
dc = palantir.utils.determine_multiscale_space(dm_res, n_eigs=10)
# Compute DC per metacell
metacells_dcs = (
dc.join(ad.obs[SEACells_label], how="inner").groupby(SEACells_label).mean()
)
from sklearn.neighbors import NearestNeighbors
neigh = NearestNeighbors(n_neighbors=nth_nbr)
nbrs = neigh.fit(metacells_dcs)
dists, nbrs = nbrs.kneighbors()
dists = pd.DataFrame(dists).set_index(metacells_dcs.index)
dists.columns += 1
nbr_cells = np.array(metacells_dcs.index)[nbrs]
metacells_nbrs = pd.DataFrame(nbr_cells)
metacells_nbrs.index = metacells_dcs.index
metacells_nbrs.columns += 1
if cluster is not None:
# Get cluster type of neighbors to ensure they match the metacell cluster
clusters = ad.obs.groupby(SEACells_label)[cluster].agg(
lambda x: x.value_counts().index[0]
)
nbr_clusters = pd.DataFrame(clusters.values[nbrs]).set_index(clusters.index)
nbr_clusters.columns = metacells_nbrs.columns
nbr_clusters = nbr_clusters.join(pd.DataFrame(clusters))
clusters_match = nbr_clusters.eq(nbr_clusters[cluster], axis=0)
return pd.DataFrame(dists[nth_nbr][clusters_match[nth_nbr]]).rename(
columns={1: "separation"}
)
else:
return pd.DataFrame(dists[nth_nbr]).rename(columns={1: "separation"})
def get_density(ad, key, nth_neighbor=150):
"""Compute cell density as 1/ the distance to the 150th (by default) nearest neighbour.
:param ad: AnnData object
:param key: (str) key in ad.obsm to use to build diffusion components on.
:param nth_neighbor:
:return: pd.DataFrame containing cell ID and density.
"""
from sklearn.neighbors import NearestNeighbors
neigh = NearestNeighbors(n_neighbors=nth_neighbor)
if "key" in ad.obsm:
print(f"Using {key} to compute cell density")
components = pd.DataFrame(ad.obsm["X_pca"]).set_index(ad.obs_names)
else:
raise ValueError(f"Key {key} not present in ad.obsm.")
diffusion_map_results = palantir.utils.run_diffusion_maps(components)
diffusion_components = palantir.utils.determine_multiscale_space(
diffusion_map_results, n_eigs=8
)
nbrs = neigh.fit(diffusion_components)
cell_density = (
pd.DataFrame(nbrs.kneighbors()[0][:, nth_neighbor - 1])
.set_index(ad.obs_names)
.rename(columns={0: "density"})
)
density = 1 / cell_density
return density
def celltype_frac(x, col_name):
"""TODO."""
val_counts = x[col_name].value_counts()
return val_counts.values[0] / val_counts.values.sum()
def compute_celltype_purity(ad, col_name):
"""Compute the purity (prevalence of most abundant value) of the specified col_name from ad.obs within each metacell.
@param: ad - AnnData object with SEACell assignment and col_name in ad.obs dataframe
@param: col_name - (str) column name within ad.obs representing celltype groupings for each cell.
"""
celltype_fraction = ad.obs.groupby("SEACell").apply(
lambda x: celltype_frac(x, col_name)
)
celltype = ad.obs.groupby("SEACell").apply(
lambda x: x[col_name].value_counts().index[0]
)
return pd.concat([celltype, celltype_fraction], axis=1).rename(
columns={0: col_name, 1: f"{col_name}_purity"}
)
| dpeerlab/SEACells | SEACells/evaluate.py | evaluate.py | py | 5,088 | python | en | code | 115 | github-code | 13 |
21582112323 | """
You've been given a list that states the daily revenue for each day of the week. Unfortunately, the list has been corrupted and contains extraneous characters. Rather than fix the source of the problem, your boss has asked you to create a program that removes any unneccessary characters and return the corrected list.
The expected characters are digits, ' $ ', and ' . ' All items in the returned list are expected to be strings.
For example:
a1 = ['$5.$6.6x.s4', '{$33ae.5(9', '$29..4e9', '%.$9|4d20', 'A$AA$4r R4.94']
remove_char(a1)
>>> ['$56.64', '$33.59', '$29.49', '$94.20', '$44.94']
"""
a1 = ['$5.$6.6x.s4', '{$33ae.5(9', '$29..4e9', '%.$9|4d20', 'A$AA$4r R4.94']
"""
res = list(map(lambda sub: int(''.join(
[ele for ele in sub if ele.isnumeric()])), a1))
print(res1)
"""
a2 = a1.filter(str.isdigit, a1)
print(a2)
| Lucky-Dutch/cov-19 | codewars/changeCharInStrings.py | changeCharInStrings.py | py | 837 | python | en | code | 0 | github-code | 13 |
11250446401 | #!/usr/bin/env python
import os
def getTestFile():
retLine=""
with open("testfile.txt", "r") as f2:
for line2 in f2.readlines():
retLine += line2
return retLine
def printFeatureFile():
print ("\n\n ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ")
with open("feature.txt", "r") as f3r:
for lines in f3r.readlines():
print(lines)
def writeFeatureFile():
print()
testcol = getTestFile()
testcollist = list(testcol.split(" "))
with open("feature.txt", "r") as f3r:
line3 = f3r.readline()
if not line3:
for i in range(len(testcollist)):
#print("testcollist[",i,"]= ", testcollist[i])
with open("feature.txt", "a") as f3a:
f3a.write(testcollist[i])
f3a.write("\n")
else:
f3r.seek(0)
lines3 = f3r.readlines()
open('feature.txt', 'w').close()
#print (lines3)
lines3len = len(lines3)
for i in range(len(lines3)):
lineFinal = ""
lineFinal =(lines3[i].strip() + '{:>10}'.format(testcollist[i].strip()) + "\n")
# if len(lineFinal.strip()) > 2:
# print("lineFinal=",lineFinal)
with open("feature.txt", "a") as f3a:
f3a.write(lineFinal)
print (" ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ")
# main
myfilename="housing.data.txt"
#if os.path.isfile(myfilename):
#print("file exists")
#else:
#print("no file")
open('feature.txt', 'w').close()
with open(myfilename, 'r') as file_handle:
for line in file_handle.readlines():
line_clean = line.replace(' ',' ').replace(' ',' ' )
line_clean =line_clean.strip()
values = line_clean.split(" ")
print()
print (" ", end="")
open('testfile.txt', 'w').close()
for value in values:
if '.' not in value:
print(int(value), end=" ")
else:
print (float(value), end=" ")
with open("testfile.txt", "a") as f2:
f2.write(value)
f2.write(" ")
writeFeatureFile()
printFeatureFile()
# identify what type of data each value is and cast it
# to the appropriate type, then print the new, properly-typed
# list to the screen
# 1', '273.0', '21.00', ==> 1, 273.0, 21.00
| allys-99/class3hw | our_csv_parser_file.py | our_csv_parser_file.py | py | 2,484 | python | en | code | 0 | github-code | 13 |
42076966578 | import collections
import sys
sys.setrecursionlimit(10 ** 8)
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N = int(readline())
A = [int(x) for x in readline().split()]
ac = collections.Counter(A)
assert set(ac.keys()).issubset({1, 2, 3})
def solve(c1, c2, c3):
K = c1 + c2 + c3
L = K + 1
L2 = L ** 2
dp = [0.0] * L ** 3
for i3 in range(c3 + 1):
for i2 in range(c2 + c3 + 1):
for i1 in range(N - i2 - i3 + 1):
isum = i1 + i2 + i3
if isum == 0:
continue
i0 = N - i1 - i2 - i3
if i0 < 0:
continue
e = i0
if i1 > 0:
e += i1 * (1.0 + dp[(i1 - 1) * L2 + i2 * L + i3])
if i2 > 0 and i1 <= K:
e += i2 * (1.0 + dp[(i1 + 1) * L2 + (i2 - 1) * L + i3])
if i3 > 0 and i2 + 1 <= c2 + c3:
e += i3 * (1.0 + dp[i1 * L2 + (i2 + 1) * L + i3 - 1])
dp[i1 * L2 + i2 * L + i3] = e / isum
return dp[c1 * L2 + c2 * L + c3]
if __name__ == "__main__":
print(solve(ac[1], ac[2], ac[3]))
| keijak/comp-pub | atcoder/dp/J/main.py | main.py | py | 1,216 | python | en | code | 0 | github-code | 13 |
27803194532 | def solution(new_id):
answer = ''
# 1단계
temp = str(new_id).lower()
# 2단계
for word in temp:
if word.islower() or word.isnumeric() \
or word == '-' or word == '_' or word == '.':
answer += word
# 3단계
temp = ''
count = 0
for i in answer:
if i == '.':
count += 1
else:
if count >= 1:
temp += '.'
count = 0
temp += i
answer = temp
# 4단계
answer = answer.strip('.')
# 5단계
if len(answer) == 0:
answer += 'a'
# 6단계
if len(answer) >= 16:
answer = answer[0:15]
answer = answer.strip('.')
# 7단계
while len(answer) < 3:
answer += answer[-1]
return answer
# 3단계는 아래와 같이 줄일 수 있다. (연속된 점을 점 하나로)
# while '..' in answer:
# answer = answer.replace('..', '.') | tkdgns8234/DataStructure-Algorithm | Algorithm/프로그래머스/level_1/신규_아이디_추천.py | 신규_아이디_추천.py | py | 945 | python | ko | code | 0 | github-code | 13 |
16464357543 | import sys
import tensorflow as tf
import numpy as np
import six
def DilatedConv_4Mehtods(type, x, k, num_out, factor, name, biased=False):
"""
DilatedConv with 4 method: Basic,Decompose,GI,SSC
Args:
type = Basic,Decompose,GI,SSC
x = input
k = kernal size
num_out output num
factor = dilated factor
Returns:
output layer
"""
if (type == 'Basic'): return DilatedConv_Basic(x, k, num_out, factor, name, biased)
elif (type == 'Decompose'): return DilatedConv_Decompose(x, k, num_out, factor, name, biased)
elif (type == 'GI'): return DilatedConv_GI(x, k, num_out, factor, name, biased)
elif (type == 'SSC'): return DilatedConv_SSC(x, k, num_out, factor, name, biased)
else:
print('type ERROR! Chose a type from: Basic,Decompose,GI,SSC')
# exit
sys.exit(-1)
def DilatedConv_Basic(x, k, num_out, factor, name, biased=False):
num_input = x.shape[3].value
with tf.variable_scope(name) as scope:
weights = tf.get_variable('weights', shape=[k, k, num_input, num_out])
output = tf.nn.atrous_conv2d(x, weights, factor, padding='SAME')
if biased:
bias = tf.get_variable('biases', shape=[num_out])
output = tf.nn.bias_add(output, bias)
return output
def DilatedConv_Decompose(x, k, num_out, factor, name, biased=False):
H = tf.shape(x)[1]
W = tf.shape(x)[2]
pad_bottom = (factor - H % factor) if H % factor != 0 else 0
pad_right = (factor - W % factor) if W % factor != 0 else 0
pad = [[0, pad_bottom], [0, pad_right]]
output = tf.space_to_batch(x, paddings=pad, block_size=factor)
num_input = x.shape[3].value
with tf.variable_scope(name) as scope:
w = tf.get_variable('weights', shape=[k, k, num_input, num_out])
s = [1, 1, 1, 1]
output = tf.nn.conv2d(output, w, s, padding='SAME')
if biased:
bias = tf.get_variable('biases', shape=[num_out])
output = tf.nn.bias_add(output, bias)
output = tf.batch_to_space(output, crops=pad, block_size=factor)
return output
def DilatedConv_GI(x, k, num_out, factor, name, biased=False):
H = tf.shape(x)[1]
W = tf.shape(x)[2]
pad_bottom = (factor - H % factor) if H % factor != 0 else 0
pad_right = (factor - W % factor) if W % factor != 0 else 0
pad = [[0, pad_bottom], [0, pad_right]]
num_input = x.shape[3].value
with tf.variable_scope(name) as scope:
w = tf.get_variable('weights', shape=[k, k, num_input, num_out])
s = [1, 1, 1, 1]
output = tf.nn.conv2d(output, w, s, padding='SAME')
fix_w = tf.Variable(tf.eye(factor*factor), name='fix_w')
l = tf.split(output, factor*factor, axis=0)
os = []
for i in six.moves.range(0, factor*factor):
os.append(fix_w[0, i] * l[i])
for j in six.moves.range(1, factor*factor):
os[i] += fix_w[j, i] * l[j]
output = tf.concat(os, axis=0)
if biased:
bias = tf.get_variable('biases', shape=[num_out])
output = tf.nn.bias_add(output, bias)
output = tf.batch_to_space(output, crops=pad, block_size=factor)
return output
def DilatedConv_SSC(x, k, num_out, factor, name, biased=False):
num_input = x.shape[3].value
fix_w_size = factor * 2 - 1
with tf.variable_scope(name) as scope:
fix_w = tf.get_variable('fix_w',
shape=[fix_w_size, fix_w_size, 1, 1, 1],
initializer=tf.zeros_initializer)
mask = np.zeros([fix_w_size, fix_w_size, 1, 1, 1], dtype=np.float32)
mask[factor - 1, factor - 1, 0, 0, 0] = 1
fix_w = tf.add(fix_w, tf.constant(mask, dtype=tf.float32))
output = tf.expand_dims(x, -1)
output = tf.nn.conv3d(output, fix_w, strides=[1]*5, padding='SAME')
output = tf.squeeze(output, -1)
w = tf.get_variable('weights', shape=[k, k, num_input, num_out])
output = tf.nn.atrous_conv2d(output, w, factor, padding='SAME')
if biased:
bias = tf.get_variable('biases', shape=[num_out])
output = tf.nn.bias_add(output, bias)
return output | qingbol/ClmsDM | models/dilated.py | dilated.py | py | 3,739 | python | en | code | 0 | github-code | 13 |
26330699380 | from sklearn.svm import LinearSVC
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.feature_selection import SelectFromModel
from sklearn.preprocessing import StandardScaler
import pandas as pd
class FeatureSelector:
def __init__(self) -> None:
self.model = None
self.features = None
self.labels = None
def set_features_and_labels(self, features, labels):
self.features = features
self.labels = labels
def logistic_regression(self):
scaler = StandardScaler().fit(self.features)
clf = LogisticRegression().fit(scaler.transform(self.features), self.labels)
return clf
def extra_trees(self):
clf = ExtraTreesClassifier(n_estimators=50).fit(self.features, self.labels)
return clf
def svc(self):
clf = LinearSVC(C=0.01, penalty="l1", dual=False).fit(self.features, self.labels)
return clf
def select_train(self, keyword):
# self.scaler = StandardScaler()
if keyword == 'logistic_regression':
clf = self.logistic_regression()
elif keyword == 'extra_trees':
clf= self.extra_trees()
elif keyword == 'svm':
clf = self.svc()
else:
print(keyword, ' feature selection method does not exist!')
self.model = SelectFromModel(clf, prefit=True)
x_new = self.model.transform(self.features)
return x_new
def select_val(self, features_val):
df = pd.DataFrame(features_val)
return df.iloc[:, self.model.get_support(indices=True)].to_numpy()
def select_data_cross_val(self, features_val, keyword):
x_train = self.select_train(keyword)
if self.model is not None:
x_val = self.select_val(features_val)
return x_train, x_val
# def lasso(x_train, y_train, x_val, x_test=None, n_fold=5, max_iters=50, thr=0.5):
# from sklearn.linear_model import LassoCV
# from sklearn.feature_selection import SelectFromModel
# from sklearn.model_selection import GridSearchCV
# from sklearn.pipeline import Pipeline
# import numpy as np
# # if grid_search:
# # pipeline = Pipeline([
# # ('scaler',StandardScaler()),
# # ('model',Lasso())
# # ])
# # search = GridSearchCV(pipeline,
# # {'model__alpha':np.arange(0.1,10,0.1)},
# # cv = 2, scoring="accuracy",verbose=3
# # )
# # search.fit(features,labels)
# # print(search.best_params_)
# lasso = {}
# cv_lasso = LassoCV(cv = n_fold, max_iter = max_iters, n_jobs = 1)
# cv_lasso_model = SelectFromModel(cv_lasso, threshold = thr)
# cv_lasso_model.fit(x_train, y_train)
# #n_remained_lasso = cv_lasso_model.transform(x_train).shape[1]
# remained_lasso_idx = cv_lasso_model.get_support(indices = True)
# x_train_lasso = x_train[:,remained_lasso_idx]
# x_val_lasso = x_val[:,remained_lasso_idx]
# lasso['train'] = x_train_lasso
# lasso['val'] = x_val_lasso
# # if x_test is not None:
# # x_test_lasso = x_test[:,remained_lasso_idx]
# # lasso['test'] = x_test_lasso
# lasso['feature_indices'] = remained_lasso_idx.tolist()
# return lasso | smriti-joshi/Fairness_training | feature_selector.py | feature_selector.py | py | 3,380 | python | en | code | 0 | github-code | 13 |
46089037124 | from cortex2 import EmotivCortex2Client
import time
url = "wss://localhost:6868"
# Remember to start the Emotiv App before you start!
# Start client with authentication
client = EmotivCortex2Client(url,
client_id='0DyMfKwKuYAG72VKATaJUI51sEHlyGqpsTk19jPP',
client_secret="Nv8JIEu7ew4zsdSbj1xha2vePzAr71JfYNi55oQDvnIOit4wSwctBIAha3XzLs4EbWR9R0ruo1gqUcUJ72UfKFnetgykJfkIfdW3OqqhZ4QcvUvIBmuZOiMBfJrGxk1F",
check_response=True,
authenticate=True,
debug=False)
# Test API connection by using the request access method
client.request_access()
# Explicit call to Authenticate (approve and get Cortex Token)
client.authenticate()
# Connect to headset, connect to the first one found, and start a session for it
client.query_headsets()
client.connect_headset(0)
client.create_session(0)
# Subscribe to the motion and mental command streams
# Spins up a separate subscription thread
client.subscribe(streams=["mot", "com"])
# Test message handling speed
a = client.subscriber_messages_handled
time.sleep(5)
b = client.subscriber_messages_handled
print("bruh", (b - a) / 5)
# Grab a single instance of data
print("data", client.receive_data())
counter = 0
# Continously grab data, while making requests periodically
while True:
counter += 1
# time.sleep(0.1)
if counter % 5000 == 0:
print(client.request_access())
# Try stopping the subscriber thread
if counter == 50000:
client.stop_subscriber()
break
try:
# Check the latest data point from the motion stream, from the first session
print(list(client.data_streams.values())[0]['mot'][0])
except:
pass
| GenerelSchwerz/big-brain-eeg | main.py | main.py | py | 1,771 | python | en | code | 0 | github-code | 13 |
21538308278 | # Native imports
from os.path import exists, join
from shutil import rmtree
from typing import Union
# Local imports
from .utils import _join_paths_mkdir
from ..Args import args
from ..Section import Section
from .nav import generate_nav_as_needed # Import for export
"""Functions to assist in writing docs to disk"""
def clear_docs():
"""Removes previously generated docs"""
if exists(args.docs_basedir):
rmtree(args.docs_basedir)
def _make_and_get_repodir(repo_name):
"""Create a directory for the repository in the docs basedir"""
return _join_paths_mkdir(args.docs_basedir, repo_name)
def _make_and_get_sectiondir(repo_name, section: Union[str,Section]):
"""Create a directory for the section in the repository's folder"""
if isinstance(section, Section):
section = section.name
return _join_paths_mkdir(_make_and_get_repodir(repo_name), section)
def write_to_docs(repo_name: str, section_id: str, content: str, filename="README.md", replaceContent=False, prepend=False) -> str:
"""Add CONTENT to the generated documentation. Optionally creates the needed directories, replaces contents..."""
section_dirname = args.get_configured_section_name(section_id)
dir = _make_and_get_sectiondir(repo_name, section_dirname)
full_filename = join(dir, filename)
mode = "a+" if (not replaceContent) and (not prepend) else "w"
if prepend:
with open(full_filename, "r", encoding="UTF-8") as file:
original_data = file.read(content)
with open(full_filename, mode, encoding="UTF-8") as file:
file.write(content)
if prepend:
file.write(original_data)
# Return without
return full_filename
| Denperidge-Redpencil/divio-docs-gen | src/divio_docs_gen/write_to_disk/__init__.py | __init__.py | py | 1,732 | python | en | code | 0 | github-code | 13 |
18994415623 | import disnake
from disnake.ext import commands
from utils import database, autocompletes, checks
class DeleteSession(commands.Cog):
def __init__(self, bot: disnake.ext.commands.Bot):
self.bot = bot
@commands.slash_command(
guild_only=True,
name="удалить-сессию",
description="Удалить одну из существующих сессий",
)
async def delete_session(
self,
inter: disnake.ApplicationCommandInteraction,
session: str = commands.param(
autocomplete=autocompletes.sessions_autocompleter,
name="сессия",
description="Сессия которую вы хотите удалить",
),
):
if not await checks.is_admin(inter=inter):
return await inter.response.send_message(
embed=disnake.Embed(
title="ОШИБКА",
description="Вы должны быть администратором для использования данной команды!",
color=disnake.Color.red(),
),
ephemeral=True,
)
sessions_list = await database.get_sessions_list()
if not sessions_list or (sessions_list and session not in sessions_list):
return await inter.response.send_message(
embed=disnake.Embed(
title="ОШИБКА",
description="Указанного вами названия нету в списке сессий!",
color=disnake.Color.red(),
),
ephemeral=True,
)
value = await database.delete_session(session)
embed = disnake.Embed(
title="УСПЕХ",
description="Указанная вами сессия успешно удалена!",
color=disnake.Color.green(),
)
if value:
embed.add_field(
name="ВАЖНО",
value="```Указанная вами сессия использовалась как активная, вам нужно создать новую сессию для продолжения работы!```",
)
await inter.response.send_message(embed=embed, ephemeral=True)
def setup(bot: commands.Bot):
bot.add_cog(DeleteSession(bot))
print(f">{__name__} is launched")
| Komo4ekoI/DiscordCasinoBot | cogs/commands/delete_session.py | delete_session.py | py | 2,474 | python | ru | code | 0 | github-code | 13 |
40380735972 | import re
import numpy as np
def cut_sent(para):
para = re.sub('([。!?\?])([^”’])', r"\1\n\2", para) # 单字符断句符
para = re.sub('(\.{6})([^”’])', r"\1\n\2", para) # 英文省略号
para = re.sub('(\…{2})([^”’])', r"\1\n\2", para) # 中文省略号
para = re.sub('([。!?\?][”’])([^,。!?\?])', r'\1\n\2', para)
# 如果双引号前有终止符,那么双引号才是句子的终点,把分句符\n放到双引号后,注意前面的几句都小心保留了双引号
para = para.rstrip() # 段尾如果有多余的\n就去掉它
# 很多规则中会考虑分号;,但是这里我把它忽略不计,破折号、英文双引号等同样忽略,需要的再做些简单调整即可。
return para.split("\n")
with open("zhilingsys.txt", "r") as f:
para = f.read()
result = cut_sent(para)
print(result)
# res = np.array(result)
# np.save('document.npy', result) | twobagoforange/saier_system | background/split.py | split.py | py | 962 | python | ja | code | 0 | github-code | 13 |
7044548017 | from client_payment_sdk import ClientPaymentSDK, sign
api_secret = 'aa21444f3f71'
params = {
'merchant_id': 15,
'order': '067dbec6-719c-11ec-9e37-0242ac130196'
}
params['signature'] = sign('/withdrawal_request', 'GET', params, api_secret)
client = ClientPaymentSDK()
result = client.withdrawal_status(params)
print(f'status: {result.status}, withdrawal_request: {result.withdrawal_request}')
| spacearound404/client-payment-sdk-python | examples/withdrawal_status.py | withdrawal_status.py | py | 405 | python | en | code | 0 | github-code | 13 |
20868595013 | from functools import partial
import fire
import pandas as pd
from catboost import CatBoostRegressor
from hyperopt import hp, fmin, tpe
from lightgbm import LGBMRegressor
from loguru import logger
from sklearn.pipeline import Pipeline
from vecstack import StackingTransformer
from xgboost import XGBRegressor
from utils import mean_absolute_percentage_error, WeightedRegressor, preprocess
df_train = pd.read_csv('train.csv', parse_dates=['OrderedDate'])
df_train = df_train.sample(200000, random_state=1337)
df_val = pd.read_csv('validation.csv', parse_dates=['OrderedDate'])
X_train = preprocess(df_train)
y_train = df_train['RTA']
X_val = preprocess(df_val)
y_val = df_val['RTA']
def objective(params, keker):
params['max_depth'] = int(params['max_depth'])
params['n_estimators'] = int(params['n_estimators'])
if keker is LGBMRegressor:
params['num_leaves'] = 2 ** params['max_depth']
reg = keker(**params)
estimators = [
('reg', reg),
]
final_estimator = WeightedRegressor()
stack = StackingTransformer(estimators=estimators, variant='A', regression=True, n_folds=3, shuffle=False,
random_state=None)
steps = [('stack', stack),
('final_estimator', final_estimator)]
pipe = Pipeline(steps)
pipe.fit(X_train, y_train)
y_pred = pipe.predict(X_val)
score = mean_absolute_percentage_error(y_val, y_pred)
logger.info(f'MAPE on valid: {score}, params: {params}')
return score
xgb_space = {
'max_depth': hp.quniform('max_depth', 2, 16, 1),
'colsample_bytree': hp.uniform('colsample_bytree', 0.3, 1.0),
'subsample': hp.uniform('subsample', 0.3, 1.0),
'learning_rate': hp.uniform('learning_rate', 0.01, 0.3),
'gamma': hp.uniform('gamma', 0.0, 1),
'seed': hp.choice('seed', [1337]),
'objective': hp.choice('objective', ['reg:tweedie']),
'n_estimators': hp.quniform('n_estimators', 60, 300, 10),
'reg_alpha': hp.uniform('reg_alpha', 0.01, 0.3),
'min_child_weight': hp.uniform('min_child_weight', 0.2, 4),
}
lgb_space = {
'max_depth': hp.quniform('max_depth', 2, 16, 1),
'colsample_bytree': hp.uniform('colsample_bytree', 0.3, 1.0),
'subsample': hp.uniform('subsample', 0.3, 1.0),
'learning_rate': hp.uniform('learning_rate', 0.01, 0.3),
'seed': hp.choice('seed', [1337]),
'objective': hp.choice('objective', ['mae']),
'n_estimators': hp.quniform('n_estimators', 60, 300, 10),
'reg_alpha': hp.uniform('reg_alpha', 0.01, 0.3),
'min_child_weight': hp.uniform('min_child_weight', 0.2, 4),
}
cat_space = {
'max_depth': hp.quniform('max_depth', 2, 16, 1),
'subsample': hp.uniform('subsample', 0.3, 1.0),
'learning_rate': hp.uniform('learning_rate', 0.01, 0.3),
'random_state': hp.choice('random_state', [1337]),
'objective': hp.choice('objective', ['MAE']),
'silent': hp.choice('silent', [True]),
'n_estimators': hp.quniform('n_estimators', 60, 300, 10),
'random_strength': hp.uniform('random_strength', 0.00001, 0.1),
'l2_leaf_reg': hp.uniform('l2_leaf_reg', 0.1, 10),
}
xgb_objective = partial(objective, keker=XGBRegressor)
lgb_objective = partial(objective, keker=LGBMRegressor)
cat_objective = partial(objective, keker=CatBoostRegressor)
def main(regressor, max_evals=100):
if regressor not in ['cat', 'xgb', 'lgb']:
raise Exception('undefined regressor')
best = None
logger.info(f'start optimizing {regressor}')
if regressor == 'xgb':
best = fmin(fn=xgb_objective,
space=xgb_space,
algo=tpe.suggest,
max_evals=max_evals)
if regressor == 'lgb':
best = fmin(fn=lgb_objective,
space=lgb_space,
algo=tpe.suggest,
max_evals=max_evals)
if regressor == 'cat':
best = fmin(fn=cat_objective,
space=cat_space,
algo=tpe.suggest,
max_evals=max_evals)
logger.info(best)
if __name__ == '__main__':
fire.Fire(main)
| georgiypetrov/citymobil-natural-log | hyperparam_tuning.py | hyperparam_tuning.py | py | 4,096 | python | en | code | 0 | github-code | 13 |
73492625616 | # Solve the Sudoku
def isValid(i,j,val,sudoku):
row=(i//3)*3
col=(j//3)*3
for k in range(9):
if sudoku[k][j]==val:
return False
for k in range(9):
if sudoku[i][k]==val:
return False
for r in range(3):
for c in range(3):
if sudoku[r+row][c+col]==val:
return False
return True
def Sudoku(row,col,sudoku):
if row==9:
return True
i=row
j=col+1
if col==8:
i=row+1
j=0
if sudoku[row][col]!=0:
return Sudoku(i,j,sudoku)
else:
for k in range(1,10):
if isValid(row,col,k,sudoku):
sudoku[row][col]=k
flag=Sudoku(i,j,sudoku)
if flag==True:
return True
sudoku[row][col]=0
def main():
sudoku=[]
for i in range(9):
sudoku.append(list(map(int,input().split())))
ans=Sudoku(0,0,sudoku)
if ans==True:
for i in range(9):
for j in range(9):
print(sudoku[i][j],end=" ")
print()
if __name__=='__main__':
main() | Ayush-Tiwari1/DSA | Days.43/3.Solve-Sudoku.py | 3.Solve-Sudoku.py | py | 1,153 | python | en | code | 0 | github-code | 13 |
404586901 | import os
import json
from shutil import move
categorie = [] # Here all the categories will be saved.
# Check every recipe in the 'ricette' folder for its category then if it's not already in the list: save it.
for path in os.scandir('ricette'):
if path.is_file():
with open(path.path, 'r') as file:
try:
data = json.load(file)
except:
print(path.path)
continue
if data['categoria'] not in categorie:
categorie.append(data['categoria'])
# Create a subfolder for every category.
for categoria in categorie:
if not os.path.exists(f'ricette/{categoria}'):
os.mkdir(f'ricette/{categoria}')
# Move every recipe in the right subfolder. If a recipe does not have a category the it will not be moved.
for ricetta in os.scandir('ricette'):
if ricetta.is_file():
with open(ricetta.path) as file_ricetta:
data_ricetta = json.load(file_ricetta)
categoria_ricetta = data_ricetta['categoria']
try:
move(ricetta.path, f'ricette/{categoria_ricetta}')
except:
print(
f'Could not move {ricetta.path} in ricette/{categoria_ricetta}')
continue
| TheCaptainCraken/Scraping-Giallo-Zaffferano | find_categories.py | find_categories.py | py | 1,253 | python | en | code | 0 | github-code | 13 |
21051068575 | # 197, 부품찾기
# 내 답, 이진 탐색 이용
def binary_search(arr, target, start, end):
if start > end:
return None
mid = (start + end)//2
if arr[mid] == target:
return mid
elif arr[mid] > target:
return binary_search(arr, target, start, mid - 1)
else:
return binary_search(arr, target, mid + 1, end)
n = int(input())
N = list(map(int, input().split()))
m = int(input())
M = list(map(int, input().split()))
N.sort()
for i in M:
if binary_search(N, i, 0, n-1) == None:
print('no', end=' ')
else:
print('yes', end=' ')
'''
# 모범 답안 중 계수 정렬 이용한 답
n = int(input())
array = [0] * 1000001
for i in input().split():
array[int(i)] += 1
m = int(input())
x = list(map(int, input().split()))
for i in x:
if array[i] == 1:
print('yes', end=' ')
else:
print('no', end=' ')
'''
'''
#모범 답안 중 집합 자료형 이용, 특정 데이터의 존재 판단 시 가장 효율적
n = int(input())
array = set(map(int, input().split())) # set 함수를 이용한 집합 초기화
m = int(input())
x= list(map(int, input().split()))
for i in x:
if i in array: print('yes', end=' ')
else: print('no', end=' ')
'''
| jinho9610/py_algo | book/bs_1.py | bs_1.py | py | 1,257 | python | ko | code | 0 | github-code | 13 |
17783409993 | import numpy as np
def day08(inp):
board = np.array([[int(c) for c in line] for line in inp.strip().splitlines()])
visibles = np.zeros_like(board, dtype=bool)
for axis in range(2):
# check rows or columns
for i in range(board.shape[axis]):
# check each row or each column
for sl in slice(None), slice(None, None, -1):
# check forward and backward
subhighest = -1
for j in range(board.shape[1 - axis])[sl]:
index = (i, j) if axis == 0 else (j, i)
if board[index] > subhighest:
visibles[index] = True
subhighest = board[index]
part1 = visibles.sum()
return part1
def day08b(inp):
board = np.array([[int(c) for c in line] for line in inp.strip().splitlines()])
highest_scenic = 0
for i0, j0 in np.indices(board.shape).reshape(2, -1).T:
scenic_score = 1
for delta in np.array([[0, 1], [0, -1], [1, 0], [-1, 0]]):
i, j = i0, j0
viewing_distance = 0
subhighest = -1
while True:
i, j = (i, j) + delta
if not (0 <= i < board.shape[0] and 0 <= j < board.shape[1]):
break
viewing_distance += 1
if board[i, j] >= board[i0, j0]:
# this is the edge
break
scenic_score *= viewing_distance
highest_scenic = max(highest_scenic, scenic_score)
part2 = highest_scenic
return part2
if __name__ == "__main__":
testinp = open('day08.testinp').read()
print(day08(testinp))
print(day08b(testinp))
inp = open('day08.inp').read()
print(day08(inp))
print(day08b(inp))
| adeak/AoC2022 | day08.py | day08.py | py | 1,798 | python | en | code | 2 | github-code | 13 |
38462273809 | """Test PyDynamic.uncertainty.propagate_convolve"""
from typing import Callable, Optional, Set, Tuple
import numpy as np
import pytest
import scipy.ndimage as sn
from hypothesis import assume, given, settings, strategies as hst
from hypothesis.strategies import composite
from numpy.testing import assert_allclose
from PyDynamic.uncertainty.propagate_convolution import convolve_unc
from .conftest import (
hypothesis_covariance_matrix,
hypothesis_covariance_matrix_with_zero_correlation,
hypothesis_dimension,
hypothesis_float_vector,
)
@composite
def x_and_Ux(
draw: Callable, reduced_set: bool = False
) -> Tuple[np.ndarray, np.ndarray]:
dim = draw(hypothesis_dimension(min_value=4, max_value=6))
x = draw(hypothesis_float_vector(length=dim, min_value=-10, max_value=10))
if reduced_set:
ux_strategies = hypothesis_covariance_matrix(number_of_rows=dim, max_value=1e-3)
else:
ux_strategies = hst.one_of(
(
hypothesis_covariance_matrix(number_of_rows=dim),
hypothesis_covariance_matrix_with_zero_correlation(number_of_rows=dim),
hypothesis_float_vector(length=dim, min_value=0.0, max_value=10),
hst.just(None),
)
)
ux = draw(ux_strategies)
return x, ux
scipy_modes = ("nearest", "reflect", "mirror")
numpy_modes = ("full", "valid", "same")
@composite
def valid_modes(draw, restrict_kind_to: Optional[str] = None) -> Set[str]:
if restrict_kind_to == "scipy":
return draw(hst.sampled_from(scipy_modes))
elif restrict_kind_to == "numpy":
return draw(hst.sampled_from(numpy_modes))
else:
return draw(hst.sampled_from(numpy_modes + scipy_modes))
@given(x_and_Ux(), x_and_Ux(), valid_modes())
@pytest.mark.slow
def test_convolution(input_1, input_2, mode):
# calculate the convolution of x1 and x2
y, Uy = convolve_unc(*input_1, *input_2, mode)
if mode in numpy_modes:
y_ref = np.convolve(input_1[0], input_2[0], mode=mode)
else: # mode in valid_modes("scipy"):
y_ref = sn.convolve1d(input_1[0], input_2[0], mode=mode)
# compare results
assert len(y) == len(Uy)
assert len(y) == len(y_ref)
assert_allclose(y + 1, y_ref + 1, rtol=2.1e-7)
@given(x_and_Ux(reduced_set=True), x_and_Ux(reduced_set=True))
@pytest.mark.slow
def test_convolution_common_call(input_1, input_2):
# check common execution of convolve_unc
assert convolve_unc(*input_1, *input_2)
@given(x_and_Ux(reduced_set=True), x_and_Ux(reduced_set=True), valid_modes())
@pytest.mark.slow
@settings(deadline=None)
def test_convolution_monte_carlo(input_1, input_2, mode):
y, Uy = convolve_unc(*input_1, *input_2, mode)
n_runs = 40000
XX1 = np.random.multivariate_normal(*input_1, size=n_runs)
XX2 = np.random.multivariate_normal(*input_2, size=n_runs)
if mode in numpy_modes:
convolve = np.convolve
else: # mode in scipy_modes:
convolve = sn.convolve1d
mc_results = [convolve(x1, x2, mode=mode) for x1, x2 in zip(XX1, XX2)]
y_mc = np.mean(mc_results, axis=0)
Uy_mc = np.cov(mc_results, rowvar=False)
# HACK: for visualization during debugging
# import matplotlib.pyplot as plt
# fig, ax = plt.subplots(nrows=1, ncols=4)
# _min = min(Uy.min(), Uy_mc.min())
# _max = max(Uy.max(), Uy_mc.max())
# ax[0].plot(y, label="fir")
# ax[0].plot(y_mc, label="mc")
# ax[0].set_title("mode: {0}, x1: {1}, x2: {2}".format(mode, len(x1), len(x2)))
# ax[0].legend()
# ax[1].imshow(Uy, vmin=_min, vmax=_max)
# ax[1].set_title("PyDynamic")
# ax[2].imshow(Uy_mc, vmin=_min, vmax=_max)
# ax[2].set_title("numpy MC")
# img = ax[3].imshow(np.log(np.abs(Uy-Uy_mc)))
# ax[3].set_title("log(abs(diff))")
# fig.colorbar(img, ax=ax[3])
# plt.show()
# /HACK
assert_allclose(y, y_mc, rtol=1e-1, atol=1e-1)
assert_allclose(Uy, Uy_mc, rtol=1e-1, atol=1e-1)
@given(x_and_Ux(reduced_set=True), x_and_Ux(reduced_set=True), hst.text())
@pytest.mark.slow
def test_convolution_invalid_mode(input_1, input_2, mode):
assume(mode not in numpy_modes and mode not in scipy_modes)
with pytest.raises(ValueError):
convolve_unc(*input_1, *input_2, mode)
| Met4FoF/Code | PyDynamic/test/test_propagate_convolution.py | test_propagate_convolution.py | py | 4,280 | python | en | code | 0 | github-code | 13 |
17051990924 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.AudioEvent import AudioEvent
class FenceEvent(object):
def __init__(self):
self._audio_events = None
self._fence_code = None
self._latitude = None
self._longitude = None
self._multi_audio_interval = None
self._radius = None
@property
def audio_events(self):
return self._audio_events
@audio_events.setter
def audio_events(self, value):
if isinstance(value, list):
self._audio_events = list()
for i in value:
if isinstance(i, AudioEvent):
self._audio_events.append(i)
else:
self._audio_events.append(AudioEvent.from_alipay_dict(i))
@property
def fence_code(self):
return self._fence_code
@fence_code.setter
def fence_code(self, value):
self._fence_code = value
@property
def latitude(self):
return self._latitude
@latitude.setter
def latitude(self, value):
self._latitude = value
@property
def longitude(self):
return self._longitude
@longitude.setter
def longitude(self, value):
self._longitude = value
@property
def multi_audio_interval(self):
return self._multi_audio_interval
@multi_audio_interval.setter
def multi_audio_interval(self, value):
self._multi_audio_interval = value
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
self._radius = value
def to_alipay_dict(self):
params = dict()
if self.audio_events:
if isinstance(self.audio_events, list):
for i in range(0, len(self.audio_events)):
element = self.audio_events[i]
if hasattr(element, 'to_alipay_dict'):
self.audio_events[i] = element.to_alipay_dict()
if hasattr(self.audio_events, 'to_alipay_dict'):
params['audio_events'] = self.audio_events.to_alipay_dict()
else:
params['audio_events'] = self.audio_events
if self.fence_code:
if hasattr(self.fence_code, 'to_alipay_dict'):
params['fence_code'] = self.fence_code.to_alipay_dict()
else:
params['fence_code'] = self.fence_code
if self.latitude:
if hasattr(self.latitude, 'to_alipay_dict'):
params['latitude'] = self.latitude.to_alipay_dict()
else:
params['latitude'] = self.latitude
if self.longitude:
if hasattr(self.longitude, 'to_alipay_dict'):
params['longitude'] = self.longitude.to_alipay_dict()
else:
params['longitude'] = self.longitude
if self.multi_audio_interval:
if hasattr(self.multi_audio_interval, 'to_alipay_dict'):
params['multi_audio_interval'] = self.multi_audio_interval.to_alipay_dict()
else:
params['multi_audio_interval'] = self.multi_audio_interval
if self.radius:
if hasattr(self.radius, 'to_alipay_dict'):
params['radius'] = self.radius.to_alipay_dict()
else:
params['radius'] = self.radius
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = FenceEvent()
if 'audio_events' in d:
o.audio_events = d['audio_events']
if 'fence_code' in d:
o.fence_code = d['fence_code']
if 'latitude' in d:
o.latitude = d['latitude']
if 'longitude' in d:
o.longitude = d['longitude']
if 'multi_audio_interval' in d:
o.multi_audio_interval = d['multi_audio_interval']
if 'radius' in d:
o.radius = d['radius']
return o
| alipay/alipay-sdk-python-all | alipay/aop/api/domain/FenceEvent.py | FenceEvent.py | py | 4,060 | python | en | code | 241 | github-code | 13 |
21871588414 | import time
import numpy as np
import matplotlib.pyplot as plt
import imageio
import os
from os import read
import pathlib
def loadData(dir):
files = os.listdir(dir)
print(files)
colors = []
for i in range (len(files)):
colors.append(imageio.imread(dir + files[i]))
return colors
def cutpic(picture, dots):
picture = picture[dots[0]:dots[1], dots[2]:dots[3], :]
return picture
def polynom(stripes, dots, degree):
mercury = [576.96, 546.074, 435.83]
polyK = np.polyfit(stripes, mercury, degree) # коэф-ы полинома
polynom = np.poly1d(polyK) # полином
print(polynom)
yvals = np.polyval(polynom, stripes)
mercurySpectr = np.polyval(polynom, np.linspace(1, dots[1] - dots[0], dots[1] - dots[0])) # Ox for all plots in wavelengths
data = [yvals, mercurySpectr]
return data
def intensities(colors, dots):
intensities = []
for i in range (len(colors)):
intensity = []
for y in range (dots[1]-dots[0]):
oneStripeIntence = 0
for x in range (dots[3]-dots[2]):
if sum(colors[i][y, x, :]) > 0:
oneStripeIntence += sum(colors[i][y, x, :])
oneStripeIntence = int( oneStripeIntence/(3*(dots[3]-dots[2]) ))
intensity.append(oneStripeIntence)
intensities.append(intensity)
return intensities
def albedoes(intensities, num):
albedoes = []
for i in range (len(intensities)):
albedo = []
for k in range (len(intensities[i])):
albedo.append(intensities[i][k]/intensities[num][k])
albedoes.append(albedo)
return albedoes
def polynomPlot(xScatter, stripes, degree, dir):
mercury = [576.96, 546.074, 435.83]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.grid(color = 'gray', linestyle = ':')
ax.set(title = 'Зависимость длины волны от номера пикселя (по высоте)', xlabel = 'Номер пикселя', ylabel = 'Длина волны, нм', label = '')
ax.scatter(stripes, mercury, label = 'Точки соответствия номеров пикселей длинам волн')
ax.plot(stripes, xScatter, label = 'Подобранный полином {} степени'.format(degree))
ax.legend(loc=1, bbox_to_anchor=(1, 0.15), prop={'size': 9})
fig.savefig(dir + 'polynom.png')
plt.show()
def intensitiesPlot(intensities, wavelength, dir):
dir1 = 'C:/Users/User/Desktop/Repositories/get/12-spectr/DATA/spectr_photos/'
rainbow = os.listdir(dir1)
for i in range(len(rainbow)):
rainbow[i] = rainbow[i][:-4]
print(rainbow)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.grid(color = 'gray', linestyle = ':')
ax.set(title = '', xlabel = 'Длина волны, нм', ylabel = 'Интенсивность')
for i in range(len(intensities)):
ax.plot(wavelength, intensities[i], label = rainbow[i], color = rainbow[i])
ax.legend()
plt.show()
fig.savefig(dir + 'intensitiesPlot.png')
def albedoesPlot(albedoes, wavelength, dir):
dir1 = 'C:/Users/User/Desktop/Repositories/get/12-spectr/DATA/spectr_photos/'
rainbow = os.listdir(dir1)
for i in range(len(rainbow)):
rainbow[i] = rainbow[i][:-4]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.grid(color = 'gray', linestyle = ':')
ax.set(title = 'График зависимости альбедо от длины волны', xlabel = 'Длина волны, нм', ylabel = 'Истиное альбедо')
for i in range(len(albedoes)):
ax.plot(wavelength, albedoes[i], label = rainbow[i], color = rainbow[i])
ax.legend()
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
ax1.grid(color = 'gray', linestyle = ':')
ax1.set(title = 'График зависимости альбедо от длины волны', xlabel = 'Длина волны, нм', ylabel = 'Истиное альбедо')
ax1.plot(wavelength, albedoes[i], label = rainbow[i], color = rainbow[i])
ax1.legend()
fig1.savefig(dir + 'albedoPlot{}.png'.format(rainbow[i]))
plt.show()
fig.savefig(dir + 'albedoPlot.png') | mershavka/get | 12-spectr/spectrFunctions.py | spectrFunctions.py | py | 4,373 | python | en | code | 0 | github-code | 13 |
27222278170 | from django.core import mail
from django.test import TestCase
from django.shortcuts import resolve_url as r
class SubscribeMailBody(TestCase):
def setUp(self):
"""Tests initialize"""
data = dict(
name="Fabricio Nogueira",
cpf="01234567891",
email="nogsantos@mail.com",
phone="62 9 9116-1686",
)
self.client.post(r('subscriptions:new'), data)
# O object autbox guarda uma lista dos emails enviados
self.email = mail.outbox[0]
def test_subscription_email_subject(self):
expect = 'Subscription confirmed'
self.assertEqual(expect, self.email.subject)
def test_subscription_email_from(self):
expect = 'contato@eventex.com.br'
self.assertEqual(expect, self.email.from_email)
def test_subscription_email_to(self):
expect = ['contato@eventex.com.br', 'nogsantos@mail.com']
self.assertEqual(expect, self.email.to)
def test_subscription_email_body(self):
contents = [
'Fabricio Nogueira',
'01234567891',
'nogsantos@mail.com',
'62 9 9116-1686',
]
# Using Subtest
with self.subTest():
for content in contents:
self.assertIn(content, self.email.body)
| nogsantos/eventex | eventex/subscriptions/tests/test_mail_subscribe.py | test_mail_subscribe.py | py | 1,317 | python | en | code | 0 | github-code | 13 |
17114748624 | import logging
from os import path
from agr_literature_service.api.models import CrossReferenceModel, ReferenceModel, \
AuthorModel, ModModel, ModCorpusAssociationModel, MeshDetailModel, \
ReferenceCommentAndCorrectionModel, ReferenceModReferencetypeAssociationModel
from agr_literature_service.lit_processing.utils.db_read_utils import \
get_references_by_curies, get_pmid_to_reference_id
from agr_literature_service.lit_processing.data_ingest.utils.db_write_utils import \
add_cross_references, update_authors, update_mod_corpus_associations, \
update_mod_reference_types, add_mca_to_existing_references, \
update_comment_corrections, update_mesh_terms, update_cross_reference, \
mark_false_positive_papers_as_out_of_corpus, mark_not_in_mod_papers_as_out_of_corpus
from ....fixtures import db, load_sanitized_references, populate_test_mod_reference_types # noqa
logging.basicConfig(format='%(message)s')
logger = logging.getLogger()
logger.setLevel(logging.INFO)
class TestDbReadUtils:
def test_dqm_update_functions(self, db, load_sanitized_references, populate_test_mod_reference_types): # noqa
refs = db.query(ReferenceModel).order_by(ReferenceModel.curie).all()
ref_curie_list = [refs[0].curie, refs[1].curie]
cross_references_to_add = [{'reference_curie': refs[0].curie,
'curie': 'ISBN:88888',
'pages': {}},
{'reference_curie': refs[1].curie,
'curie': 'ISBN:66666',
'pages': {}}]
reference_id = refs[0].reference_id
reference_id2 = refs[1].reference_id
## test add_cross_references() function
add_cross_references(cross_references_to_add, ref_curie_list, logger)
db.commit()
for x in db.query(CrossReferenceModel).filter(CrossReferenceModel.curie.like('NLM:%')).all():
if x.reference == reference_id:
assert x.curie == 'ISBN:88888'
elif x.reference == reference_id2:
assert x.curie == 'ISBN:66666'
## test update_authors()
db_entries = get_references_by_curies(db, [refs[0].curie, refs[1].curie])
db_entry = db_entries[refs[0].curie]
author_list_in_json = [
{
"authorRank": 1,
"firstname": "Hello",
"lastname": "World",
"name": "Hello World"},
{
"authorRank": 2,
"firstname": "Hello",
"lastname": "There",
"name": "Hello There"
}
]
update_authors(db, reference_id, db_entry.get('author', []), author_list_in_json,
logger)
db.commit()
for x in db.query(AuthorModel).filter_by(reference_id=reference_id).all():
if x.order == 1:
assert x.name == 'Hello World'
assert x.last_name == 'World'
elif x.order == 2:
assert x.name == 'Hello There'
assert x.last_name == 'There'
mod_to_mod_id = dict([(x.abbreviation, x.mod_id) for x in db.query(ModModel).all()])
## test update_mod_corpus_associations()
mod_corpus_associations = [
{
"corpus": False,
"mod_abbreviation": "SGD",
"mod_corpus_sort_source": "dqm_files"
}
]
update_mod_corpus_associations(db, mod_to_mod_id, reference_id,
db_entry.get('mod_corpus_association', []),
mod_corpus_associations, logger)
db.commit()
mca = db.query(ModCorpusAssociationModel).filter_by(reference_id=reference_id, corpus=False).first()
for mod in mod_to_mod_id:
if mod_to_mod_id[mod] == mca.mod_id:
assert mod == 'SGD'
## test update_mod_reference_types()
mrt_rows = db.query(ReferenceModReferencetypeAssociationModel).filter_by(reference_id=reference_id).all()
assert len(mrt_rows) == 1
mod_reference_types = [
{
"referenceType": "Journal",
"source": "SGD"
}
]
update_mod_reference_types(db, reference_id,
db_entry.get('mod_referencetypes', []),
mod_reference_types, {'Journal'}, logger)
db.commit()
mrt_rows = db.query(ReferenceModReferencetypeAssociationModel).filter_by(reference_id=reference_id).order_by(
ReferenceModReferencetypeAssociationModel.reference_mod_referencetype_id).all()
assert len(mrt_rows) == 2
assert mrt_rows[0].mod_referencetype.mod.abbreviation == 'ZFIN'
assert mrt_rows[1].mod_referencetype.mod.abbreviation == 'SGD'
## test mark_not_in_mod_papers_as_out_of_corpus()
mod_corpus_associations = [
{
"corpus": True,
"mod_abbreviation": "ZFIN",
"mod_corpus_sort_source": "dqm_files"
}
]
update_mod_corpus_associations(db, mod_to_mod_id, reference_id,
db_entry.get('mod_corpus_association', []),
mod_corpus_associations, logger)
db.commit()
cr = db.query(CrossReferenceModel).filter_by(
reference_id=reference_id, curie_prefix='ZFIN', is_obsolete=False).one_or_none()
mod_xref_id = cr.curie
missing_papers_in_mod = [(mod_xref_id, 'test_AGR_ID', None)]
mark_not_in_mod_papers_as_out_of_corpus('ZFIN', missing_papers_in_mod)
mod_id = mod_to_mod_id['ZFIN']
mca = db.query(ModCorpusAssociationModel).filter_by(
reference_id=reference_id, mod_id=mod_id).one_or_none()
assert mca.corpus is False
def test_pubmed_search_update_functions(self, db, load_sanitized_references): # noqa
## test add_mca_to_existing_references()
r = db.query(ReferenceModel).first()
add_mca_to_existing_references(db, [r.curie], 'XB', logger)
db.commit()
mca_rows = db.query(ModCorpusAssociationModel).filter_by(reference_id=r.reference_id).order_by(
ModCorpusAssociationModel.mod_corpus_association_id).all()
assert len(mca_rows) == 2
assert mca_rows[1].corpus is None
assert mca_rows[1].mod_corpus_sort_source == 'mod_pubmed_search'
## getting things ready for pubmed update specific functions
# base_path = environ.get('XML_PATH')
log_file = path.join(path.dirname(__file__), 'pubmed_update.log')
fw = open(log_file, "w")
update_log = {}
field_names_to_report = ['comment_erratum', 'mesh_term', 'doi', 'pmcid', 'pmids_updated']
for field_name in field_names_to_report:
if field_name == 'pmids_updated':
update_log[field_name] = []
else:
update_log[field_name] = 0
pmid = "33622238"
pmid_to_reference_id = {}
reference_id_to_pmid = {}
mod = 'ZFIN'
get_pmid_to_reference_id(db, mod, pmid_to_reference_id, reference_id_to_pmid)
reference_id = pmid_to_reference_id[pmid]
## test update_comment_corrections()
reference_ids_to_comment_correction_type = {}
comment_correction_in_json = {
"ErratumIn": [
"34354223"
]
}
update_comment_corrections(db, fw, pmid, reference_id, pmid_to_reference_id,
reference_ids_to_comment_correction_type,
comment_correction_in_json, update_log)
db.commit()
rcc = db.query(ReferenceCommentAndCorrectionModel).filter_by(reference_id_to=reference_id).one_or_none()
assert rcc.reference_comment_and_correction_type == 'ErratumFor'
assert rcc.reference_id_from == pmid_to_reference_id['34354223']
## test update_mesh_terms()
mt_rows = db.query(MeshDetailModel).filter_by(reference_id=reference_id).all()
assert len(mt_rows) == 24
mesh_terms_in_json_data = [
{
"meshHeadingTerm": "Fibroblast Growth Factors",
"meshQualifierTerm": "genetics"
}
]
update_mesh_terms(db, fw, pmid, reference_id, [],
mesh_terms_in_json_data, update_log)
db.commit()
mt_rows = db.query(MeshDetailModel).filter_by(reference_id=reference_id).order_by(
MeshDetailModel.mesh_detail_id).all()
assert len(mt_rows) == 25
assert mt_rows[24].heading_term == 'Fibroblast Growth Factors'
assert mt_rows[24].qualifier_term == 'genetics'
## test update_cross_reference()
doi_db = "DOI:10.1186/s12576-021-00791-4"
doi_json = "DOI:10.1186/s12576-021-00791-x"
doi_list_in_db = []
pmcid_db = ""
pmcid_json = "PMCID:PMC667788"
pmcid_list_in_db = []
update_cross_reference(db, fw, pmid, reference_id, doi_db, doi_list_in_db, doi_json,
pmcid_db, pmcid_list_in_db, pmcid_json, update_log)
db.commit()
for x in db.query(CrossReferenceModel).filter_by(reference_id=reference_id).all():
if x.curie.startswith('PMCID:'):
assert x.curie == 'PMCID:PMC667788'
elif x.curie.startswith('DOI:'):
assert x.curie == 'DOI:10.1186/s12576-021-00791-4'
## test mark_false_positive_papers_as_out_of_corpus()
mca_rows = db.execute("SELECT cr.curie FROM cross_reference cr, mod_corpus_association mca, "
"mod m WHERE mca.reference_id = cr.reference_id "
"AND mca.mod_id = m.mod_id "
"AND m.abbreviation = 'XB'").fetchall()
assert len(mca_rows) > 0
fp_pmids = set()
for x in mca_rows:
fp_pmids.add(x[0].replace("PMID:", ""))
mark_false_positive_papers_as_out_of_corpus(db, 'XB', fp_pmids)
cr_rows = db.execute("SELECT is_obsolete FROM cross_reference "
"WHERE curie_prefix = 'Xenbase'").fetchall()
for x in cr_rows:
assert x[0] is True
| alliance-genome/agr_literature_service | tests/lit_processing/data_ingest/utils/test_db_write_utils.py | test_db_write_utils.py | py | 10,440 | python | en | code | 1 | github-code | 13 |
505297802 | from django.shortcuts import render
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from django.http.response import JsonResponse
from .models import customer
from customer.Serializer import customerSerializer,customercredSerializer
from django.core.files.storage import default_storage
# Create your views here.
# Create your views here.
@csrf_exempt
def customerApi(request,id=0):
if request.method=='GET':
customers = customer.objects.all()
customers_serializer = customerSerializer(customers,many=True)
return JsonResponse(customers_serializer.data,safe=False)
elif request.method =='POST':
customers_data=JSONParser().parse(request)
customers_serializer = customerSerializer(data=customers_data)
if customers_serializer.is_valid():
customers_serializer.save()
return JsonResponse("Added Successfully!!" , safe = True)
return JsonResponse("Failed to Add ", safe = False)
@csrf_exempt
def customercredApi(request):
if request.method == 'GET':
customercreds = customer.objects.all()
customercreds_serializer = customercredSerializer(customercreds, many=True)
return JsonResponse(customercreds_serializer.data, safe=False)
elif request.method == 'POST':
customercred_data = JSONParser().parse(request)
customercred_serializer = customercredSerializer(data=customercred_data)
if customercred_serializer.is_valid():
customercred_serializer.save()
return JsonResponse("Added Successfully!!", safe=False)
return JsonResponse("Failed to add the data", safe=False)
| sameerkulkarni2596/Main_project | customer/views.py | views.py | py | 1,733 | python | en | code | 0 | github-code | 13 |
5217142158 |
import configparser
import math
import random
import time
import numpy as np
import torch
#import seaborn as sns
import matplotlib.pyplot as plt
from scipy.ndimage import binary_erosion
def has_cuda():
# is there even cuda available?
has_cuda = torch.cuda.is_available()
if (has_cuda):
# we require cuda version >=3.5
capabilities = torch.cuda.get_device_capability()
major_version = capabilities[0]
minor_version = capabilities[1]
if major_version < 3 or (major_version == 3 and minor_version < 5):
has_cuda = False
return has_cuda
# Output a torch device to use.
def get_torch_device():
# output the gpu or cpu device
device = torch.device('cuda' if has_cuda() else 'cpu')
return device
def asMinutes(s):
m = math.floor(s / 60)
s -= m * 60
return '%dm %ds' % (m, s)
def timeSince(since, percent):
now = time.time()
s = now - since
es = s / (percent+.00001)
rs = es - s
return '%s (- %s)' % (asMinutes(s), asMinutes(rs))
def parseConfigFile(filename='config.ini'):
args = {}
config = configparser.ConfigParser()
config.read('config.ini')
args['data_folder'] = config['INPUT_DATA']['data_folder']
args['file_ext'] = config['INPUT_DATA']['file_ext']
args['data_name'] = config['TRAIN_DATA']['data_name']
args['patch_size'] = int(config['TRAIN_DATA']['patch_size'])
args['n_channels'] = int(config['TRAIN_DATA']['n_channels'])
args['max_samples_per_image'] = int(config['TRAIN_DATA']['max_samples_per_image'])
if args['max_samples_per_image'] == -1:
args['max_samples_per_image'] = np.inf
args['sample_level'] = int(config['TRAIN_DATA']['sample_level'])
args['train_perc'] = float(config['TRAIN_DATA']['train_perc'])
args['pytables_folder'] = config['TRAIN_DATA']['pytables_folder']
args['model_path'] = config['AUTOENCODER']['model_path']
args['n_classes'] = int(config['AUTOENCODER']['n_classes'])
args['padding'] = bool(config['AUTOENCODER']['padding'])
args['depth'] = int(config['AUTOENCODER']['depth'])
args['wf'] = int(config['AUTOENCODER']['wf'])
args['up_mode'] = config['AUTOENCODER']['up_mode']
args['batch_norm'] = bool(config['AUTOENCODER']['batch_norm'])
args['batch_size'] = int(config['AUTOENCODER']['batch_size'])
args['num_epochs'] = int(config['AUTOENCODER']['num_epochs'])
return args
def HeatMap_Sequences(data, filename='Heatmap_Sequences.tif'):
"""
HeatMap of Sequences
This method creates a heatmap/clustermap for sequences by latent features
for the unsupervised deep lerning methods.
Inputs
---------------------------------------
filename: str
Name of file to save heatmap.
sample_num_per_class: int
Number of events to randomly sample per class for heatmap.
color_dict: dict
Optional dictionary to provide specified colors for classes.
Returns
---------------------------------------
"""
sns.set(font_scale=0.5)
CM = sns.clustermap(data, standard_scale=1, cmap='bwr')
ax = CM.ax_heatmap
ax.set_xticklabels('')
ax.set_yticklabels('')
plt.show()
plt.savefig(filename)
def bw_on_image(im, bw, color):
for i in range(0, im.shape[2]):
t = im[:, :, i]
t[bw] = color[i]
im[:, :, i] = t
def label_on_image(im, labelIm, M=None, inPlace=True, randSeed=None):
if not inPlace:
im2 = im.copy()
label_on_image(im2, labelIm, M, True)
return im2
else:
max_label = np.max(labelIm)
if M is None:
if randSeed is not None:
random.seed(randSeed)
M = np.random.randint(0, 255, (max_label+1, 3))
if max_label == 0:
return
elif max_label == 1:
bw_on_image(im, labelIm == max_label, M[1, :])
else:
for r in range(1, im.shape[0]-1):
for c in range(1, im.shape[1]-1):
l = labelIm[r, c]
#if l > 0 and (l != labelIm[r,c-1] or l != labelIm[r,c+1] or l != labelIm[r-1,c] or l != labelIm[r+1,c]):
if l > 0:
im[r,c,0] = M[l, 0]
im[r,c,1] = M[l, 1]
im[r,c,2] = M[l, 2]
def find_edge(bw, strel=5):
return np.bitwise_xor(bw, binary_erosion(bw, structure=np.ones((strel, strel))).astype(bw.dtype))
| SatvikaBharadwaj/Unet_bonehistomorphometry | utils.py | utils.py | py | 4,544 | python | en | code | 0 | github-code | 13 |
43069089692 | # -*- coding: utf-8 -*-
# @Time : 2019-11-10 15:59
# @Author : GCY
# @FileName: sql_save.py
# @Software: PyCharm
# @Blog :https://github.com/GUO-xjtu
import pymysql
import utils.all_config as config
class MySQLCommand(object):
# 初始化类
def __init__(self):
self.host = config.mysql_host
self.port = config.mysql_port # 端口号
self.user = config.mysql_user # 用户名
self.password = config.mysql_password
self.db = config.mysql_db # 存储库
self.unum = 0
self.mnum = 0
self.pnum = 0
self.snum = 0
self.lnum = 0
# 连接数据库
def connectdb(self):
print('连接到mysql服务器...')
try:
self.conn = pymysql.connect(
host=self.host,
user=self.user,
passwd=self.password,
port=self.port,
db=self.db,
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)
self.cursor = self.conn.cursor()
print('连接上了!')
except:
print('连接失败!')
# 更新歌单信息
def update_list(self, music_list):
cols = music_list.keys()
values = music_list.values()
if 'id' in cols:
list_id = music_list['id']
elif 'list_id' in cols:
list_id = music_list['list_id']
else:
print('更新歌单信息失败,数据错误,此数据为%r' % music_list)
return
succeed = False
for col, val in zip(cols, values):
if col != 'list_id':
try:
sql = ("update music_list set %s = '%s' where id='%s'" % (col, val, list_id))
self.cursor.execute(sql)
self.conn.commit()
succeed = True
print('更新歌单%s的%s成功' % (list_id, col))
# 判断是否执行成功
except pymysql.Error as e:
# 发生错误回滚
# self.conn.rollback()
succeed = False
print("id为 %s 的歌单数据更新失败,原因 %s,数据为%r" % (list_id, e, music_list))
if succeed:
print('更新歌单%s成功' % list_id)
# 插入歌单信息
def insert_list(self, music_lists):
# 插入数据
try:
cols = ', '.join(music_lists.keys())
values = '"," '.join(music_lists.values())
sql = "INSERT INTO music_list (%s) VALUES (%s)" % (cols, '"' + values + '"')
try:
self.cursor.execute(sql)
self.conn.commit()
self.mnum += 1
try:
print("id为 %s 的歌单数据插入成功,第%d个歌单" % (music_lists['id'], self.mnum))
except:
print("id为 %s 的歌单数据插入成功,第%d个歌单" % (music_lists['list_id'], self.mnum))
except pymysql.Error as e:
# 发生错误回滚
# self.conn.rollback()
print(e)
self.mnum += 1
self.update_list(music_lists)
except pymysql.Error as e:
print("歌单数据库错误,原因 %s, 数据为 %r" % (e, music_lists))
# 更新用户数据
def update_user(self, users):
cols = users.keys()
values = users.values()
user_id = users['userId']
succeed = False
for col, val in zip(cols, values):
if col != 'userId':
try:
sql = ("update user set %s ='%s' where userId='%s'" % (col, val, user_id))
self.cursor.execute(sql)
self.conn.commit()
succeed = True
# 判断是否执行成功
except pymysql.Error as e:
# 发生错误回滚
# self.conn.rollback()
succeed = False
print("id为 %s 的用户数据更新失败,原因 %s" % (user_id, e))
if succeed:
print("id为 %s 的用户数据更新成功" % user_id)
# 插入用户数据, 插入之前先查询是否存在,若存在,就不再插入
def insert_user(self, users):
# 插入数据
try:
cols = ', '.join(users.keys())
values = '"," '.join(users.values())
sql = "INSERT INTO user (%s) VALUES (%s)" % (cols, '"' + values + '"')
try:
self.cursor.execute(sql)
self.conn.commit()
# 判断是否执行成功
self.unum += 1
print('id为%s的用户信息插入成功,第%d位用户' % (users['userId'], self.unum))
except pymysql.Error:
self.update_user(users)
except pymysql.Error as e:
print("用户数据库错误,原因 %s, 数据为:%r" % (e, users))
# 插入评论用户数据, 插入之前先查询是否存在,若存在,就不再插入
def insert_co_user(self, users):
# 插入数据
try:
sql = "INSERT INTO comment_user (user_id) VALUES (%s)" % users
try:
self.cursor.execute(sql)
self.conn.commit()
except pymysql.Error:
pass
except pymysql.Error as e:
print("用户数据库错误,原因 %s, 数据为:%r" % (e, users))
# 插入评论数据
def insert_comments(self, message):
try:
cols = ', '.join(message.keys())
values = '"," '.join(message.values())
sql = "INSERT INTO comments(%s) VALUES (%s)" % (cols, '"'+values+'"')
result = self.cursor.execute(sql)
self.conn.commit()
# 判断是否执行成功
if result:
self.pnum += 1
print("ID为%s的歌曲的第%d条评论插入成功" % (message['music_id'], self.pnum))
else:
print("ID为%s的歌曲的第%d条评论插入失败" % (message['music_id'], self.pnum))
self.pnum += 1
except pymysql.Error as e:
# 发生错误回滚
self.conn.rollback()
print("第%d条评论插入失败,原因 %d:%s" % (self.pnum, e.args[0], e.args[1]))
# 插入歌单评论数据
def insert_list_comm(self, message):
try:
cols = ', '.join(message.keys())
values = '"," '.join(message.values())
sql = "INSERT INTO list_comment(%s) VALUES (%s)" % (cols, '"'+values+'"')
result = self.cursor.execute(sql)
self.conn.commit()
# 判断是否执行成功
if result:
self.lnum += 1
print("ID为%s的歌单的第%d条评论插入成功" % (message['list_id'], self.lnum))
else:
print("ID为%s的歌单的第%d条评论插入失败" % (message['list_id'], self.lnum))
self.lnum += 1
except pymysql.Error as e:
# 发生错误回滚
self.conn.rollback()
print("第%d条评论插入失败,原因 %d:%s" % (self.lnum, e.args[0], e.args[1]))
# 更新歌曲数据
def update_music(self, music):
cols = music.keys()
values = music.values()
id = music['music_id']
for col, val in zip(cols, values):
if col != 'music_id':
try:
sql = ("update music set %s = '%s' where music_id='%s'" % (col, val, id))
self.cursor.execute(sql)
self.conn.commit()
print('更新成功,ID%s, 更新内容为%s' % (id, col))
# 判断是否执行成功
except pymysql.Error as e:
# 发生错误回滚
# self.conn.rollback()
print("id为 %s 的歌曲数据更新失败,原因 %s" % (id, e))
# 插入音乐数据
def insert_music(self, music):
id = music['music_id']
try:
sql = "INSERT INTO music (%s) VALUES (%s)" % ('music_id', id)
try:
self.cursor.execute(sql)
self.conn.commit()
# 判断是否执行成功
self.mnum += 1
print('id为%s的歌曲信息插入成功,第%d首歌曲' % (music['music_id'], self.mnum))
self.update_music(music)
except Exception as e:
print(e)
self.update_music(music)
except Exception as e:
print('插入ID为%s的歌曲信息失败,原因是%s. 歌曲内容为:%r' % (music['music_id'], e, music))
def update_singer(self, artist_id, artist_name, homepage_id, top50_song_dict):
self.snum += 1
cols = ['artist_id', 'artist_name', 'homepage_id', 'top50_song_dict']
values = [artist_id, artist_name, homepage_id, top50_song_dict]
for col, val in zip(cols, values):
if col != 'artist_id' and col != 'artist_name' and val != '':
sql = ("update singer set {}={} where artist_id={}".format(col, val, artist_id))
try:
self.cursor.execute(sql)
self.conn.commit()
print('更新歌手成功,ID-->%s, 更新内容为%s' % (artist_id, col))
# 判断是否执行成功
except pymysql.Error as e:
# 发生错误回滚
print("id为 %s 的歌手数据更新失败,原因 %s" % (artist_id, e))
print(val)
print('错误:', sql)
def insert_singer(self, artist_id, artist_name, homepage_id, top50_song_dict):
self.snum += 1
sql = "INSERT INTO singer(artist_id, artist_name, homepage_id, top50_song_dict) VALUES (%s, %s, %s, %s)"
try:
result = self.cursor.execute(sql, (artist_id, artist_name, homepage_id, top50_song_dict))
if result:
self.conn.commit()
print('第%d位歌手信息插入成功, 歌手ID为%s' % (self.snum, artist_id))
except:
self.update_singer(artist_id, artist_name, homepage_id, top50_song_dict)
def closeMysql(self):
self.cursor.close()
self.conn.close() # 创建数据库操作类的实例
| GUO-xjtu/wyy_spider | utils/sql_save.py | sql_save.py | py | 10,616 | python | en | code | 0 | github-code | 13 |
2200175437 | import numpy as np
def randfunc(p):
f = np.array(p)
f = f / f.sum()
for i in range(1,len(f)):
f[i] = f[i] + f[i-1]
r = np.random.rand()
return np.searchsorted(f,r)
def randfunc2(f):
f = np.array(f)
r = np.random.rand()
return np.searchsorted(f,r)
def zipf_init(num):
f = []
for i in range(num):
f.append(1.0/(i+1.0))
f = np.array(f)
f = f / f.sum()
for i in range(1,num):
f[i] = f[i] + f[i-1]
return f
| aaeviru/pythonlib | crand.py | crand.py | py | 485 | python | en | code | 0 | github-code | 13 |
19986619522 | # -*- coding: utf-8 -*-
import os
import sys
sys.path.append(os.getcwd()+"/helpers.py")
from helpers import Helpers
def main():
data = Helpers.get_rate()
df = Helpers.get_dataframe(data)
Helpers.write_data(df)
if __name__ == '__main__':
main()
| farman1855/babbel_project | module/core.py | core.py | py | 266 | python | en | code | 0 | github-code | 13 |
18014774013 | from random import randint, random
from tinydb import Query, TinyDB
from tinydb.table import Document
stock_table = TinyDB('stock.json').table('stock')
def get_stock(product_id: int) -> dict:
stock = stock_table.get(doc_id=product_id)
return stock.copy()
def update_stock(product_id: int, stock: int):
stock_table = TinyDB('stock.json').table('stock')
stock_table.update({"stock":stock}, doc_ids = [product_id])
if __name__ == "__main__":
for i in range(100):
stock = randint(1, 15)
price = round((random() * 100), 2)
stock_table.insert(Document({"stock":stock, "price": price}, doc_id=i))
# print(get_stock(15)) | Nvillaluenga/villaluenga-unt-microservices | capitulo_2/stock/repository/stockRepository.py | stockRepository.py | py | 643 | python | en | code | 0 | github-code | 13 |
32395172482 |
def update(mean1, var1, mean2, var2):
new_mean = (var2 * mean1 + var1 * mean2) / (var1 + var2)
new_var = 1/(1/var1 + 1/var2)
return [new_mean, new_var]
def predict(mean1, var1, mean2, var2):
new_mean = mean1 + mean2
new_var = var1 + var2
return [new_mean, new_var]
measurements = [5., 6., 7., 9., 10.]
motion = [1., 1., 2., 1., 1.]
measurement_sigma = 4. # assume constant variance
motion_sigma = 2. # # assume constant variance
# init position distribution
mu = 0.
sig = 1000.
for i in range(len(measurements)):
[mu, sig] = update(mu, sig, measurements[i], measurement_sigma)
print("Update: ",mu,sig)
[mu, sig] = predict(mu, sig, motion[i], motion_sigma)
print("Predict: ", mu, sig)
| AymanNasser/Sensor-Fusion-Nanodegree-Udacity | Part4 - Kalman Filters/Lesson-2/1D_KF.py | 1D_KF.py | py | 719 | python | en | code | 0 | github-code | 13 |
27388635845 | import argparse
from classes.datum import Datum
from classes.settings import Settings
parser = argparse.ArgumentParser(description = 'This is filtering outlier data.')
parser.add_argument('-s', '--setting', help = 'Enter path to the setting file.')
parser.add_argument('-d', '--data', help = 'Enter path to the data file')
def main():
args = parser.parse_args()
settings = Settings(args.setting)
datum = Datum()
if not datum.read_raw_data(args.data):
raise RuntimeError('There was an issue reading the data from the file.')
datum.sanatize(settings, 'Abs')
main()
| alizand1992/chemdata | chemdata.py | chemdata.py | py | 602 | python | en | code | 0 | github-code | 13 |
32932424666 | import cv2
from cvzone.HandTrackingModule import HandDetector
cap = cv2.VideoCapture(0)
detector = HandDetector(maxHands=2, detectionCon=0.8)
while True:
success, img = cap.read()
hands, img = detector.findHands(img)
if hands:
first_hand = hands[0]
first_hand_landmarks = first_hand['lmList']
first_hand_boundingBox = first_hand['bbox']
first_hand_centerPoint = first_hand['center']
first_hand_type = first_hand['type']
first_hand_fingers = detector.fingersUp(first_hand)
if len(hands)==2:
second_hand = hands[1]
second_hand_landmarks = second_hand['lmList']
second_hand_boundingBox = second_hand['bbox']
second_hand_centerPoint = second_hand['center']
second_hand_type = second_hand['type']
second_hand_fingers = detector.fingersUp(second_hand)
#print(first_hand_fingers, second_hand_fingers)
#length, info, img = detector.findDistance(first_hand_landmarks[8], second_hand_landmarks[8], img)
#length, info, img = detector.findDistance(first_hand_centerPoint, second_hand_centerPoint, img)
cv2.imshow('Image', img)
key = cv2.waitKey(1)
if key==27:
break
cap.release()
cv2.destroyAllWindows()
| JongBright/Hand-Tracking | multipleHandTracking.py | multipleHandTracking.py | py | 1,304 | python | en | code | 1 | github-code | 13 |
25032279424 | def lesenka(g, a, h):
'''g это тип лесенки: 1 - правый верх, 2- левый верх, 3- правый низ, 4- левый низ'''
'''a это количество строчек'''
'''h это символ, из которого лесенка будет состоять'''
for i in range(1, a + 1):
if g == 1:
print(' ' * (a - i), h * i)
if g == 2:
print(h * i)
if g == 3:
print(' ' * (i-1), h * (a - i+1))
if g == 4:
print(h * (a - i+1))
| TomasT2/hw-17.04.2021 | 1 lesenka.py | 1 lesenka.py | py | 563 | python | ru | code | 0 | github-code | 13 |
34304660815 | import os
from PyPDF2 import PdfFileMerger
import tkinter
from tkinter import filedialog
# Prevents an empty tkinter window from appearing
tkinter.Tk().withdraw()
#Getting the path of selected files in an array
source_dir = filedialog.askopenfilenames(filetypes=[('PDF files', '*.pdf'),
('JPG files', '*.jpg'),
('PNG files', '*.png'),
('all files', '.*')],
initialdir=os.getcwd(),
title="Select files", multiple=True)
#Making merger object
merger =PdfFileMerger()
source_dir = list(source_dir)
#fixes tkinter issue: Bring first element to the last
source_dir.append(source_dir.pop(0))
for item in source_dir:
if item.endswith('pdf'):
#appending all pdfs selections only
merger.append(item)
#writing the pdf of desired name specified by the user
merger.write(filedialog.asksaveasfilename())
merger.close()
| Siraj19/PDF_Merger | main.py | main.py | py | 1,112 | python | en | code | 1 | github-code | 13 |
28117058358 | #!/bin/python3
import math
import os
import random
import re
import sys
from collections import Counter
# Complete the freqQuery function below.
def freqQuery(queries):
hash = Counter()
count_hash = Counter() # count => count of count
result = []
for q in queries:
op, num = q[0], q[1]
if op == 1:
count_hash[hash[num]] -= 1
hash[num] += 1
count_hash[hash[num]] += 1
elif op == 2:
if hash[num] > 0: # count can be 0
count_hash[hash[num]] -= 1
hash[num] -= 1
count_hash[hash[num]] += 1
elif op == 3:
if count_hash[num] > 0: # count can be 0
result.append(1)
else:
result.append(0)
# print(op, num, hash, count_hash)
return result
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
q = int(input().strip())
queries = []
for _ in range(q):
queries.append(list(map(int, input().rstrip().split())))
ans = freqQuery(queries)
fptr.write('\n'.join(map(str, ans)))
fptr.write('\n')
fptr.close()
| piggybox/hackerrank | hash/frequency_queries.py | frequency_queries.py | py | 1,174 | python | en | code | 1 | github-code | 13 |
15339972701 | import time
import logging
import torch
from stud.callbacks import ProgressBar
from stud.training.earlystopping import EarlyStopping
from tqdm.auto import tqdm
from torch.nn.utils import clip_grad_norm_
from torch.optim.lr_scheduler import ReduceLROnPlateau
import pkbar
from sklearn.metrics import f1_score
try:
from torchcrf import CRF
except ModuleNotFoundError:
import os
os.system('pip install pytorch-crf')
from torchcrf import CRF
class F1_score(object):
"""
Utility function [NOT USED]
"""
def __init__(self, num_classes=None):
self.labels = None
if num_classes:
self.labels = [i for i in range(num_classes)]
def __call__(self, best_path, target):
best_path = torch.argmax(best_path, -1)
y_pred = best_path.contiguous().view(1, -1).squeeze().cpu()
y_true = target.contiguous().view(1, -1).squeeze().cpu()
y_true = y_true.detach().numpy()
y_pred = y_pred.detach().numpy()
return f1_score(y_true, y_pred, labels=self.labels, average="macro")
class Trainer:
def __init__(self, model, loss_function, optimizer, batch_num, num_classes, verbose):
"""
Creates a trainer object to train baseline models
Args:
model:
loss_function:
optimizer:
batch_num:
num_classes:
verbose:
"""
self.model = model
self.loss_function = loss_function
self.optimizer = optimizer
self._verbose = verbose
self.evaluator = F1_score(num_classes)
self.progressbar = ProgressBar(n_batch=batch_num, loss_name='loss')
def train(self, train_dataset, valid_dataset, epochs=1, save_to=None):
"""
Train the model on a given train dataset, and every epoch, computes val_loss. Trainer object is backed up
with Early Stopping, Gradient clipping, ReduceLROnPlateau to avoid over-fitting.
Args:
train_dataset:
valid_dataset:
epochs:
save_to:
Returns:
"""
train_loss = 0.0
es = EarlyStopping(patience=5)
for epoch in tqdm(range(epochs), desc="Training Epochs"):
epoch_loss = 0.0
self.model.train()
for step, sample in enumerate(train_dataset):
start = time.time()
inputs = sample['inputs']
labels = sample['outputs']
self.optimizer.zero_grad()
predictions_ = self.model(inputs)
predictions = predictions_.view(-1, predictions_.shape[-1])
labels = labels.view(-1)
sample_loss = self.loss_function(predictions, labels)
sample_loss.backward()
clip_grad_norm_(self.model.parameters(), 5.) # Gradient Clipping
self.optimizer.step()
epoch_loss += sample_loss.tolist()
f1_score_ = self.evaluator(predictions_, labels)
self.progressbar.step(batch_idx=step,
loss=sample_loss.item(),
f1=f1_score_.item(),
use_time=time.time() - start)
avg_epoch_loss = epoch_loss / len(train_dataset)
train_loss += avg_epoch_loss
valid_loss = self.evaluate(valid_dataset)
if self._verbose > 0:
print(
f'Epoch {epoch}: [loss = {avg_epoch_loss:0.4f}, val_loss = {valid_loss:0.4f}]')
if es.step(valid_loss):
print(
f"Early Stopping callback was activated at epoch num: {epoch}")
break
avg_epoch_loss = train_loss / epochs
if save_to is not None:
torch.save(self.model, save_to)
return avg_epoch_loss
def evaluate(self, valid_dataset):
"""
Used to compute val_loss on dev/valid dataset
Args:
valid_dataset:
Returns:
"""
valid_loss = 0.0
self.model.eval()
with torch.no_grad():
for sample in valid_dataset:
inputs = sample['inputs']
labels = sample['outputs']
predictions = self.model(inputs)
predictions = predictions.view(-1, predictions.shape[-1])
labels = labels.view(-1)
sample_loss = self.loss_function(predictions, labels)
valid_loss += sample_loss.tolist()
return valid_loss / len(valid_dataset)
def predict(self, x):
self.model.eval()
with torch.no_grad():
logits = self.model(x)
predictions = torch.argmax(logits, -1)
return logits, predictions
class CRF_Trainer:
def __init__(self, model, loss_function, optimizer, label_vocab, writer):
self.model = model
self.loss_function = loss_function
self.optimizer = optimizer
self.label_vocab = label_vocab
self._device = 'cuda' if torch.cuda.is_available() else 'cpu'
self.writer = writer
def train(self, train_dataset, valid_dataset, epochs=1):
"""
Train the model on a given train dataset, and every epoch, computes val_loss. Trainer object is backed up
with Early Stopping, clip_grad_norm_, ReduceLROnPlateau to avoid over-fitting.
Args:
train_dataset:
valid_dataset:
epochs:
Returns:
"""
es = EarlyStopping(patience=10)
scheduler = ReduceLROnPlateau(self.optimizer, 'min', patience=2)
train_loss = 0.0
epoch, step = 0, 0
for epoch in tqdm(range(epochs), desc=f'Training Epoch # {epoch + 1} / {epochs}'):
epoch_loss = 0.0
self.model.train()
for step, sample in tqdm(enumerate(train_dataset), desc=f'Train on batch # {step + 1}'):
inputs, labels = sample['inputs'], sample['outputs']
mask = (inputs != 0).to(self._device, dtype=torch.uint8)
self.optimizer.zero_grad()
# Pass the inputs directly, log_probabilities already calls forward
sample_loss = -self.model.log_probs(inputs, labels, mask)
sample_loss.backward()
clip_grad_norm_(self.model.parameters(), 5.) # Gradient Clipping
self.optimizer.step()
epoch_loss += sample_loss.tolist()
avg_epoch_loss = epoch_loss / len(train_dataset)
train_loss += avg_epoch_loss
valid_loss, valid_acc = self.evaluate(valid_dataset)
epoch_summary = f'Epoch #: {epoch + 1} [loss: {avg_epoch_loss:0.4f}, val_loss: {valid_loss:0.4f}]'
print(epoch_summary)
if self.writer:
self.writer.set_step(epoch, 'train')
self.writer.add_scalar('loss', epoch_loss)
self.writer.set_step(epoch, 'valid')
self.writer.add_scalar('val_loss', valid_loss)
scheduler.step(valid_loss)
if es.step(valid_loss):
print(f"Early Stopping activated on epoch #: {epoch}")
break
avg_epoch_loss = train_loss / epochs
return avg_epoch_loss
def evaluate(self, valid_dataset):
"""
Used to compute val_loss on dev/valid dataset
Args:
valid_dataset:
Returns:
"""
valid_loss = 0.0
# set dropout to 0!! Needed when we are in inference mode.
self.model.eval()
with torch.no_grad():
for sample in tqdm(valid_dataset, desc='Computing Val Loss'):
inputs = sample['inputs']
labels = sample['outputs']
mask = (inputs != 0).to(self._device, dtype=torch.uint8)
sample_loss = -self.model.log_probs(inputs, labels, mask).sum()
valid_loss += sample_loss.tolist()
# Compute accuracy
predictions = self.model.predict(inputs)
# argmax is a list, must convert to tensor
argmax = labels.new_tensor(predictions)
acc = (labels == argmax.squeeze()).float().mean()
return valid_loss / len(valid_dataset), acc / len(valid_dataset)
class BiLSTM_CRF_POS_Trainer:
"""
BiLSTM CRF POS Model trainer
"""
def __init__(self, model, loss_function, optimizer, label_vocab, writer):
self.model = model
self.loss_function = loss_function
self.optimizer = optimizer
self.label_vocab = label_vocab
self._device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
self.writer = writer
def train(self, train_dataset, valid_dataset, epochs=1):
es = EarlyStopping(patience=5)
scheduler = ReduceLROnPlateau(self.optimizer, 'min', patience=2, verbose=True)
train_loss, best_val_loss = 0.0, float(1e4)
epoch, step = 0, 0
for epoch in range(1, epochs + 1):
epoch_loss = 0.0
print(f'Epoch: {epoch}/{epochs}')
bar = pkbar.Kbar(target=len(train_dataset))
for step, sample in enumerate(train_dataset):
self.model.train()
inputs, labels, pos = sample['inputs'].to(self._device), sample['outputs'].to(self._device), sample[
'pos'].to(self._device)
mask = (inputs != 0).to(self._device, dtype=torch.uint8)
self.optimizer.zero_grad()
# Pass the inputs directly, log_probabilities already calls forward
sample_loss = -self.model.log_probs(inputs, labels, mask, pos)
sample_loss.backward()
clip_grad_norm_(self.model.parameters(), 5.0) # Gradient Clipping
self.optimizer.step()
epoch_loss += sample_loss.tolist()
bar.update(step, values=[("loss", sample_loss.item())])
avg_epoch_loss = epoch_loss / len(train_dataset)
train_loss += avg_epoch_loss
valid_loss = self.evaluate(valid_dataset)
bar.add(1, values=[("loss", train_loss), ("val_loss", valid_loss)])
if self.writer:
self.writer.set_step(epoch, 'train')
self.writer.add_scalar('loss', epoch_loss)
self.writer.set_step(epoch, 'valid')
self.writer.add_scalar('val_loss', valid_loss)
is_best = valid_loss <= best_val_loss
if is_best:
logging.info("Model Checkpoint saved")
best_val_loss = valid_loss
model_dir = os.path.join(os.getcwd(), 'model',
f'{self.model.name}_ckpt_best')
self.model.save_checkpoint(model_dir)
scheduler.step(valid_loss)
if es.step(valid_loss):
print(f"Early Stopping activated on epoch #: {epoch}")
break
avg_epoch_loss = train_loss / epochs
return avg_epoch_loss
def evaluate(self, valid_dataset):
valid_loss = 0.0
valid_f1 = 0.0
# set dropout to 0!! Needed when we are in inference mode.
self.model.eval()
with torch.no_grad():
for sample in valid_dataset:
inputs, labels, pos = sample['inputs'].to(self._device), sample['outputs'].to(self._device), sample[
'pos'].to(self._device)
mask = (inputs != 0).to(self._device, dtype=torch.uint8)
sample_loss = -self.model.log_probs(inputs, labels, mask, pos).sum()
valid_loss += sample_loss.tolist()
return valid_loss / len(valid_dataset)
| elsheikh21/named_entity_recognition | hw1/stud/training/train.py | train.py | py | 11,824 | python | en | code | 0 | github-code | 13 |
37798233944 | import os
from Clarinet.melodyextraction.skyline import skyline,mskyline
from Clarinet.constants import midi_folder
strategies={
"skyline":skyline,
"modified-skyline":mskyline
}
def extractMelody(file, output_dir=midi_folder,strategy="modified-skyline"):
folder_name,filename=file.split('/')[-2],file.split('/')[-1].split('.')[0]
if strategy=="modified-skyline":
output_dir=f"{output_dir}/{folder_name}_modified"
else:
output_dir=f"{output_dir}/{folder_name}"
strategy=strategies[strategy]
mid_out = strategy(file)
if not os.path.exists(output_dir):
os.mkdir(output_dir)
out=f"{output_dir}/{filename}_melody.mid"
mid_out.dump(out)
return(output_dir)
| rohans0509/Clarinet | Clarinet/melodyextraction/__init__.py | __init__.py | py | 727 | python | en | code | 4 | github-code | 13 |
29876864320 | """Implement quick sort in Python.
Input a list.
Output a sorted list."""
def quicksort(arr):
if len(arr) < 2:
return arr
pivot = arr.pop()
left = list(filter(lambda x: x <= pivot, arr))
right = list(filter(lambda x: x > pivot, arr))
return quicksort(left) + [pivot] + quicksort(right)
test = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14]
print(quicksort(test))
| michealkeines/DataStructures | quicksort.py | quicksort.py | py | 383 | python | en | code | 0 | github-code | 13 |
73789045779 | TOKEN = 'Token'
import telebot
from telebot import types
from os import path
#is_content=False
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from PIL import Image
import matplotlib.pyplot as plt
import torchvision.transforms as transforms
import torchvision.models as models
import copy
from script import image_loader, ContentLoss, gram_matrix, StyleLoss, Normalization, get_style_model_and_losses, get_input_optimizer, run_style_transfer
bot = telebot.TeleBot(TOKEN, parse_mode=None)
@bot.message_handler(commands=['start'])
def send_welcome(message):
kb = types.InlineKeyboardMarkup(row_width = 1)
btn1 = types.InlineKeyboardButton(text='старт', callback_data='btn1')
kb.add(btn1)
bot.send_message(message.chat.id, "Бот применяет к первому изображению стиль второго изображения. Загрузите содержание(c подписью content), а затем стиль(с подписью style), нажмите start и дождитесь завершения переноса. Содержание должно иметь четко выраженный объект. Стиль должен иметь просто четкие линии, несколько однородных тонов.", reply_markup=kb)
@bot.message_handler(commands=['help'])
def send_welcome2(message):
bot.send_message(message.chat.id, 'send me 2 photos. Image photo and style photo')
@bot.message_handler(content_types = ['photo'])
def handle_docs_document(message):
file_info = bot.get_file(message.photo[len(message.photo) - 1].file_id)
downloaded_file = bot.download_file(file_info.file_path)
#src = message.photo[1].file_id
src = message.caption+'.jpg'
if message.caption in ['content', 'style']:
with open(src, 'wb') as new_file:
new_file.write(downloaded_file)
bot.reply_to(message, 'фотография '+message.caption+' сохранена')
else:
bot.reply_to(message, 'пожалуйста отметьте на фотографии content или style')
@bot.callback_query_handler(func=lambda callback: callback.data)
def check_callback_data(callback):
if callback.data == 'btn1':
if path.exists("content.jpg") and path.exists("style.jpg"):
style_img = image_loader('style.jpg')
content_img = image_loader('content.jpg')
assert style_img.size() == content_img.size(), \
"we need to import style and content images of the same size"
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
imsize = 512 if torch.cuda.is_available() else 128
cnn = models.vgg19(pretrained=True).features.to(device).eval()
loader = transforms.Compose([
transforms.Resize((imsize, imsize)), # scale imported image
transforms.ToTensor()]) # transform it into a torch tensor
cnn_normalization_mean = torch.tensor([0.485, 0.456, 0.406]).to(device)
cnn_normalization_std = torch.tensor([0.229, 0.224, 0.225]).to(device)
content_layers_default = ['conv_4']
style_layers_default = ['conv_1', 'conv_2', 'conv_3', 'conv_4', 'conv_5']
input_img = content_img.clone()
output = run_style_transfer(cnn, cnn_normalization_mean, cnn_normalization_std,
content_img, style_img, input_img)
with open('output.jpg', 'wb') as output_file:
image = output.cpu().clone() # we clone the tensor to not do changes on it
image = image.squeeze(0) # remove the fake batch dimension
image = transforms.ToPILImage(output)
output_file.write(output.transforms.ToPILImage())
bot.send_photo(callback.message.chat.id, photo=open('output.jpg', 'rb'), caption='смотри, что получилось')
else:
bot.send_message(callback.message.chat.id, 'пришлите фотографии стиля и контента')
bot.infinity_polling()
| marssellio/dls_final_project | bot.py | bot.py | py | 4,162 | python | en | code | 0 | github-code | 13 |
70179200018 | "Iris Model"
# pylint: disable=no-member
from app import db
from sqlalchemy.sql import select
import pandas as pd
# Iris dataset taken from: https://scikit-learn.org/stable/auto_examples/datasets/plot_iris_dataset.html
class Iris(db.Model):
__tablename__ = "iris"
iris_id = db.Column(db.Integer, primary_key=True)
sep_length = db.Column(db.Float)
sep_width = db.Column(db.Float)
pet_length = db.Column(db.Float)
pet_width = db.Column(db.Float)
target = db.Column(db.Float)
@classmethod
def get_data(cls) -> pd.DataFrame:
# train_df = pd.read_sql(db.session.query(cls), db.get_engine())
train_df = pd.read_sql(select([cls]), db.get_engine())
return train_df.drop(["target", "iris_id"], axis=1), train_df["target"]
def __repr__(self):
return f"<Iris {self.iris_id}>"
| davideasaf/modern-flask-boilerplate | app/models/iris.py | iris.py | py | 842 | python | en | code | 0 | github-code | 13 |
7457320257 | #!/bin/env python
import curses
from curses import wrapper
import time
import random
import os
current_text = "texts/classic.txt"
wpm = 0
def start_screen(stdscr):
stdscr.clear()
stdscr.addstr("Welcome to Carter's Typing Test!")
stdscr.addstr("\nPress enter to begin!")
stdscr.addstr("\nMore options:")
stdscr.addstr("\n\tt: change theme")
stdscr.addstr("\n\tm: change mode")
stdscr.addstr("\n\ta: add to current text")
stdscr.addstr("\n\ts: score report(currently unsupported)")
stdscr.refresh()
def display_text(stdscr, target, current, wpm=0):
stdscr.addstr(target)
stdscr.addstr(1, 0, f"WPM: {wpm}")
for i, char in enumerate(current):
correct_char = target[i]
color = curses.color_pair(1)
if char != correct_char:
color = curses.color_pair(2)
stdscr.addstr(0, i, char, color)
def change_theme(stdscr):
stdscr.clear()
stdscr.addstr("Light (L) or Dark (D) mode?")
key = stdscr.getkey()
background_color = curses.COLOR_WHITE
default_text_color = curses.COLOR_BLACK
if key in ("L", "l"):
background_color = curses.COLOR_WHITE
default_text_color = curses.COLOR_BLACK
elif key in ("D", "d"):
background_color = curses.COLOR_BLACK
default_text_color = curses.COLOR_WHITE
stdscr.clear()
stdscr.addstr("Pick color of correct text")
stdscr.addstr("\n\tb: blue")
stdscr.addstr("\n\tc: cyan")
stdscr.addstr("\n\tg: green")
stdscr.addstr("\n\tm: magenta")
stdscr.addstr("\n\ty: yellow")
key = stdscr.getkey()
correct_text_color = curses.COLOR_GREEN
if key in ("b", "B"):
correct_text_color = curses.COLOR_BLUE
elif key in ("c", "C"):
correct_text_color = curses.COLOR_CYAN
elif key in ("g", "G"):
correct_text_color = curses.COLOR_GREEN
elif key in ("m", "M"):
correct_text_color = curses.COLOR_MAGENTA
elif key in ("y", "Y"):
correct_text_color = curses.COLOR_YELLOW
curses.init_pair(1, correct_text_color, background_color)
curses.init_pair(2, curses.COLOR_RED, background_color)
def change_mode(stdscr):
global current_text
stdscr.clear()
stdscr.addstr(f"Current text file is: {current_text}")
stdscr.addstr("\nWhich text file would you like to use?")
i = 0
for file in os.listdir("./texts"):
stdscr.addstr(f"\n{i}: {file}")
i += 1
stdscr.refresh()
key = stdscr.getkey()
j = 0
for file in os.listdir("./texts"):
stdscr.addstr(f"\n{j}")
if int(key) == j:
current_text = "texts/" + file
break
j += 1
def add_text(stdscr):
global current_text
stdscr.clear()
stdscr.addstr(f"The current text file is: {current_text}")
stdscr.addstr("\nPlease input a new line, or press esc to cancel.\nOnce you are done press esc.")
stdscr.refresh()
new_line = []
while True:
key = stdscr.getkey()
stdscr.clear()
if ord(key) == 27:
break
if key in ("KEY_BACKSPACE", '\b', "\x7f"):
if len(new_line) > 0:
new_line.pop()
else:
new_line.append(key)
stdscr.addstr("".join(new_line))
stdscr.refresh()
if len(new_line) > 0:
stdscr.clear()
stdscr.addstr("Your new line is:")
stdscr.addstr("\n" + "".join(new_line).strip())
stdscr.addstr("\nPress esc to cancel, enter to save.")
stdscr.refresh()
key = stdscr.getkey()
if ord(key) == 27:
pass
else:
new_line = "".join(new_line).strip()
with open(current_text, "a") as f:
f.writelines("\n" + new_line)
def score_report(stdscr):
stdscr.clear()
scores = []
sum_of_scores = 0
high_score = 0
low_score = 1000
with open("scores.txt", "r") as f:
lines = f.readlines()
for line in lines:
scores.append(line)
sum_of_scores += int(line)
if int(line) > high_score:
high_score = int(line)
if int(line) < low_score:
low_score = int(line)
stdscr.addstr(f"\nAverage WPM: {sum_of_scores/len(scores)}")
stdscr.addstr(f"\nHigh Score: {high_score}")
stdscr.addstr(f"\nLow Score: {low_score}")
stdscr.getkey()
def add_score(score):
with open("scores.txt", "a") as f:
f.writelines("\n" + str(score))
lines = []
with open("scores.txt", "r") as f:
lines = f.readlines()
with open("scores.txt", "w") as f:
for number, line in enumerate(lines):
if line != "\n":
f.write(line)
def load_text():
global current_text
with open(current_text, "r") as f:
lines = f.readlines()
return random.choice(lines).strip()
def wpm_test(stdscr):
global wpm
target_text = load_text()
current_text = []
wpm = 0
start_time = time.time()
stdscr.nodelay(True)
while True:
time_elapsed = max(time.time() - start_time, 1)
wpm = round((len(current_text) / (time_elapsed / 60)) / 5)
stdscr.clear()
display_text(stdscr, target_text, current_text, wpm)
stdscr.refresh()
if "".join(current_text) == target_text:
stdscr.nodelay(False)
break
try:
key = stdscr.getkey()
except:
continue
if current_text == []:
start_time = time.time()
try:
if ord(key) == 27: #If user hits escape key
break
except:
print()
if key in ("KEY_BACKSPACE", '\b', "\x7f"):
if len(current_text) > 0:
current_text.pop()
elif len(current_text) < len(target_text):
current_text.append(key)
def main(stdscr):
curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)
global current_text
global wpm
while True:
start_screen(stdscr)
key = stdscr.getkey()
doTest = False
if key == "t":
change_theme(stdscr)
elif key == "m":
change_mode(stdscr)
elif key == "a":
add_text(stdscr)
elif key == "s":
score_report(stdscr)
elif ord(key) == 27:
break
else:
doTest = True
while doTest:
wpm_test(stdscr)
add_score(wpm)
stdscr.addstr(2, 0, "You completed the text! Press enter to do another test...")
key = stdscr.getkey()
if ord(key) == 27:
doTest = False
wrapper(main)
| CarterT27/Terminal-Typing-Test | main.py | main.py | py | 6,736 | python | en | code | 3 | github-code | 13 |
9936281877 | import requests
sid = '917503904'
headers = {
'Student-Id': sid,
}
certificate_path = 'C:\\Users\\Jacob\\.mitmproxy\\mitmproxy-ca-cert.pem'
r = requests.get('https://kartik-labeling-cvpr-0ed3099180c2.herokuapp.com/ecs152a_ass1', headers=headers, verify=certificate_path)
print("Status Code:", r.status_code)
print(r.headers) | jucobee/152-networks | mitmproxy/proj3.py | proj3.py | py | 330 | python | en | code | 0 | github-code | 13 |
40144911934 | import autode as ade
import numpy as np
from copy import deepcopy
from autode.log import logger
from autode.mol_graphs import make_graph
from autode.path.path import Path
from autode.transition_states.ts_guess import get_ts_guess
from autode.utils import work_in
def get_ts_adaptive_path(reactant, product, method, fbonds, bbonds,
name='adaptive'):
"""
Generate a TS guess geometry based on an adaptive path along multiple
breaking and/or forming bonds
Arguments:
reactant (autode.species.Species):
product (autode.species.Species):
method (autode.wrappers.base.ElectronicStructureMethod):
fbonds (list(autode.pes.pes.FormingBond)):
bbonds (list(autode.pes.pes.BreakingBond)):
Keyword Arguments:
name (str):
Returns:
(autode.transition_states.ts_guess.TSguess | None):
"""
ts_path = AdaptivePath(init_species=reactant,
bonds=pruned_active_bonds(reactant, fbonds, bbonds),
method=method,
final_species=product)
ts_path.generate(name=name)
if not ts_path.contains_peak:
logger.warning('Adaptive path had no peak')
return None
return get_ts_guess(ts_path[ts_path.peak_idx].species, reactant, product,
name=name)
def pruned_active_bonds(initial_species, fbonds, bbonds):
"""
Prune the set of forming and breaking bonds for special cases
(1) Three bonds form a ring, in which case the adaptive path may fail to
traverse the MEP. If so then delete the breaking bond with the largest
overlap to the forming bond e.g.::
H
/ \
M --- C
where all the bonds drawn are active and the C-H bond is forming
Arguments:
initial_species (autode.species.Species):
fbonds (list(autode.pes.pes.FormingBond)):
bbonds (list(autode.pes.pes.BreakingBond)):
Returns:
(list(autode.pes.pes.ScannedBond)):
"""
logger.info('Pruning active bonds for special cases')
# Flat list of all the atom indexes in the breaking/forming bonds
a_atoms = [bond.atom_indexes for bond in fbonds + bbonds]
coords = initial_species.coordinates
if len(fbonds) == 1 and len(bbonds) == 2 and len(set(a_atoms)) == 3:
logger.info('Found 3-membered ring with 2 breaking and 1 forming bond')
f_i, f_j = fbonds[0].atom_indexes
f_vec = coords[f_i] - coords[f_j]
f_vec /= np.linalg.norm(f_vec)
b0_i, b0_j = bbonds[0].atom_indexes
b0_projection = np.dot((coords[b0_i] - coords[b0_j]), f_vec)
b1_i, b1_j = bbonds[1].atom_indexes
b1_projection = np.dot((coords[b1_i] - coords[b1_j]), f_vec)
if b0_projection > b1_projection:
logger.info(f'Excluding {bbonds[0]}')
bbonds.pop(0)
else:
logger.info(f'Excluding {bbonds[1]}')
bbonds.pop(1)
return fbonds + bbonds
class PathPoint:
def copy(self):
"""Return a copy of this point"""
return PathPoint(self.species.copy(), deepcopy(self.constraints))
def __init__(self, species, constraints):
"""
Point on a PES path
Arguments:
species (autode.species.Species):
constraints (dict): Distance constraints keyed with atom indexes as
a tuple with distances (floats) as values
"""
self.species = species
assert type(constraints) is dict
self.constraints = constraints
self.energy = None # Ha
self.grad = None # Ha Å^-1
class AdaptivePath(Path):
def __eq__(self, other):
"""Equality of two adaptive paths"""
if not isinstance(other, AdaptivePath):
return False
return super().__eq__(other)
@work_in('initial_path')
def append(self, point) -> None:
"""
Append a point to the path and optimise it
Arguments:
point (PathPoint): Point on a path
Raises:
(autode.exceptions.CalculationException):
"""
super().append(point)
idx = len(self) - 1
calc = ade.Calculation(name=f'path_opt{idx}',
molecule=self[idx].species,
method=self.method,
keywords=self.method.keywords.low_opt,
n_cores=ade.Config.n_cores,
distance_constraints=self[idx].constraints)
calc.run()
# Set the required properties from the calculation
self[idx].species.atoms = calc.get_final_atoms()
make_graph(self[idx].species)
self[idx].energy = calc.get_energy()
if self.method.name == 'xtb' or self.method.name == 'mopac':
# XTB prints gradients including the constraints, which are ~0
# the gradient here is just the derivative of the electronic energy
# so rerun a gradient calculation, which should be very fast
# while MOPAC doesn't print gradients for a constrained opt
calc = ade.Calculation(name=f'path_grad{idx}',
molecule=self[idx].species,
method=self.method,
keywords=self.method.keywords.grad,
n_cores=ade.Config.n_cores)
calc.run()
self[idx].grad = calc.get_gradients()
calc.clean_up(force=True, everything=True)
else:
self[idx].grad = calc.get_gradients()
return None
def plot_energies(self, save=True, name='init_path', color='k', xlabel='ζ'):
return super().plot_energies(save, name, color, xlabel)
def contains_suitable_peak(self):
"""Does this path contain a peak suitable for a TS guess?"""
if not self.contains_peak:
return False
if self.products_made(product=self.final_species):
logger.info('Products made and have a peak. Assuming suitable!')
return True
# Products aren't made by isomorphism but we may still have a suitable
# peak..
if any(self[-1].constraints[b.atom_indexes] == b.final_dist
for b in self.bonds):
logger.warning('Have a peak, products not made on isomorphism, but'
' at least one of the distances is final. Assuming '
'the peak is suitable ')
return True
return False
def _adjust_constraints(self, point):
"""
Adjust the geometry constraints based on the final point
Arguments:
point (autode.neb.PathPoint):
"""
logger.info(f'Adjusting constraints on point {len(self)}')
# Flat list of all the atom indexes involved in the bonds
atom_idxs = [i for bond in self.bonds for i in bond]
max_step, min_step = ade.Config.max_step_size, ade.Config.min_step_size
for bond in self.bonds:
(i, j), coords = bond.atom_indexes, self[-1].species.coordinates
# Normalised r_ij vector
vec = coords[j] - coords[i]
vec /= np.linalg.norm(vec)
# Calculate |∇E_i·r| i.e. the gradient along the bond. Positive
# values are downhill in energy to form the bond and negative
# downhill to break it
gradi = np.dot(self[-1].grad[i], vec) # |∇E_i·r| bond midpoint
gradj = np.dot(self[-1].grad[j], -vec)
# Exclude gradients from atoms that are being substituted
if atom_idxs.count(i) > 1:
grad = gradj
elif atom_idxs.count(j) > 1:
grad = gradi
else:
grad = np.average((gradi, gradj))
logger.info(f'|∇E_i·r| = {grad:.4f} on {bond}')
# Downhill in energy to break/form this breaking/forming bond
if grad * np.sign(bond.dr) > 0:
dr = np.sign(bond.dr) * ade.Config.max_step_size
# otherwise use a scaled value, depending on the gradient
# large values will have small step sizes, down to min_step Å
else:
dr = (max_step - min_step) * np.exp(-(grad/0.05)**2) + min_step
dr *= np.sign(bond.dr)
new_dist = point.species.distance(*bond.atom_indexes) + dr
# No need to go exceed final distances on forming/breaking bonds
if bond.forming and new_dist < bond.final_dist:
new_dist = bond.final_dist
elif bond.breaking and new_dist > bond.final_dist:
new_dist = bond.final_dist
else:
logger.info(f'Using step {dr:.3f} Å on bond: {bond}')
point.constraints[bond.atom_indexes] = new_dist
return None
def generate(self, init_step_size=0.2, name='initial'):
"""
Generate the path from the starting point; can be called only once!
Keyword arguments:
init_step_size (float): Initial step size in all bonds to calculate
the gradient
name (str): Prefix to use for saved plot and geometries
"""
logger.info('Generating path from the initial species')
assert len(self) == 1
# Always perform an initial step linear in all bonds
logger.info('Performing a linear step and calculating gradients')
point = self[0].copy()
for bond in self.bonds:
# Shift will be -min_step_size if ∆r is negative and larger than
# the minimum step size
dr = np.sign(bond.dr) * min(init_step_size, np.abs(bond.dr))
point.constraints[bond.atom_indexes] += dr
self.append(point)
logger.info('First point found')
def reached_final_point():
"""Are there any more points to add?"""
return all(point.constraints[b.atom_indexes] == b.final_dist
for b in self.bonds)
logger.info('Adaptively adding points to the path')
while not (reached_final_point() or self.contains_suitable_peak()):
point = self[-1].copy()
self._adjust_constraints(point=point)
self.append(point)
self.plot_energies(name=f'{name}_path')
self.print_geometries(name=f'{name}_path')
return None
def __init__(self, init_species, bonds, method, final_species=None):
"""
PES Path
Arguments:
init_species (autode.species.Species):
bonds (list(autode.pes.ScannedBond)):
method (autode.wrappers.base.ElectronicStructureMethod):
Keyword Arguments:
final_species (autode.species.Species):
"""
super().__init__()
self.method = method
self.bonds = bonds
self.final_species = final_species
# Bonds need to have the initial and final dists to drive along them
for bond in bonds:
assert bond.curr_dist is not None and bond.final_dist is not None
# Add the first point - will run a constrained minimisation if possible
init_point = PathPoint(species=init_species,
constraints={bond.atom_indexes: bond.curr_dist
for bond in bonds})
if init_point.species.n_atoms > 0:
self.append(init_point)
| Crossfoot/autodE | autode/path/adaptive.py | adaptive.py | py | 11,617 | python | en | code | null | github-code | 13 |
36548072389 | from army import Army
from army import Squad
from units import Soldier
from random import Random
class Strategy:
@staticmethod
def rand(enemy: Army, rand_=Random()):
squad = rand_.choice(enemy.squads)
return rand_.choice(squad.units)
@staticmethod
def weakest(enemy: Army):
squad_hp = 10000
squad = None
for s in enemy.squads:
sum = 0
for unit in s.units:
sum += unit.hp
if squad_hp > sum:
squad = s
squad_hp = sum
unit = squad.units[0]
for u in squad.units:
if u.hp < unit.hp:
unit = u
return unit
@staticmethod
def strongest(enemy: Army):
squad_hp = 0
squad = None
for s in enemy.squads:
sum = 0
for unit in s.units:
sum += unit.hp
if squad_hp < sum:
squad = s
squad_hp = sum
unit = squad.units[0]
for u in squad.units:
if u.hp > unit.hp:
unit = u
return unit
strategy = {
'random': Strategy.rand,
'weakest': Strategy.weakest,
'strongest': Strategy.strongest
}
| alpine-cat/battlefield | strategy.py | strategy.py | py | 1,245 | python | en | code | 0 | github-code | 13 |
33792479431 | import cv2
import matplotlib.pyplot as plt
import numpy as np
import skimage.io as io
from skimage.filters import threshold_otsu
from scipy.signal import savgol_filter
# cropped,top,bottom = find_roi(img)
def find_roi(img):
img = img.astype('float32')
# binarize
thresh = threshold_otsu(img)
binary = img > thresh
binary = binary.astype(np.uint8)
# close
kernel = np.ones((25, 25), np.uint8)
close = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel)
# crop
height, width = close.shape
first_white = int(np.argmax(close > 0) / width)
last_white = height - int(np.argmax(np.flip(close) > 0) / width)
crop = img[:last_white, :]
return crop, first_white, last_white
# flattened, unshiftList = flatten(img)
# unflattened = shiftColumn(flattened, unshiftList)
def flatten(img):
img = img.astype('float32')
# denoise Gaussian
gaussian = cv2.GaussianBlur(img, (5, 5), 0)
# tentatively assign brightest pixel as RPE
height, width = gaussian.shape
indicesX = np.array([], dtype=np.int8)
indicesY = np.array([], dtype=np.int8)
snrs = np.array([], dtype=np.float)
for i in range(width):
cur_col = np.array(gaussian[:, i])
snr = signaltonoise(cur_col, axis=0, ddof=0)
maxi = np.where(cur_col == np.amax(cur_col))[0][0]
indicesX = np.append(indicesX, i)
indicesY = np.append(indicesY, maxi)
snrs = np.append(snrs, snr)
# remove columns that present a significantly lower signal-to-noise ratio
mean = np.mean(snrs)
# 5% less than average snr allowed
limit = mean - 0.05 * mean
remove = np.where(snrs < limit)[0]
indicesX = np.delete(indicesX, remove)
indicesY = np.delete(indicesY, remove)
# remove outliers greater 60pixels
median = np.median(indicesY)
newX = np.array([], dtype=np.int8)
newY = np.array([], dtype=np.int8)
for i in range(len(indicesY)):
el = indicesY[i]
if el < median + 60 and el > median - 60:
newX = np.append(newX, indicesX[i])
newY = np.append(newY, el)
# img[el, indicesX[i]] = 1.
indicesX = newX
indicesY = newY
# fit 2nd order polynomial to RPE Points
# coeffs = np.polyfit(indicesX, indicesY, 4)
# approximation = np.poly1d(coeffs)
# rpe = scipy.interpolate.UnivariateSpline(indicesX, indicesY)
# # approximation.set_smoothing_factor(150)
# alternatively
nearest_neighbour_rpe = np.array([indicesY[find_nearest_return_index(indicesX, x)] for x in range(width)])
nearest_neighbour_rpe = medfilt(nearest_neighbour_rpe, 3)
nearest_neighbour_rpe = savgol_filter(nearest_neighbour_rpe, 51, 3)
# shift each column up or down such that the RPE points lie on a flat line
shiftList = np.array([], dtype=np.int8)
for i in range(width):
shiftList = np.append(shiftList, nearest_neighbour_rpe[i])
# print rpe-line-estimate
#img[int(nearest_neighbour_rpe[i]), i] = 1.
# Todo is this okay?
# col = img[:, i]
# for y in range(height):
# if y > approx+20.:
# col[y] = 0.
# img[:, i] = col
maxShift = max(shiftList)
shiftList = [int(maxShift - x) for x in shiftList]
img = shiftColumn(shiftList, img)
return img, [-x for x in shiftList]
def shiftColumn(shift_list, img):
img = img.copy()
if len(img.shape) > 2:
height, width, channels = img.shape
for color in range(4):
for i in range(len(shift_list)):
tmp_column = img[:, i, color]
shift = int(shift_list[i])
if shift > 0:
img[shift:height - 1, i, color] = tmp_column[0:height - 1 - shift]
img[0:shift - 1, i, color] = np.flip(tmp_column[:shift - 1])
if shift < 0:
img[0:height - 1 + shift, i, color] = tmp_column[abs(shift):height - 1]
img[height - 1 + shift:height - 1, i, color] = np.flip(tmp_column[height - 1 + shift:height - 1])
elif len(img.shape) == 2:
height, width = img.shape
for i in range(len(shift_list)):
tmp_column = img[:, i]
shift = int(shift_list[i])
if shift > 0:
img[shift:height - 1, i] = tmp_column[0:height - 1 - shift]
img[0:shift - 1, i] = np.flip(tmp_column[:shift - 1])
if shift < 0:
img[0:height - 1 + shift, i] = tmp_column[abs(shift):height - 1]
img[height - 1 + shift:height - 1, i] = np.flip(tmp_column[height - 1 + shift:height - 1])
elif len(img.shape) == 1:
for i in range(len(shift_list)):
shift = int(shift_list[i])
img[i] = img[i] + shift
return img
def medfilt(x, k):
k2 = (k - 1) // 2
y = np.zeros((len(x), k), dtype=x.dtype)
y[:, k2] = x
for i in range(k2):
j = k2 - i
y[j:, i] = x[:-j]
y[:j, i] = x[0]
y[:-j, -(i + 1)] = x[j:]
y[-j:, -(i + 1)] = x[-1]
return np.median(y, axis=1)
def signaltonoise(a, axis, ddof):
a = np.asanyarray(a)
m = a.mean(axis)
sd = a.std(axis=axis, ddof=ddof)
return np.where(sd == 0, 0, m / sd)
# dark_to_bright, bright_to_dark = get_gradients(img,filter)
# filter: 'Scharr' or 'Sobel'
def get_gradients(img, filter):
if filter == 'Scharr':
img = cv2.Scharr(img, cv2.CV_16S, 0, 1)
norm_Img = img * (1 / np.amax(img))
return (norm_Img + abs(norm_Img)) / 2, (norm_Img - abs(norm_Img)) / (-2)
if filter == 'Sobel':
img = cv2.Sobel(img, cv2.CV_16S, 0, 1, ksize=5)
norm_Img = img * (1 / np.amax(img))
return (norm_Img + abs(norm_Img)) / 2, (norm_Img - abs(norm_Img)) / (-2)
def find_nearest_return_index(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return idx
def intensity_profiling(img, rpe_estimate):
img = img.astype('float32')
# denoise with 3x19 average filter
kernel = np.ones((3, 19), np.float32) / 48
img = cv2.filter2D(img, -1, kernel)
# 0 -> if: smaller than the median of their corresponding column
for i in range(img.shape[1]):
median = np.median(img[:, i])
curCol = img[:, i]
thresh = np.array([0. if float(x) < median else float(x) for x in curCol], dtype=np.float32)
img[:, i] = thresh
# second-order derivative of the contrast-enhanced image to boost layer boundaries
for i in range(img.shape[1]):
curCol = img[:, i]
first_derivative = np.gradient(curCol)
second_derivative = np.gradient(first_derivative)
img[:, i] = second_derivative
# thresholding 0
ret, img = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY)
# set all non-zero clusters less than 5 pixels tall to zero
for i in range(img.shape[1]):
curCol = img[:, i]
clustersize = 0
for j in range(len(curCol)):
if curCol[j] >= 254.:
clustersize = clustersize + 1
elif clustersize < 5:
while clustersize > 0:
curCol[j - clustersize] = 0.
clustersize = clustersize - 1
img[:, i] = curCol
# join the remaining clusters that are closer than 3 pixels from each other.
# Todo Test if it makes a difference?
for i in range(img.shape[0]):
curRow = img[i, :]
gap = 0
for j in range(len(curRow)):
if curRow[j] >= 254.:
if gap < 3:
while gap > 0:
curRow[j - gap] = 255.
gap = gap - 1
gap = 0
else:
gap = gap + 1
img[i, :] = curRow
# horizontal 1-D closing operation with a kernel of 10 pixels
kernel = np.ones((1, 10), np.uint8)
opening = np.uint8(cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel))
img = opening
# remove any cluster smaller than 500 pixels
nlabels, labels, stats, centroids = cv2.connectedComponentsWithStats(img)
height, width = labels.shape
for i in range(height):
for j in range(width):
if labels[i, j] > 0:
for label in range(1, nlabels):
y_values, x_values = np.where(labels == label)
if len(x_values) < 500:
for k in range(len(x_values)):
labels[y_values[k], x_values[k]] = 0.
else:
for k in range(len(x_values)):
labels[y_values[k], x_values[k]] = -1.
img = np.array([-x for x in labels])
# interpolating the approximate location
# from neighboring columns in which they are detached
# remove values below rpe
# for i in range(width):
# rpe_pos = rpe_estimate(i)
# for j in range(height):
# if j > rpe_pos + 5:
# img[j, i] = 0.0
return img
# y x
def path_to_y_array(paths, width):
paths = np.array(sorted(np.array(paths), key=lambda tup: tup[0]))
ys = paths[:, 0]
reduced = [paths[np.argmax(paths[:, 1] == i)] for i in range(width)]
reduced = np.array(sorted(np.array(reduced), key=lambda tup: tup[1]))
reduced = reduced[:, 0]
return reduced
def mask_image(img, y_values, offset=0, above=False):
img = np.array(img.copy())
height, width = img.shape
for x in range(width):
cur_col = img[:, x]
for y in range(height):
if above:
if y < y_values[x] + offset:
cur_col[y] = 0.
elif y > y_values[x] + offset:
img[y, x] = 0.
return img
################################ examples################################
def exampleCrop():
image_file = '../testvectors/sick.tif'
im = io.imread(image_file, as_gray=True)
im = im.astype('float32')
cropped, top, bottom = find_roi(im)
plt.gca().imshow(cropped, cmap='gray')
plt.figure()
plt.gca().imshow(im, cmap='gray')
plt.setp(plt.gca(), xticks=[], yticks=[])
plt.show()
def exampleFlatten():
image_file = '../testvectors/sick/with druses/7CE97D80.tif'
im = io.imread(image_file, as_gray=True)
im = im.astype('float32')
flattened, shiftlist = flatten(im)
plt.gca().imshow(flattened, cmap='gray')
plt.setp(plt.gca(), xticks=[], yticks=[])
plt.show()
# dark_to_bright, bright_to_dark = get_gradients(img,filter)
# filter: 'Scharr' or 'Sobel'
def get_gradients(img, filter):
if filter == 'Scharr':
img = cv2.Scharr(img, cv2.CV_16S, 0, 1)
norm_Img = (img - np.amin(img))/(np.amax(img)-np.amin(img))
return norm_Img, (1-norm_Img)
if filter == 'Sobel':
img = cv2.Sobel(img, cv2.CV_16S, 0, 1, ksize=5)
norm_Img = img * (1 / np.amax(abs(img)))
pos = (norm_Img + abs(norm_Img)) / 2
neg = (norm_Img - abs(norm_Img)) /(-2)
cv2.imshow("neg", neg)
cv2.waitKey(0)
cv2.destroyAllWindows()
return (norm_Img + abs(norm_Img)) / 2, (norm_Img - abs(norm_Img)) / (-2)
if filter == 'Sobel2':
img = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=5)
norm_Img = (img - np.amin(img))/(np.amax(img)-np.amin(img))
return norm_Img, (1-norm_Img)
def exampleGradient():
image_file = '../testvectors/sick/with druses/7CE97D80.tif'
im = io.imread(image_file, as_gray=True)
im = im.astype('float32')
scharr,neg_scharr = get_gradients(im,'Scharr')
sobel,neg_sobel = get_gradients(im,'Sobel2')
stack1 = np.vstack((sobel,scharr))
stack2 = np.vstack((neg_sobel,neg_scharr))
stack = np.hstack((stack1,stack2))
plt.gca().imshow(stack, cmap='gray')
plt.setp(plt.gca(), xticks=[], yticks=[])
plt.show()
def exampleIntensityProfiling():
image_file = '../testvectors/sick/with druses/7CE97D80.tif'
im = io.imread(image_file, as_gray=True)
im = im.astype('float32')
crop, top, bottom = find_roi(im)
flattened, invert, rpe = flatten(crop)
result = shiftColumn(invert, flattened)
both = np.vstack((crop, flattened, result))
fig = plt.gcf()
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
ax.imshow(both, cmap='gray')
plt.setp(ax, xticks=[], yticks=[])
plt.show()
#exampleIntensityProfiling()
#exampleGradient()
#exampleFlatten()
| creamartin/retina | assets/segmentation/segmentation_helper.py | segmentation_helper.py | py | 12,450 | python | en | code | 5 | github-code | 13 |
18445712200 | from .create_input import hexToBinaryZokratesInput
from .create_input import hexToDecimalZokratesInput
def compute_merkle_path(tree, element):
i = tree.index(element)
path = []
direction = []
while i > 0:
if i % 2 == 0:
path.append(tree[i-1])
direction.append(0)
else:
if tree[i+1] != '':
path.append(tree[i+1])
else:
path.append(tree[i])
direction.append(1)
i = int((i-1)/2)
return [path, direction]
def get_proof_input(tree, element, header):
path = compute_merkle_path(tree, element)
return ' '.join(hexToDecimalZokratesInput(header)) + ' ' + hexToBinaryZokratesInput(''.join(path[0])) + ' ' + ' '.join([str(element) for element in path[1]])
| informartin/zkRelay | preprocessing/compute_merkle_path.py | compute_merkle_path.py | py | 792 | python | en | code | 24 | github-code | 13 |
8320907199 | """ Contains a City class for modeling epidemic spread through Europe """
from geopy.distance import vincenty
class City(object):
""" City class which contains a dictionary of trade routes,
a dictionary of pilgrimage routes, id, position, name, country,
and whether or not it is infected.
"""
def __init__(self, name, pos, city_id, country):
""" Initializes City class.
name: string of city name
pos: tuple of (lat, long)
id: int that represents city
country: string of country name
"""
self.name = name
self.pos = pos
self.city_id = city_id
self.country = country
# Set up attributes for infection and healing
self.is_infected = False
# self.infected_timer = 0
self.infection_count = 0
self.susceptibility = 1
self.historical_mortality = None
# Create dictionaries for pilgrimage routes and trade routes
# Dictionaries are of city_id : distance in km
self.route_plg = dict()
self.route_trade = dict()
self.degree = 0
self.clustering_coefficient = 0
self.closeness = 0
def __str__(self):
""" Prints the city name """
return self.name + ", " + self.country + "\nPilgrimage Routes:\n" + str(self.route_plg)+"\nTradeRoutes:\n"+str(self.route_trade)
def calc_dist(self, pos):
""" Given a different city's position, calculates
the distance between them 'as a bird flies'.
"""
return (vincenty(self.pos, pos).meters)/1000
def add_route(self, city, use):
""" Given another city and what the connection was used for,
passes the proper dictionary to add_to_dict, which will then
add the city to the proper place.
city: instance of City class
use: string of either pil or trd
"""
if use is 'plg':
self.add_to_dict(self.route_plg, city, use)
else: self.add_to_dict(self.route_trade, city, use)
def add_to_dict(self, route_dict, city, use):
""" Checks to see if city is already in route_dict and adds
it if not.
"""
if city.city_id not in route_dict:
dist = self.calc_dist(city.pos)
route_dict[city.city_id] = dist
city.add_route(self, use) # Tries to add itself to the other city
self.degree += 1
# def heal(self):
# """ Heals the city if infected """
# self.infected_timer -= 1
# if self.infected_timer <= 0:
# return True
# return False
| LucyWilcox/Plague | code/City.py | City.py | py | 2,261 | python | en | code | 0 | github-code | 13 |
3176973614 | from sklearn.neural_network import MLPRegressor
from math import *
import numpy as np
# Method for splitting list of data into smaller lists with roughly even numbers
def split_data(data, num_nets):
for i in range(0, len(data), num_nets):
yield data[i:i + num_nets]
def singleVsMultiple(size, breadth, num_nets, split_factor):
# Generate Data
rand = np.random.uniform
training_input = [[rand(0.0, breadth)] for i in range(size)]
testing_input = [[rand(0.0, breadth)] for i in range(size)]
training_output = [sqrt(datum[0]) for datum in training_input]
testing_output = [sqrt(datum[0]) for datum in testing_input]
# Instantiate Nets
single_net = MLPRegressor()
multiple_nets = [MLPRegressor() for i in range(num_nets)]
# Train Nets
single_net.fit(training_input, training_output)
multiple_nets = [multiple_nets[i].fit(training_input, training_output) for i in range(num_nets)]
# Test Nets
single_prediction = single_net.predict(testing_input)
multiple_predictions = [multiple_nets[i].predict(testing_input) for i in range(num_nets)]
# Checking Accuracy (Print Out)
# for i in range(size):
# print(testing_output[i], single_prediction[i])
# print("////////////////////////////////////")
# for j in range(num_nets):
# print(testing_output[i], multiple_predictions[j][i])
# print("####################################")
# Checking Accuracy (Mean Squared Error)
# single_net_error = (np.sum([(single_prediction[i] - testing_output[i])**2 for i in range(size)]))/size
# print("Single Net MSE: ",single_net_error)
# multiple_nets_errors = []
# for i in range(num_nets):
# error = (np.sum([(multiple_predictions[i][j] - testing_output[j])**2 for j in range(size)]))/size
# multiple_nets_errors.append(error)
# print("Other Net MSE: ", error)
# Checking Accuracy (Mean Square Error - Median Composite Estimate)
single_net_error = (np.sum([(single_prediction[i] - testing_output[i])**2 for i in range(size)]))/size
print("Single Net MSE: ",single_net_error)
multiple_nets_error = (np.sum([ (np.average([ multiple_predictions[j][i] for j in range(num_nets) ]) - testing_output[i])**2 for i in range(size)]))/size
print("Multiple Net MSE: ", multiple_nets_error)
return (single_net_error, multiple_nets_error)
| nvonturk/Experiments | networks/fullinfo_net_sqrt.py | fullinfo_net_sqrt.py | py | 2,400 | python | en | code | 0 | github-code | 13 |
13023906911 | # Encoding: UTF-8
import matplotlib.pyplot as plt
def sum():
# 定义5个数
num1 = 1
num2 = 2
num3 = 3
num4 = 4
num5 = 5
# 计算它们的和
total = num1 + num2 + num3 + num4 + num5
return total
def huatu():
# x =[0,12,9,3,0]
# y=[0,0,4,4,0]
# # 不规则四边形
# x =[0,12,9,3,0]
# y =[7,10,17,8,7]
# 海宁坐标
x = [30.361647,30.362318,30.362090,30.361494,30.361647]
y = [120.397399,120.397969,120.398272,120.397736,120.397399]
# # // 海宁区间经纬度调换顺序 (30.361494, 120.397736)->(30.362090, 120.398272)->(30.362318, 120.397969)->(30.361647, 120.397399)
# x = [30.361494,30.362090,30.362318,30.361647,30.361494]
# y = [120.397736,120.398272,120.397969,120.397399,120.397736]
# plt.axis([0, 12, 0, 4])
plt.plot(y,x,'r-o')
# 在每个点上添加标记1234
for i in range(len(x)-1):
plt.text(y[i], x[i], str(i+1), fontsize=12, ha='center', va='center')
plt.show()
if __name__ == '__main__':
# 输出结果
total = sum()
print("这5个数的和为:", total)
huatu()
plt.pause(0)
# # BEGIN
# import java.lang.Math;
# public class Main {
# public static void main(String[] args) {
# double lon = 116.4074; // 经度
# double lat = 39.9042; // 纬度
# double x = lon * 20037508.34 / 180;
# double y = Math.log(Math.tan((90 + lat) * Math.PI / 360)) / (Math.PI / 180);
# y = y * 20037508.34 / 180;
# System.out.println("经度:" + lon + ",纬度:" + lat + ",墨卡托坐标x:" + x + ",墨卡托坐标y:" + y);
# }
# }
# # END
# public class Main {
# public static void main(String[] args) {
# double lon = 116.4074; // 经度
# double lat = 39.9042; // 纬度
# double x = lon * 20037508.34 / 180;
# double y = Math.log(Math.tan((90 + lat) * Math.PI / 360)) / (Math.PI / 180);
# y = y * 20037508.34 / 180;
# System.out.println("经度:" + lon + ",纬度:" + lat + ",墨卡托坐标x:" + x + ",墨卡托坐标y:" + y);
# // 定义区域的边界
# double minX = 10000000;
# double minY = 10000000;
# double maxX = 20000000;
# double maxY = 20000000;
# // 检查点是否在区域内
# boolean isInRegion = isPointInRegion(x, y, minX, minY, maxX, maxY);
# System.out.println("点是否在区域内:" + isInRegion);
# }
# public static boolean isPointInRegion(double x, double y, double minX, double minY, double maxX, double maxY) {
# return x >= minX && x <= maxX && y >= minY && y <= maxY;
# }
# }
# public class Main {
# public static void main(String[] args) {
# Coordinate[] polygonCoordinates = new Coordinate[]{
# new Coordinate(0.0, 7.0),
# new Coordinate(12.0, 10.0),
# new Coordinate(9.0, 17.0),
# new Coordinate(3.0, 8.0),
# new Coordinate(0.0, 7.0)
# };
# // 转换多边形的每个顶点坐标,并创建新的Coordinate对象
# Coordinate[] transformedCoordinates = new Coordinate[polygonCoordinates.length];
# for (int i = 0; i < polygonCoordinates.length; i++) {
# double[] mercator = Mercator(polygonCoordinates[i].x, polygonCoordinates[i].y);
# transformedCoordinates[i] = new Coordinate(mercator[0], mercator[1]);
# }
# // 打印转换后的坐标
# for (Coordinate coordinate : transformedCoordinates) {
# System.out.println("墨卡托坐标x:" + coordinate.x + ",墨卡托坐标y:" + coordinate.y);
# }
# }
# public static double[] Mercator(double WGS1984_lon, double WGS1984_lat) {
# double mercator_x = WGS1984_lon * 20037508.34 / 180;
# double mercator_y = Math.log(Math.tan((90 + WGS1984_lat) * Math.PI / 360)) / (Math.PI / 180);
# mercator_y = mercator_y * 20037508.34 / 180;
# return new double[]{mercator_x, mercator_y};
# }
# } | sc1206385466/UAV-Flight-Area-Restrictions | huizhiquyutu.py | huizhiquyutu.py | py | 4,067 | python | en | code | 0 | github-code | 13 |
24991410256 | import sys
l = [list(map(int, s.strip())) for s in sys.stdin]
def step(old):
new = [[i + 1 for i in x] for x in old]
extinct = set()
nxt, fla = doflashes(new, extinct)
print(f'fla {fla} ext {extinct}')
return nxt, fla
def doflashes(world, extinct):
new = [row[:] for row in world]
flashes = 0
for ri, row in enumerate(new):
for ci, cell in enumerate(row):
if (ri, ci) in extinct:
continue
if cell > 9:
flashes += 1
new[ri][ci] = 0
extinct.add((ri, ci))
for x, y in ((ci, ri-1), (ci, ri+1), (ci-1, ri), (ci+1, ri), (ci-1, ri-1), (ci-1, ri+1), (ci+1, ri-1), (ci+1, ri+1)):
if 0 <= y < len(new) and 0 <= x < len(row) and (y, x) not in extinct:
new[y][x] += 1
nworld, fla = doflashes(new, extinct)
return nworld, flashes + fla
return new, flashes
def show(wld):
for row in wld:
for col in row:
print(str(col), end=' ')
print()
tot = 0
world = [row[:] for row in l]
for st in range(100):
world, fla = step(world)
tot += fla
print(f'step {st+1} flashes {tot}')
show(world)
| Grissess/aoc2021 | day11.py | day11.py | py | 1,240 | python | en | code | 0 | github-code | 13 |
14739336055 | #Uses python3
import sys
import queue
white = False
black = True
biPartate = True
def bipartite(adj):
#write your code here
#isBipartite = True
colour = [None] * len(adj)
marked = [False] * len(adj)
for v in range(len(adj)):
if not marked[v]:
bfs(adj, colour, marked, v)
if biPartate:
return 1
return 0
def bfs(adj, colour, marked, v):
global white, black, biPartate
q = queue.Queue(maxsize=len(adj))
colour[v] = white
marked[v] = True
q.put(v)
while not q.empty():
v = q.get()
for w in adj[v]:
if not marked[w]:
marked[w] = True
colour[w] = not colour[v]
q.put(w)
elif colour[w] == colour[v]:
biPartate = False
if __name__ == '__main__':
#file1 = open("01bi.txt", "r")
#input = file1.read()
input = sys.stdin.read()
data = list(map(int, input.split()))
n, m = data[0:2]
data = data[2:]
edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2]))
adj = [[] for _ in range(n)]
for (a, b) in edges:
adj[a - 1].append(b - 1)
adj[b - 1].append(a - 1)
print(bipartite(adj))
| price-dj/Algorithms_On_Graphs | Week3/workspace/bipartite.py | bipartite.py | py | 1,216 | python | en | code | 0 | github-code | 13 |
7236455306 | import unittest
import requests
import json
from InterfaceTest.common.config import Conf
from InterfaceTest.common.mylogin import mylogin
import time
class GoodsDetail(unittest.TestCase):
def setUp(self):
self.cookie = mylogin()
# 商品详情页
def test_a_goodsDetail(self):
data={
'clientType':2,
'goodsId':256595020035811,
'imei':'0B3B30A7-41B8-43D6-8979-A49F56020843',
'mobileModel':'iPhone_X',
'systemVersion':'12.1',
'version':105,
'versionIos':105
}
response = requests.post(url=Conf.API_ADDRESS+'/sdapp/goods/queryDetail',data=data,cookies=self.cookie)
# response = json.loads(response.content)
# print(response)
# self.assertEqual(True, False)
code = response.status_code
if code == 200:
result = json.loads(response.content)
# return result["result"]["goodsSkus"][0]["skuId"]
# return result["result"]["goodsDetail"]["goodsId"]
goodsId = result["result"]["goodsDetail"]["goodsId"]
skuId = result["result"]["goodsSkus"][0]["skuId"]
# list = []
#
# list.append(skuId)
# list.append(goodsId)
# # return skuIds[0]
# return list
dict = {"skuId":skuId,"goodsId":goodsId}
# print(str(dict))
return dict
# 商品说明
def test_b_goodsexplain(self):
a = self.test_a_goodsDetail()
# print(a)
# user_dict = eval(a)
# print(type(user_dict))
id = a['goodsId']
# print(id)
data = {
'clientType': 2,
'imei':'D439B4B3-DB5D-4505-B38E-4AB6351B158E',
'mobileModel': 'iPhone_X',
'goodsId':id,
'version': 105,
'versionIos': 105,
'systemVersion': '12.1',
'weexVersion':127
}
# print(data)
response = requests.post(url=Conf.API_ADDRESS+'/sdapp/goods/getGoodsInstructions',data=data,cookies=self.cookie)
result = json.loads(response.content)
print(result)
time.sleep(1)
# 商品优惠券(需要查看该商品有没有优惠券)
def test_c_goodscoupon(self):
a = self.test_a_goodsDetail()
id = a['goodsId']
data = {
'clientType': 2,
'imei': 'D439B4B3-DB5D-4505-B38E-4AB6351B158E',
'mobileModel': 'iPhone_X',
'goodsId': id,
'version': 105,
'versionIos': 105,
'systemVersion': '12.1',
'weexVersion': 127
}
response = requests.post(url=Conf.API_ADDRESS+'/sdapp/coupon/findByGoodsId',data=data,cookies=self.cookie)
# result = json.loads(response.content)
# print(result)
# time.sleep(1)
code = response.status_code
if code == 200:
result = json.loads(response.content)
# id = result["result"][0]["id"]
# print(id)
return result["result"][0]["id"]
# 领取优惠券
def test_d_receivecoupon(self):
id1 = self.test_c_goodscoupon()
# print(id)
data = {
'clientType': 2,
'imei': 'D439B4B3-DB5D-4505-B38E-4AB6351B158E',
'mobileModel': 'iPhone_X',
'couponId': id1,
'version': 105,
'versionIos': 105,
'systemVersion': '12.1',
'weexVersion': 127
}
response = requests.post(url=Conf.API_ADDRESS+"/sdapp/coupon/addUserCoupon",data=data,cookies=self.cookie)
result = json.loads(response.content)
print(result)
time.sleep(1)
# 商品收藏
def test_e_shoucang(self):
a = self.test_a_goodsDetail()
id = a['goodsId']
# print(id)
data = {
'clientType': 2,
'imei': '0B3B30A7-41B8-43D6-8979-A49F56020843',
'mobileModel': 'iPhone_X',
'systemVersion': '12.1',
'version': 105,
'versionIos': 105,
'goodsId': id
}
response = requests.post(url=Conf.API_ADDRESS + '/sdapp/goods/collect/insertCollect', data=data,
cookies=self.cookie)
result = json.loads(response.content)
print(result)
time.sleep(1)
# 商品精选
def test_f_jingxuan(self):
a = self.test_a_goodsDetail()
id = a['goodsId']
# print(id)
data = {
'clientType': 2,
'imei': '0B3B30A7-41B8-43D6-8979-A49F56020843',
'mobileModel': 'iPhone_X',
'systemVersion': '12.1',
'version': 105,
'versionIos': 105,
'goodsId': id
}
response = requests.post(url=Conf.API_ADDRESS + '/sdapp/goods/user/shop/insertGoodsUserShop', data=data,
cookies=self.cookie)
result = json.loads(response.content)
print(result)
time.sleep(1)
# 商品分享
def test_g_fexniang(self):
a = self.test_a_goodsDetail()
id = a['goodsId']
# print(id)
data = {
'clientType': 2,
'type': 4,
'imei': '0B3B30A7-41B8-43D6-8979-A49F56020843',
'mobileModel': 'iPhone_X',
'systemVersion': '12.1',
'version': 105,
'versionIos': 105,
'dataId': id
}
response = requests.post(url=Conf.API_ADDRESS + '/sdapp/core/share/detail', data=data, cookies=self.cookie)
result = json.loads(response.content)
print(result)
time.sleep(1)
# 分享增加活跃值
def test_h_addActive(self):
a = self.test_a_goodsDetail()
id = a['goodsId']
# print(id)
data = {
'clientType': 2,
'dataId': id,
'imei': '0B3B30A7-41B8-43D6-8979-A49F56020843',
'mobileModel': 'iPhone_X',
'systemVersion': '12.1',
'version': 105,
'versionIos': 105,
'type': 4
}
response = requests.post(url=Conf.API_ADDRESS+"/sdapp/core/share/addActive",data=data,cookies=self.cookie)
result = json.loads(response.content)
print(result)
time.sleep(1)
# 加入购物车列表
def test_i_addshopcar(self):
a = self.test_a_goodsDetail()
skuId = a['skuId']
tradeSkuVO = [{"num":1,"skuId":"{}".format(skuId)}]
data = {
'clientType': 2,
'mobileModel': 'iPhone_X',
'systemVersion': '12.1',
'version': 105,
'versionIos': 105,
'tradeSkuVO':'{}'.format(tradeSkuVO)
# 'skuId':'{}'.format(skuId),
# 'num':1
}
print(data)
result = requests.post(url=Conf.API_ADDRESS + "/sdapp/shop/car/addShopCar",data=data,cookies=self.cookie)
response = json.loads(result.content)
print(response)
time.sleep(1)
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
| renjunpei/Django | text/InterfaceTest/testcase/goodsDetail.py | goodsDetail.py | py | 7,177 | python | en | code | 0 | github-code | 13 |
20654307114 |
class Pedestrian:
def __init__(self, num, prng, current_time):
self.num = num
self.arrival = current_time
self.speed = prng()
self.crossed_street = False
print ("[PED] created with id: {}, speed: {}".format(self.num, self.speed))
def calc_travel_time(self, travel_distance):
# calculate expected travel time
travel_time = self.time_from_dist(travel_distance)
self.travel_time = travel_time
print("[PED] calculated travel_time = {} s".format(travel_time))
# return calculated travel time (not clock time) for welford
return travel_time
def calc_crosswalk_time(self, dist_to_crosswalk, time):
# calculate when ped will arrive at crosswalk
crosswalk_time = self.time_from_dist(dist_to_crosswalk) + time
self.crosswalk_time = crosswalk_time
print("[PED] calculated crosswalk_time = {} s".format(crosswalk_time))
# return expected arrival time for event creation
return crosswalk_time
def calc_cross_time(self, street_width):
# calculate time taken to cross street
cross_time = self.time_from_dist(street_width)
self.cross_time = cross_time
print("[PED] calculated cross_time = {} s".format(cross_time))
return cross_time
def time_from_dist(self, distance):
# helper to calculate travel times based on distance and speed
return distance / self.speed
def cross_street(self, current_time):
print("[PED] crossing street")
# calculate delay time due to waiting at crosswalk
self.delay = current_time - self.crosswalk_time
self.crossed_street = True
print("[PED] calculated delay: {}".format(self.delay))
# return delay time
return self.delay
| eric-olson/crosswalkSIM | pedestrian.py | pedestrian.py | py | 1,826 | python | en | code | 0 | github-code | 13 |
7878969678 | '''
집합 자료형
#set.py
Author : sblim
Date : 2018-12-08
이 프로그램은 Set 스터디 프로그램입니다.
'''
#집합(SET)은 파이썬 2.3버전부터 지원하기 시작한 자료형
#s1 = set([1,2,3]) #{1,2,3}
#s2 = set("HELLO") #{'H','E','L','O'}
#특징
#1. 중복을 허용하지 않는다.
#2. 순서가 없다. 인덱싱을 사용할 수 없다.
#인덱싱을 사용하기 위해서
#리스트로 변환
#LIST = list(s1)
#튜플로 변환
#TUPLE = tuple(s2)
#집합 자료형 활용하기
#교집합
s1 = set([1,2,3,4])
s2 = set([3,4,5,6])
s3 = s1&s2
print(s3) #{3,4}
s3 = s1.intersection(s2)
print(s3) #{3,4}
#합집합
s3 = s1 | s2
print(s3) #{1,2,3,4,5,6}
s3 = s1.union(s2)
print(s3)
#차집합
s3 = s1 - s2 #s3 = s1.difference(s2)
print(s3) #{1,2}
s3 = s2 - s1 #s3 = s2.difference(s1)
print(s3) #{5,6}
#ADD 1개 원소 추가
s1 = set([1,2,3])
s1.add(4)
print(s1)
#UPDATE 여러 개 원소 추가
s1 = set([1,2,3])
s1.update([5,6,7])
print(s1) #{1,2,3,5,6,7}
#REMOVE 특정 원소 제거
s1 = set([1,2,3])
s1.remove(2)
print(s1) #{1,3}
| andylion-repo/python | bak/set.py | set.py | py | 1,075 | python | ko | code | 0 | github-code | 13 |
8208656084 | from ufit import UFitError
from ufit.data import ill, nicos, nicos_old, simple, simple_csv, trisp, \
llb, cascade, taipan, nist
from ufit.data.loader import Loader
from ufit.data.dataset import Dataset, ScanData, ImageData, DatasetList
from ufit.plotting import mapping
from ufit.pycompat import listitems
data_formats_scan = {
'ill': ill,
'nicos': nicos,
'old nicos': nicos_old,
'simple': simple,
'simple comma-separated': simple_csv,
'trisp': trisp,
'llb': llb,
'taipan': taipan,
'nist': nist,
}
data_formats_image = {
'cascade': cascade,
}
data_formats = dict(listitems(data_formats_scan) +
listitems(data_formats_image))
__all__ = ['Dataset', 'DatasetList', 'ScanData', 'ImageData', 'sets',
'set_datatemplate', 'set_dataformat', 'read_data', 'as_data',
'read_numors', 'do_mapping']
# simplified interface for usage in noninteractive scripts
global_loader = Loader()
sets = global_loader.sets
def set_datatemplate(template):
"""Set a new template for data file names.
Normally, data file names consist of a fixed part and a sequential number.
Therefore ufit constructs file names from a data template, which should
contain a placeholder like ``%06d`` (for a 6-digit sequential number), and
the actual file number given in the :func:`read_data` function.
An example::
set_datatemplate('/data/exp/data2012n%06d.dat')
d1 = read_data(100)
d2 = read_data(101)
# etc.
"""
global_loader.template = template
def set_dataformat(format):
"""Set the input data format.
Normally ufit autodetects file formats, but this can be overridden using
this function. Data formats are:
* ``'ill'`` - ILL TAS data format
* ``'llb'`` - LLB binary TAS data format (known working for data from 1T and
4F unpolarized)
* ``'nicos'`` - NICOS data format
* ``'old nicos'`` - NICOS 1.0 data format
* ``'trisp'`` - FRM-II TRISP data format
* ``'taipan'`` - ANSTO Taipan data format
* ``'nist'`` - NIST data format
* ``'simple'`` - simple whitespace-separated multi-column files
* ``'simple comma-separated'`` - simple comma-separated multi-column files
"""
if format not in data_formats:
raise UFitError('Unknown data format: %r, available formats are %s'
% (format, ', '.join(data_formats)))
global_loader.format = format
def read_data(n, xcol='auto', ycol='auto', dycol=None, ncol=None, nscale=1, filter=None):
"""Read a data file. Returns a :class:`Dataset` object.
:param xcol: X column name (or 1-based index)
:param ycol: Y column name (or 1-based index)
:param ycol: Y errors column name (or 1-based index); the default is to take
the square root of the Y column as appropriate for counts
:param ncol: normalization column name (or 1-based index); typically a beam
monitor column
:param nscale: scale for the normalization column; the Y data is determined
as ``y[i] = y_raw[i] / ncol[i] * nscale``
:param filter: dictionary of column names and filtered values; only datapoints
with given values will be part of the dataset; if None, then not applied.
"""
return global_loader.load(n, xcol, ycol, dycol, ncol, nscale, filter)
def as_data(x, y, dy, name=''):
"""Quickly construct a :class:`Dataset` object from three numpy arrays."""
return Dataset.from_arrays(name or 'data', x, y, dy)
def read_numors(nstring, binsize, xcol='auto', ycol='auto',
dycol=None, ncol=None, nscale=1, floatmerge=True):
"""Read a number of data files. Returns a list of :class:`Dataset`\s.
:param nstring: A string that gives file numbers, with the operators given
below.
:param binsize: Bin size when files need to be merged according to
*nstring*.
:param floatmerge: If to use float merging instead of binning. Default true.
Other parameters as in :func:`read_data`.
*nstring* can contain these operators:
* ``,`` -- loads multiple files
* ``-`` -- loads multiple sequential files
* ``+`` -- merges multiple files
* ``>`` -- merges multiple sequential files
For example:
* ``'10-15,23'`` loads files 10 through 15 and 23 in 7 separate datasets.
* ``'10+11,23+24'`` loads two datasets consisting of files 10 and 11 merged
into one set, as well as files 23 and 24.
* ``'10>15+23'`` merges files 10 through 15 and 23 into one single dataset.
* ``'10,11,12+13,14'`` loads four sets.
"""
return global_loader.load_numors(nstring, binsize, xcol, ycol,
dycol, ncol, nscale, floatmerge)
def do_mapping(x, y, runs, minmax=None, mode=0, log=False, dots=True,
xscale=1, yscale=1, interpolate=100, usemask=True, figure=None,
clear=True, colors=None, axes=None, title=None):
"""Create a 2D map from several datasets.
An example::
mapping("h", "E", datas)
:param minmax: tuple of minimum and maximum value for z-scale
:param mode: 0 = image, 1 = contour filled, 2 = contour lines
:param log: True if the z-scale should be logarithmic
:param dots: whether to show dots on position of datapoints
:param xscale, yscale: to define scale between x and y axis
:param interpolate: number of points to interpolate in between points
:param usemask: True if masked out points should be removed
:param figure: where to plot, default is current figure (``pl.gcf()``)
:param clear: whether to do ``figure.clf()`` before plotting
:param colors: when using mode > 1, optional list of colors for plotting
:param axes: axes where to plot, default is figure.gca()
:param title: title of the plot
"""
return mapping(x, y, runs, minmax, mode, log, dots,
xscale, yscale, interpolate, usemask, figure,
clear, colors, axes, title)
| McStasMcXtrace/ufit | ufit/data/__init__.py | __init__.py | py | 5,990 | python | en | code | 1 | github-code | 13 |
4534603079 | #!/usr/bin/env python3
# reTxt.py - searches all .txt files in the current working directory
# for a user supplies regualer expression
import sys, re, os
from pathlib import Path
# Make regex from supplied string
sRegex = re.compile(sys.argv[1])
p = Path.cwd()
fileList = list(p.glob('*.txt'))
# Go trhough each file line by line and print matching ones
for item in fileList:
fileName = os.path.basename(item)
currentFile = open(fileName, 'r')
for line in currentFile:
if sRegex.search(line):
print(line)
currentFile.close()
| sbackon/Boring_Stuff | Boring_Stuff_9/Practice_Projects/reTxt.py | reTxt.py | py | 577 | python | en | code | 0 | github-code | 13 |
5104153983 | import numpy as np
import pandas as pd
import datajoint as dj
from ...common.common_nwbfile import AnalysisNwbfile
from ...utils.dj_helper_fn import fetch_nwb
from .position_dlc_pose_estimation import DLCPoseEstimation # noqa: F401
from .position_dlc_position import DLCSmoothInterp
schema = dj.schema("position_v1_dlc_cohort")
@schema
class DLCSmoothInterpCohortSelection(dj.Manual):
"""
Table to specify which combination of bodyparts from DLCSmoothInterp
get combined into a cohort
"""
definition = """
dlc_si_cohort_selection_name : varchar(120)
-> DLCPoseEstimation
---
bodyparts_params_dict : blob # Dict with bodypart as key and desired dlc_si_params_name as value
"""
@schema
class DLCSmoothInterpCohort(dj.Computed):
"""
Table to combine multiple bodyparts from DLCSmoothInterp
to enable centroid/orientation calculations
"""
# Need to ensure that nwb_file_name/epoch/interval list name endure as primary keys
definition = """
-> DLCSmoothInterpCohortSelection
---
"""
class BodyPart(dj.Part):
definition = """
-> DLCSmoothInterpCohort
-> DLCSmoothInterp
---
-> AnalysisNwbfile
dlc_smooth_interp_position_object_id : varchar(80)
dlc_smooth_interp_info_object_id : varchar(80)
"""
def fetch_nwb(self, *attrs, **kwargs):
return fetch_nwb(
self,
(AnalysisNwbfile, "analysis_file_abs_path"),
*attrs,
**kwargs,
)
def fetch1_dataframe(self):
nwb_data = self.fetch_nwb()[0]
index = pd.Index(
np.asarray(
nwb_data["dlc_smooth_interp_position"]
.get_spatial_series()
.timestamps
),
name="time",
)
COLUMNS = [
"video_frame_ind",
"x",
"y",
]
return pd.DataFrame(
np.concatenate(
(
np.asarray(
nwb_data["dlc_smooth_interp_info"]
.time_series["video_frame_ind"]
.data,
dtype=int,
)[:, np.newaxis],
np.asarray(
nwb_data["dlc_smooth_interp_position"]
.get_spatial_series()
.data
),
),
axis=1,
),
columns=COLUMNS,
index=index,
)
def make(self, key):
from .dlc_utils import OutputLogger, infer_output_dir
output_dir = infer_output_dir(key=key, makedir=False)
with OutputLogger(
name=f"{key['nwb_file_name']}_{key['epoch']}_{key['dlc_model_name']}_log",
path=f"{output_dir.as_posix()}/log.log",
print_console=False,
) as logger:
logger.logger.info("-----------------------")
logger.logger.info("Bodypart Cohort")
# from Jen Guidera
self.insert1(key)
cohort_selection = (DLCSmoothInterpCohortSelection & key).fetch1()
table_entries = []
bodyparts_params_dict = cohort_selection.pop(
"bodyparts_params_dict"
)
temp_key = cohort_selection.copy()
for bodypart, params in bodyparts_params_dict.items():
temp_key["bodypart"] = bodypart
temp_key["dlc_si_params_name"] = params
table_entries.append((DLCSmoothInterp & temp_key).fetch())
assert len(table_entries) == len(
bodyparts_params_dict
), "more entries found in DLCSmoothInterp than specified in bodyparts_params_dict"
table_column_names = list(table_entries[0].dtype.fields.keys())
for table_entry in table_entries:
entry_key = {
**{
k: v for k, v in zip(table_column_names, table_entry[0])
},
**key,
}
DLCSmoothInterpCohort.BodyPart.insert1(
entry_key, skip_duplicates=True
)
logger.logger.info("Inserted entry into DLCSmoothInterpCohort")
| LorenFrankLab/spyglass | src/spyglass/position/v1/position_dlc_cohort.py | position_dlc_cohort.py | py | 4,503 | python | en | code | 49 | github-code | 13 |
18796507031 | import pandas as pd
import os
import pickle
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn import tree
# from catboost import CatBoostClassifier
from sklearn.svm import SVC
# single flexible function to train different model types with different features
def train_model(model_name, features_name, custom_features=None, input_labels=None):
EMOTICONS_PUNCTUATION = os.path.abspath(
'Features\\Emoticons_Exclamation.pkl')
IDF_Pickle = os.path.abspath('Features\\idf.pkl')
if input_labels is None:
train_path = "MultiClass_Train.csv"
train_set = pd.read_csv(train_path, sep=',', encoding='utf-8')
all_labels = train_set["Labels"].tolist()
labels = []
for i in range(len(all_labels)):
if 'NORMAL' in list(all_labels)[i]:
labels.append("NORMAL")
else:
labels.append("TOXIC")
else:
labels = input_labels
print("Labels ready")
if features_name.lower() == "idf":
idf_path = IDF_Pickle
features = pd.read_pickle(idf_path)
print("Features: idf")
elif features_name.lower() == "emoticons":
features_path = EMOTICONS_PUNCTUATION
features = pd.read_pickle(features_path)
features = features.drop(columns=['Emoticons', 'Question Marks', 'Exclamation Marks', 'Expressive Punctuation'])
print("Features: emoticons")
elif features_name.lower() == "punctuation":
features_path = EMOTICONS_PUNCTUATION
features = pd.read_pickle(features_path)
features = features[['Question Marks', 'Exclamation Marks', 'Expressive Punctuation']]
print("Features: punctuation")
elif features_name.lower() == "all":
idf_path = IDF_Pickle
idf_features_df = pd.read_pickle(idf_path)
features_path = EMOTICONS_PUNCTUATION
add_features_df = pd.read_pickle(features_path)
features = pd.concat([idf_features_df, add_features_df.drop(columns=['Emoticons'])], axis=1)
print("Features: all")
else:
features = custom_features
if model_name.lower() == "rfm":
model = RandomForestClassifier(random_state=0)
print("Model: Random Forest")
# model = RandomForestClassifier(max_depth=10, random_state=0)1
elif model_name.lower() == "logreg":
model = LogisticRegression()
print("Model: Logistic Regression")
# support vector machines take too long to train, >24 hours
# elif model_name.lower() == "svc" or model_name.lower == "support vector":
# model = SVC(kernel="linear")
# print("Model: Support Vector Classifier")
elif model_name.lower() == "dtree" or model_name.lower() == "decision tree":
model = tree.DecisionTreeClassifier()
print("Model: Decision Tree")
elif model_name.lower() == "catboost":
# model = CatBoostClassifier()
print("Model: Catboost")
model.fit(features, labels)
print("Model trained")
path = f"Models\\BinaryClass_{model_name}_{features_name}.pkl"
with open(path, 'wb') as file:
pickle.dump(model, file)
print("Model saved")
print("Done")
# train_model(model_name="",features_name = "", custom_features=None, labels=None)
models_list = ["rfm", "logreg", "catboost" , "dtree"]
features_list = ["idf", "punctuation", "emoticons", "all",]
models_list = ["dtree"]
features_list = ["all"]
# prepare label data
train_path = "MultiClass_Train.csv"
train_set = pd.read_csv(train_path, sep=',', encoding='utf-8')
all_labels = train_set["Labels"].tolist()
labels = []
for i in range(len(all_labels)):
if 'NORMAL' in list(all_labels)[i]:
labels.append("NORMAL")
else:
labels.append("TOXIC")
# train all
for modeltype in models_list:
for featuretype in features_list:
train_model(model_name=modeltype, features_name=featuretype, input_labels=labels)
print(f"Model trained with algorithm:{modeltype} and features: {featuretype}")
# Enable all code below for training a custom model with selective features
'''print("Reading previous models")
rfm_model = pandas.read_pickle("Models\\BinaryClass_rfm_all.pkl")
logreg_model = pandas.read_pickle("Models\\BinaryClass_logreg_all.pkl")
idf2_features_df = pd.read_pickle('Features\\idf.pkl')
add2_features_df = pd.read_pickle('Features\\Emoticons_Exclamation.pkl')
all_features = pd.concat([idf2_features_df, add2_features_df.drop(columns=['Emoticons'])], axis=1)
def evaluate_features(model, features, model_type):
feature_list = list(features.columns)
indexes = []
importances = []
counter = 0
if model_type.lower() == "rfm" or model_type.lower() == "random forest":
for item in model.feature_importances_:
if abs(item) > 0.0003:
indexes.append(counter)
importances.append(item)
counter += 1
elif model_type.lower() == "logreg" or model_type.lower() == "logistic regression":
for item in list(model.coef_[0]):
if abs(item) > 1.5:
indexes.append(counter)
importances.append(item)
counter += 1
usefull_features = []
for item in indexes:
usefull_features.append(feature_list[item])
#print(len(usefull_features))
#for i in range(len(usefull_features)):
# print(usefull_features[i], importances[i])
return usefull_features, importances
print("Checking feature coefs")
# select the best logreg features
selected_logreg_features, logreg_importances = evaluate_features(model=logreg_model, features=all_features,
model_type='logreg')
# select the best random forest features
selected_rfm_features, rfm_importances = evaluate_features(model=rfm_model, features=all_features,
model_type='rfm')
# combine the features and cast them into a set to get rid of duplicates
collective_features = set(selected_rfm_features + selected_logreg_features)
selected_features = all_features[list(collective_features)]
print("Combined features")
# train a new random forest and logistic regression model with the combined set of useful features
#train_model("rfm","selected_collective", custom_features=selected_features, input_labels=None)
#train_model("logreg","selected_collective", custom_features=selected_features, input_labels=None)
train_model("svc","selected_collective", custom_features=selected_features, input_labels=None)'''
| aMala3/RussianToxic | Train_BinaryClass.py | Train_BinaryClass.py | py | 6,589 | python | en | code | 0 | github-code | 13 |
41612839551 | import pytest
from tsp import Place, Tour
def test_tour_cost(tsp_obj, tour_obj):
assert [tsp_obj.cost(current, next)
for current, next in tour_obj] == [3, 6, 5, 8, 7]
assert tsp_obj.total_cost(tour_obj) == 29
def test_tsp_creation(tsp_obj):
assert Place(0, 0, 0) == tsp_obj.places[0] and \
Place(1, 1, 0) == tsp_obj.places[1] and \
Place(2, 0, 1) == tsp_obj.places[2] and \
Place(3, 1, 1) == tsp_obj.places[3] and \
Place(4, 2, 3) == tsp_obj.places[4]
def test_missing_places(tsp_obj):
t1 = Tour()
t2 = Tour()
t1.append(places['A'])
t1.append(places['B'])
t1.append(places['C'])
t2.append(places['D'])
assert t1.missing(places.values()) == set(t2._path)
| Carlosrlpzi/tsp_ | tests/test_tsp.py | test_tsp.py | py | 746 | python | en | code | 0 | github-code | 13 |
26993679470 | #https://assinaturas.superlogica.com/hc/pt-br/articles/360008275514-Integra%C3%A7%C3%B5es-via-API
import sys
import re
from datetime import date, timedelta, datetime
import threading
from service.clientRestService import ClientRestService
from service.metricasRestService import MetricasRestService
from dao.clientDao import ClienteDao
from dao.metricasDao import MetricasDao
class job:
# Define o número de jobs iniciais sendo:
# Número de threads iniciais x número de chamadas por endpoint (cada endpoint tem uma thread)
# Aumentar com cautela para evitar sobrecarga e travamentos no banco e servidor
threadLimiter = threading.BoundedSemaphore(2)
# Construtor
def __init__(self):
print('Iniciando o Job')
# Realiza o processamento dos clientes
def processar(self, data_exec):
print ('Iniciando o processamento para período ' + data_exec)
metricasDao = MetricasDao()
metricasDao.limpar_tabelas(data_exec)
clientesDao = ClienteDao()
clientesDao.limpar_tabelas(data_exec)
chamadas = [self._processar_metricas, self._processa_clientes_adimplentes, self._processa_clientes_inadimplentes]
threads = []
for metodo in chamadas:
t = threading.Thread(target=metodo, args=(data_exec,))
threads.append(t)
t.start()
def _processar_metricas(self, data_exec):
metricas = ''
print('Obtendo as métricas...')
#criando um objeto MetricasDao
dao = MetricasDao()
dao.limpar_tabelas(data_exec)
# criando um objeto MetricasRestServices
service = MetricasRestService()
# Obtendo sa métrica na superlógica
metricas = service.get_metricas(data_exec)
for metrica in metricas:
#Salvando no banco de dados
dao.incluir_metrica(metrica, data_exec)
# Processa os clientes adimplentes
def _processa_clientes_adimplentes(self, data_exec):
clientesAdimplentes = []
print('Obtendo os adimplentes...')
# criando um objeto ClienteDao
dao = ClienteDao()
# criando um objeto ClienteRestService
service = ClientRestService()
condicao = True
pagina = 0
# Enquanto retornar 150 clientes
while (condicao):
print('Requisitando...')
pagina += 1
aux = service.get_clientes_adimplentes(pagina, data_exec)
clientesAdimplentes += aux
condicao = (len(aux) == 150)
print('Na pagina ' + str(pagina) + ' obteve ' + str(len(aux)) + ' clientes adimplentes')
print('Existem ' + str(len(clientesAdimplentes)) + ' adimplentes para inserir')
for cliente in clientesAdimplentes:
dao.incluir_cliente_adimplente(cliente, data_exec)
# Processa os clientes inadimplentes
def _processa_clientes_inadimplentes(self, data_exec):
clientes_inadimplentes = []
print('Obtendo os inadimplentes...')
# criando um objeto ClienteDao
dao = ClienteDao()
# criando um objeto ClienteRestService
service = ClientRestService()
condicao = True
pagina = 0
# Enquanto retornar 150 clientes
while (condicao):
print('Requisitando...')
pagina += 1
aux = service.get_clientes_inadimplentes(pagina, data_exec)
clientes_inadimplentes += aux
condicao = (len(aux) == 150)
print('Na pagina ' + str(pagina) + ' obteve ' + str(len(aux)) + ' clientes inadimplentes')
print('Existem ' + str(len(clientes_inadimplentes)) + ' inadimplentes para inserir')
for cliente in clientes_inadimplentes:
dao.incluir_cliente_inadimplente(cliente, data_exec)
for recebimento in cliente['recebimento']:
dao.incluir_recebimentos_pendentes(recebimento, cliente['id_sacado_sac'], data_exec)
for encargo in recebimento['encargos']:
dao.incluir_encargos_recebimentos(encargo, recebimento['id_recebimento_recb'], data_exec)
# Semaforo para controlar o numero de threads ativas por periodo
def _run(self, data_exec):
self.threadLimiter.acquire()
try:
print('>>>> Thread ' + str(data_exec) + ' Iniciada')
self.processar(str(data_exec))
finally:
print('>>>> Thread Liberada')
self.threadLimiter.release()
# Cria as threads
def _create_threads(self, periodo):
for data_exec in periodo:
t = threading.Thread(target=self._run, args=(data_exec,))
t.start()
#Inicio
if __name__ == "__main__":
periodo = []
DATE_PATTERN = '%m/%d/%Y'
#Obtém data passada por parâmetro
parametros = sys.argv
#Se passou apenas uma data
if (len(parametros) == 2):
periodo.append(datetime.strptime(str(parametros[1]), DATE_PATTERN))
#Se passou um periodo
elif (len(parametros) == 3):
data_inicial = datetime.strptime(str(parametros[1]), DATE_PATTERN)
data_final = datetime.strptime(str(parametros[2]), DATE_PATTERN)
# Popula o array com o range de datas
periodo = [ data_inicial + timedelta(n) for n in range(int ((data_final - data_inicial).days))]
else:
periodo.append(date.today().strftime(DATE_PATTERN))
#Inicia o processo
job()._create_threads(periodo)
| prgmw/integracao | src/job.py | job.py | py | 5,494 | python | pt | code | 0 | github-code | 13 |
24418424026 | import pandas as pd
import openai
import tiktoken
import re
class AIDataAnalyzer:
'''
AIDA: Artificial Intelligence Data Analyzer
This class contains methods that uses the OpenAI API to analyze data.
The idea is as follows:
- The data are stored in a dataframe, which is passed to the class
- Thereafter, the user can call methods to analyze the data
- The analysis is done by consulting the OpenAI API for generating code, which is then executed
- The results are returned to the user
The class has several pre-specified methods for analyzing data, but the user can also give free text instructions
In essence, the class automates the process of typing a question "give me code for the following ..." into ChatGPT
and then copy-pasting the returned code into a Jupyter notebook
'''
def __init__(self, df, max_tokens=4000, temperature=0.2, api_key=None, api_key_filename=None, column_descriptions=None):
self.open_ai_api_key = self.set_openai_api_key(key=api_key, filename=api_key_filename)
self.df = df
self.column_descriptions = column_descriptions
self.max_tokens = max_tokens
self.temperature = temperature
self.comments = []
self.query_history = []
self.code_history = []
self.current_query = ""
# display a reminder to set openai key in case not set
print("Note: Beware that there may be security risks involved in executing AI-generated code. Use the 'query' function at own risk!")
if self.open_ai_api_key is None:
print("Note: No OpenAI API key has been set yet. Use set_openai_api_key() to set it.")
if self.column_descriptions is None:
print("Note: No column descriptions have been set, which may negatively affect the results. Use set_column_descriptions() to set them.")
def count_gpt_prompt_tokens(self, messages, model="gpt-3.5-turbo"):
'''Returns the number of tokens used by a list of messages.'''
try:
encoding = tiktoken.encoding_for_model(model)
except KeyError:
encoding = tiktoken.get_encoding("cl100k_base")
tokens_per_message = 3
tokens_per_name = 1
if model in ["gpt-3.5-turbo", "gpt-3.5-turbo-0301"]:
tokens_per_message = 4
tokens_per_name = -1
num_tokens = 0
for message in messages:
num_tokens += tokens_per_message
for key, value in message.items():
num_tokens += len(encoding.encode(value))
if key == "name":
num_tokens += tokens_per_name
num_tokens += 3 # every reply is primed with assistant
return num_tokens
def set_openai_api_key(self, key=None, filename=None):
'''Set the OpenAI API key. If a filename is provided, load the key from that file.'''
# if a filename is provided, load the key from that file
if filename is not None:
# load from specified file
try:
with open(filename, "r") as f:
self.open_ai_api_key = f.read()
except FileNotFoundError:
print(f"ERROR: could not find {filename}")
elif key is not None:
self.open_ai_api_key = key
else:
self.open_ai_api_key = None
if self.open_ai_api_key is not None:
# show a masked version of the open ai key (first 4 and last 4 characters, with . in between)
print(f"OpenAI API key was set to {self.open_ai_api_key[0:4]}....{self.open_ai_api_key[-4:]}")
def set_column_descriptions(self, descriptions):
'''Set the descriptions for the columns in the dataframe'''
for column in descriptions:
if column not in self.df.columns:
raise ValueError(f"The column '{column}' does not exist in the DataFrame.")
self.column_descriptions = descriptions
def get_python_code_from_openai(self, instruction, the_model = "gpt-3.5-turbo", verbose_level = 0, include_comments = True):
'''Send an instruction to the OpenAI API and return the Python code that is returned'''
# build system prompt
system_prompt = "You are a Python programming assistant\n"
system_prompt += "The user provides an instruction and you return Python code to achieve the desired result\n"
if include_comments:
system_prompt += "You document the code by adding comments\n"
else:
system_prompt += "You don't add comments to the code\n"
system_prompt += "You include all necessary imports\n"
system_prompt += "When displaying results in text form, you round to 3 decimals, unless specified otherwise\n"
system_prompt += "When creating plots, you always label the axes and include a legend, unless specified otherwise\n"
#system_prompt += "When creating plots in a loop, you organize them in 1 figure with 3 plots per row, unless specified otherwise\n"
system_prompt += "It is very important that you start each piece of code in your response with [code] and end it with [/code]\n"
system_prompt += "Assume that the dataframe uses named labels for columns, not integer indices.\n"
system_prompt += "You can make use of IPython Markdown to beautify the outputs\n"
system_prompt += "Here is an example of how to make a correlation heatmap: mask = np.triu(np.ones_like(correlation_matrix, dtype=bool)), heatmap = sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', mask=mask, ax=axs[0], annot_kws={'size': 18})\n"
# build user prompt
user_prompt = ""
user_prompt += "I would like your help with data analysis.\n"
user_prompt += "The data consists of the following columns:\n"
for col in self.column_descriptions:
user_prompt += f"# {col}: {self.column_descriptions[col]}\n"
if len(self.comments) > 0:
user_prompt += "Here are some comments about the data and your task:\n"
for comment in self.comments:
user_prompt += f"# {comment}\n"
user_prompt += "Please complete the following code:\n\n"
user_prompt += "import pandas as pd\n"
user_prompt += "df = pd.read_csv('data.csv')\n"
user_prompt += "# " + instruction.replace("\n", "\n# ") + "\n\n"
#user_prompt += "Remember to organize plots in 1 figure with 3 plots per row when creating them in a loop\n"
user_prompt += "Remember that you must start each piece of code in your response with [code] and end it with [/code]\n"
user_prompt += "Remember to include all necessary imports\n"
user_prompt += "When you loop over df.columns, use cnt and col_idx as variable names\n"
user_prompt += "Never use 'col_idx' as a variable name for something else\n"
user_prompt += "When you compute the row or column for axs, call the variables subplot_row and subplot_col\n"
user_prompt += "Remember to remove unused subplots\n"
# build the message array for the request
msg_array = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
]
# count number of tokens in input
encoding = tiktoken.encoding_for_model("gpt-3.5-turbo")
encoding.encode(user_prompt)
# perform the request
openai.api_key = self.open_ai_api_key
response = openai.ChatCompletion.create(
model=the_model,
messages=msg_array,
max_tokens=self.max_tokens - self.count_gpt_prompt_tokens(msg_array, model=the_model),
temperature=self.temperature,
)
# process the response
token_cnt = response['usage']['total_tokens']
content = response['choices'][0]['message']['content']
code = re.findall(r'\[code\](.*?)\[\/code\]', content, re.DOTALL)
code = "\n".join(code)
# remove any lines that in which read_csv is called
code = "\n".join([line for line in code.split("\n") if "read_csv" not in line])
code = "\n".join([line for line in code.split("\n") if "# read the data" not in line])
# add "import pandas as pd" if it is not already there
if not "import pandas" in code:
code = "import pandas as pd\n" + code
# make sure that display and MarkDown are imported if Markdown appears anywhere in the code:
if "Markdown" in code:
code = "from IPython.display import display, Markdown\n" + code
# print content and nr of tokens in prompt as counted and as reported by OpenAI
if verbose_level > 1:
print(f"Total tokens: {token_cnt}")
print(f"Content: {content}")
print(f"Number of tokens in prompt: {self.count_gpt_prompt_tokens(msg_array, model=the_model)}")
print(f"Number of tokens reported by OpenAI: {response['usage']['prompt_tokens']}")
return code
def build_query(self, new_line):
'''Add a line to the current query'''
self.current_query += new_line + "\n"
def reset_query(self):
'''Reset the current query'''
self.current_query = ""
def show_query(self):
'''Print the current query'''
print(self.current_query)
def execute_query(self, run_code = True, verbose_level = 0):
'''Execute a free text instruction'''
self.query_history.append(self.current_query)
print("Query was submitted. Waiting for response...")
code = self.get_python_code_from_openai(self.current_query, verbose_level = verbose_level, include_comments = (not run_code) or (verbose_level > 0))
print("\nReturned code:")
print("--------------------------------------------------------------------------")
print(code.strip("\n"))
print("--------------------------------------------------------------------------")
self.code_history.append(code)
if run_code:
print("\nExecuting the code...\n")
try:
namespace = {'df': self.df}
exec(code, namespace)
except Exception as e:
print(f"Error executing code: {str(e)}")
self.current_query = ""
#------------ comments -----------#
def add_comment(self, comment):
'''Add a comment to the list of comments unless it is already in there'''
if comment not in self.comments:
self.comments.append(comment)
def show_comments(self):
'''Print all comments'''
cnt=0
for comment in self.comments:
print(f"[{cnt}] {comment}")
cnt += 1
def delete_comment(self, comment_nr):
'''Delete a comment'''
if comment_nr == -1:
self.comments = []
if comment_nr < len(self.comments):
del self.comments[comment_nr]
#------------ query history -----------#
def show_query_history(self):
'''Print the query history'''
cnt=0
for query in self.query_history:
print(f"[{cnt}] {query}")
cnt += 1
def show_code_history(self):
'''Print the code history'''
cnt=0
for code in self.code_history:
print(f"\n[{cnt}]\n{code}")
cnt += 1
| nronaldvdberg/integrify | ronaldlib/ronaldlib/aida.py | aida.py | py | 11,489 | python | en | code | 0 | github-code | 13 |
43581470136 | #!/usr/bin/env python2.7
import kivy
kivy.require('1.7.2')
from kivy.app import App
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from plyer import notification
__version__ = '0.1'
class Playground(BoxLayout):
def _do_notify(self,
title="Default Title",
message="This is the default message."):
notification.notify(title, message)
class PlaygroundApp(App):
def build(self):
return Playground()
if __name__ == '__main__':
PlaygroundApp().run()
| brousch/playground | playground/main.py | main.py | py | 585 | python | en | code | 2 | github-code | 13 |
37005323970 | import torch
import torch.nn as nn
from functools import partial
from timm.models.cait import default_cfgs, checkpoint_filter_fn
from timm.models.registry import register_model
from timm.models.layers import trunc_normal_, Mlp, PatchEmbed
from timm.models.helpers import *
def _create_cait(variant, pretrained=False, **kwargs):
if kwargs.get('features_only', None):
raise RuntimeError('features_only not implemented for Vision Transformer models.')
model = build_model_with_cfg(
Cait, variant, pretrained,
default_cfg=default_cfgs[variant],
pretrained_filter_fn=checkpoint_filter_fn,
**kwargs)
return model
class ClassAttn(nn.Module):
# taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
# with slight modifications to do CA
def __init__(self, dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0.):
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
self.scale = head_dim ** -0.5
self.q = nn.Linear(dim, dim, bias=qkv_bias)
self.k = nn.Linear(dim, dim, bias=qkv_bias)
self.v = nn.Linear(dim, dim, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x, global_attn = None):
B, N, C = x.shape # 8,197,384
q = self.q(x[:, 0]).unsqueeze(1).reshape(B, 1, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) # batchsize, heads, 1, 48
k = self.k(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) # batchsize, heads, 197, 48
q = q * self.scale
v = self.v(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) # batchsize, heads, 197, 48
attn = (q @ k.transpose(-2, -1)) # batchsize, heads, 1,197
attn = attn.softmax(dim=-1)
if global_attn != None:
tradeoff = 0.9
attn = tradeoff * attn + (1-tradeoff) * global_attn
attn = self.attn_drop(attn)
x_cls = (attn @ v).transpose(1, 2).reshape(B, 1, C) # batchsize, heads,1,48 --> batchsize, 1, 384
x_cls = self.proj(x_cls) # 8,1,384
x_cls = self.proj_drop(x_cls)
return x_cls, attn
class LayerScaleBlockClassAttn(nn.Module):
# taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
# with slight modifications to add CA and LayerScale
def __init__(
self, dim, num_heads, mlp_ratio=4., qkv_bias=False, drop=0., attn_drop=0.,
drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, attn_block=ClassAttn,
mlp_block=Mlp, init_values=1e-4):
super().__init__()
self.norm1 = norm_layer(dim)
self.attn = attn_block(
dim, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop) # bs,1,384
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = mlp_block(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
self.gamma_1 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True)
self.gamma_2 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True)
def forward(self, x, x_cls, global_attn = None): # x_cls-->8,1,384
u = torch.cat((x_cls, x), dim=1)
x, attn = self.attn(self.norm1(u), global_attn)
x_cls = x_cls + self.drop_path(self.gamma_1 * x)
x_cls = x_cls + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x_cls)))
return x_cls, attn
class TalkingHeadAttn(nn.Module):
# taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
# with slight modifications to add Talking Heads Attention (https://arxiv.org/pdf/2003.02436v1.pdf)
def __init__(self, dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0.):
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads # 768 // 8 = 96
self.scale = head_dim ** -0.5 # 1/根号96
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_l = nn.Linear(num_heads, num_heads)
self.proj_w = nn.Linear(num_heads, num_heads)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x, global_attn = None):
B, N, C = x.shape # 4,196,384
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0] * self.scale, qkv[1], qkv[2] # 4,8,196,48
attn = (q @ k.transpose(-2, -1)) # 4,8,196,196
attn = self.proj_l(attn.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
attn = attn.softmax(dim=-1) # 4,8,196,196
if global_attn != None:
tradeoff = 1.
attn = tradeoff * attn + (1-tradeoff) * global_attn
soft_attn = attn
attn = self.proj_w(attn.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C) # 4,8,196,48 reshape --> 4,196,384
x = self.proj(x)
x = self.proj_drop(x)
return x, soft_attn
class LayerScaleBlock(nn.Module):
# taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
# with slight modifications to add layerScale
def __init__(
self, dim, num_heads, mlp_ratio=4., qkv_bias=False, drop=0., attn_drop=0.,
drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, attn_block=TalkingHeadAttn,
mlp_block=Mlp, init_values=1e-4):
super().__init__()
self.norm1 = norm_layer(dim)
self.attn = attn_block(
dim, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = mlp_block(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
self.gamma_1 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True)
self.gamma_2 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True)
def forward(self, x, global_attn = None):
temp, attn = self.attn(self.norm1(x), global_attn)
x = x + self.drop_path(self.gamma_1 * temp)
x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x)))
return x, attn
class Cait(nn.Module):
# taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
# with slight modifications to adapt to our cait models
def __init__(
self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dim=768, depth=12,
num_heads=12, mlp_ratio=4., qkv_bias=True, drop_rate=0., attn_drop_rate=0.,
drop_path_rate=0.,
norm_layer=partial(nn.LayerNorm, eps=1e-6),
global_pool=None,
block_layers=LayerScaleBlock,
block_layers_token=LayerScaleBlockClassAttn,
patch_layer=PatchEmbed,
act_layer=nn.GELU,
attn_block=TalkingHeadAttn,
mlp_block=Mlp,
init_scale=1e-4,
attn_block_token_only=ClassAttn,
mlp_block_token_only=Mlp,
depth_token_only=2,
mlp_ratio_clstk=4.0
):
super().__init__()
self.num_classes = num_classes
self.num_features = self.embed_dim = embed_dim
self.patch_embed = patch_layer(
img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)
num_patches = self.patch_embed.num_patches
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim))
self.pos_drop = nn.Dropout(p=drop_rate)
dpr = [drop_path_rate for i in range(depth)]
self.blocks = nn.ModuleList([
block_layers(
dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias,
drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer,
act_layer=act_layer, attn_block=attn_block, mlp_block=mlp_block, init_values=init_scale)
for i in range(depth)])
self.blocks_token_only = nn.ModuleList([
block_layers_token(
dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio_clstk, qkv_bias=qkv_bias,
drop=0.0, attn_drop=0.0, drop_path=0.0, norm_layer=norm_layer,
act_layer=act_layer, attn_block=attn_block_token_only,
mlp_block=mlp_block_token_only, init_values=init_scale)
for i in range(depth_token_only)])
self.norm = norm_layer(embed_dim)
self.feature_info = [dict(num_chs=embed_dim, reduction=0, module='head')]
self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity()
trunc_normal_(self.pos_embed, std=.02)
trunc_normal_(self.cls_token, std=.02)
self.apply(self._init_weights)
def _init_weights(self, m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
@torch.jit.ignore
def no_weight_decay(self):
return {'pos_embed', 'cls_token'}
def get_classifier(self):
return self.head
def reset_classifier(self, num_classes, global_pool=''):
self.num_classes = num_classes
self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity()
def forward_features(self, x, global_attn = None):
B = x.shape[0]
x = self.patch_embed(x) # 8,196,384
cls_tokens = self.cls_token.expand(B, -1, -1) # 8,1,384
x = x + self.pos_embed
x = self.pos_drop(x)
patch_attns = []
cls_attns = []
for i, blk in enumerate(self.blocks):
if global_attn != None:
x, patch_attn = blk(x, global_attn[0][-1].detach())
else:
x, patch_attn = blk(x)
patch_attns.append(patch_attn)
for i, blk in enumerate(self.blocks_token_only):
if global_attn != None:
cls_tokens, cls_attn = blk(x, cls_tokens, global_attn[1][-1].detach())
else:
cls_tokens, cls_attn = blk(x, cls_tokens)
cls_attns.append(cls_attn)
x = torch.cat((cls_tokens, x), dim=1)
x = self.norm(x)
return x[:, 0], [patch_attns, cls_attns]
def forward(self, x, global_attn = None):
x, attns = self.forward_features(x, global_attn)
x = self.head(x)
return x, attns
# class MyCait(Cait):
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
# def forward_features(self, x):
# B = x.shape[0]
# x = self.patch_embed(x) # 8,196,384
# cls_tokens = self.cls_token.expand(B, -1, -1) # 8,1,384
# x = x + self.pos_embed
# x = self.pos_drop(x)
# layer_wise_tokens = []
# for i, blk in enumerate(self.blocks):
# x,_ = blk(x)
# # layer_wise_tokens.append(x)
# for i, blk in enumerate(self.blocks_token_only):
# cls_tokens,_ = blk(x, cls_tokens)
# # layer_wise_tokens.append(cls_tokens)
# # layer_wise_tokens = [self.norm(x) for x in layer_wise_tokens] # 8, 196, 384
# x = torch.cat((cls_tokens, x), dim=1)
# x = self.norm(x)
# return x[:, 0], layer_wise_tokens # layer_wise_tokens[-1].squeeze(dim = 1) == x[:, 0] 最后两层的cls_tocken都有判别性
# def forward(self, x):
# x, layer_wise_tokens = self.forward_features(x)
# x = self.head(x)
# # depth_token_only = len(self.blocks_token_only)
# # for i in range(len(layer_wise_tokens)-depth_token_only,len(layer_wise_tokens)):
# # layer_wise_tokens[i] = self.head(layer_wise_tokens[i]).squeeze(1)
# return x, layer_wise_tokens
# @register_model
def cait_xxs24_224(pretrained=False, **kwargs):
model_args = dict(patch_size=16, embed_dim=192, depth=24, num_heads=4, init_scale=1e-5, **kwargs)
model = _create_cait('cait_xxs24_224', pretrained=pretrained, **model_args)
return model
# @register_model
def cait_xxs24_384(pretrained=False, **kwargs):
model_args = dict(patch_size=16, embed_dim=192, depth=24, num_heads=4, init_scale=1e-5, **kwargs)
model = _create_cait('cait_xxs24_384', pretrained=pretrained, **model_args)
return model
# @register_model
def cait_xxs36_224(pretrained=False, **kwargs):
model_args = dict(patch_size=16, embed_dim=192, depth=36, num_heads=4, init_scale=1e-5, **kwargs)
model = _create_cait('cait_xxs36_224', pretrained=pretrained, **model_args)
return model
# @register_model
def cait_xxs36_384(pretrained=False, **kwargs):
model_args = dict(patch_size=16, embed_dim=192, depth=36, num_heads=4, init_scale=1e-5, **kwargs)
model = _create_cait('cait_xxs36_384', pretrained=pretrained, **model_args)
return model
# @register_model
def cait_xs24_384(pretrained=False, **kwargs):
model_args = dict(patch_size=16, embed_dim=288, depth=24, num_heads=6, init_scale=1e-5, **kwargs)
model = _create_cait('cait_xs24_384', pretrained=pretrained, **model_args)
return model
# @register_model
def cait_s24_224(pretrained=False, **kwargs):
model_args = dict(patch_size=16, embed_dim=384, depth=24, num_heads=8, init_scale=1e-5, **kwargs)
model = _create_cait('cait_s24_224', pretrained=pretrained, **model_args)
return model
# @register_model
def cait_s24_384(pretrained=False, **kwargs):
model_args = dict(patch_size=16, embed_dim=384, depth=24, num_heads=8, init_scale=1e-5, **kwargs)
model = _create_cait('cait_s24_384', pretrained=pretrained, **model_args)
return model
# @register_model
def cait_s36_384(pretrained=False, **kwargs):
model_args = dict(patch_size=16, embed_dim=384, depth=36, num_heads=8, init_scale=1e-6, **kwargs)
model = _create_cait('cait_s36_384', pretrained=pretrained, **model_args)
return model
# @register_model
def cait_m36_384(pretrained=False, **kwargs):
model_args = dict(patch_size=16, embed_dim=768, depth=36, num_heads=16, init_scale=1e-6, **kwargs)
model = _create_cait('cait_m36_384', pretrained=pretrained, **model_args)
return model
# @register_model
def cait_m48_448(pretrained=False, **kwargs):
model_args = dict(patch_size=16, embed_dim=768, depth=48, num_heads=16, init_scale=1e-6, **kwargs)
model = _create_cait('cait_m48_448', pretrained=pretrained, **model_args)
return model | tuoli9/GALD | vit_models/re_cait.py | re_cait.py | py | 15,467 | python | en | code | 0 | github-code | 13 |
38462179659 | """Test PyDynamic.uncertainty.propagate_DFT.DFT_deconv"""
from typing import Callable, cast, Dict, Tuple
import numpy as np
import pytest
import scipy.stats as stats
from hypothesis import given, HealthCheck, settings
from hypothesis.strategies import composite, DrawFn, SearchStrategy
from numpy.testing import assert_allclose
from PyDynamic.uncertainty.propagate_DFT import DFT_deconv
from .conftest import (
hypothesis_covariance_matrix_for_complex_vectors,
hypothesis_float_vector,
hypothesis_nonzero_complex_vector,
hypothesis_positive_powers_of_two,
)
@composite
def deconvolution_input(
draw: DrawFn, reveal_bug: bool = False
) -> SearchStrategy[Dict[str, np.ndarray]]:
n = draw(hypothesis_positive_powers_of_two(min_k=2, max_k=4))
if reveal_bug:
y = np.r_[
draw(hypothesis_float_vector(length=n, min_value=0.5, max_value=1.0)),
np.zeros(n),
]
uy = np.eye(N=n * 2)
h = np.r_[
draw(hypothesis_float_vector(length=n, min_value=0.5, max_value=1.0)),
draw(hypothesis_float_vector(length=n, min_value=1000.0, max_value=1001.0)),
]
uh = np.eye(N=n * 2)
else:
covariance_bounds = {"min_value": 1e-17, "max_value": 1e-11}
vector_magnitude_bounds = {"min_magnitude": 1e-2, "max_magnitude": 1e2}
y_complex = draw(
hypothesis_nonzero_complex_vector(length=n, **vector_magnitude_bounds)
)
y = np.r_[y_complex.real, y_complex.imag]
uy = draw(
hypothesis_covariance_matrix_for_complex_vectors(
length=n, **covariance_bounds
)
)
h_complex = draw(
hypothesis_nonzero_complex_vector(length=n, **vector_magnitude_bounds)
)
h = np.r_[h_complex.real, h_complex.imag]
uh = draw(
hypothesis_covariance_matrix_for_complex_vectors(
length=n, **covariance_bounds
),
)
return cast(
SearchStrategy[Dict[str, np.ndarray]], {"Y": y, "UY": uy, "H": h, "UH": uh}
)
@given(deconvolution_input())
@settings(
deadline=None,
suppress_health_check=[
*settings.default.suppress_health_check,
HealthCheck.too_slow,
],
max_examples=100,
)
@pytest.mark.slow
def test_dft_deconv(
multivariate_complex_monte_carlo, complex_deconvolution_on_sets, DFT_deconv_input
):
x_deconv, u_deconv = DFT_deconv(**DFT_deconv_input)
n_monte_carlo_runs = 40000
monte_carlo_mean, monte_carlo_cov = multivariate_complex_monte_carlo(
vectors=(DFT_deconv_input["Y"], DFT_deconv_input["H"]),
covariance_matrices=(DFT_deconv_input["UY"], DFT_deconv_input["UH"]),
n_monte_carlo_runs=n_monte_carlo_runs,
operator=complex_deconvolution_on_sets,
)
x_deconv_shift_away_from_zero = 1 - np.min(x_deconv)
u_deconv_shift_away_from_zero = 1 - np.min(u_deconv)
assert_allclose(
x_deconv + x_deconv_shift_away_from_zero,
monte_carlo_mean + x_deconv_shift_away_from_zero,
rtol=6.8e-2,
)
assert_allclose(
u_deconv + u_deconv_shift_away_from_zero,
monte_carlo_cov + u_deconv_shift_away_from_zero,
rtol=4.98e-1,
)
@pytest.fixture(scope="module")
def multivariate_complex_monte_carlo(
_monte_carlo_samples_for_several_vectors,
_mean_of_multivariate_monte_carlo_samples,
_covariance_of_multivariate_monte_carlo_samples,
):
def _perform_multivariate_complex_monte_carlo(
vectors: Tuple[np.ndarray, np.ndarray],
covariance_matrices: Tuple[np.ndarray, np.ndarray],
n_monte_carlo_runs: int,
operator: Callable,
):
vectors_monte_carlo_samples = _monte_carlo_samples_for_several_vectors(
vectors=vectors,
covariance_matrices=covariance_matrices,
n_monte_carlo_runs=n_monte_carlo_runs,
)
vectors_monte_carlo_samples_after_applying_operator = operator(
*vectors_monte_carlo_samples
)
monte_carlo_samples_mean = _mean_of_multivariate_monte_carlo_samples(
vectors_monte_carlo_samples_after_applying_operator
)
monte_carlo_samples_cov = _covariance_of_multivariate_monte_carlo_samples(
vectors_monte_carlo_samples_after_applying_operator
)
return monte_carlo_samples_mean, monte_carlo_samples_cov
return _perform_multivariate_complex_monte_carlo
@pytest.fixture(scope="module")
def _monte_carlo_samples_for_several_vectors():
def _draw_monte_carlo_samples_for_several_vectors(
vectors: Tuple[np.ndarray, ...],
covariance_matrices: Tuple[np.ndarray, ...],
n_monte_carlo_runs: int,
) -> Tuple[np.ndarray, ...]:
tuple_of_monte_carlo_samples_for_several_vectors = tuple(
stats.multivariate_normal.rvs(
mean=vector, cov=covariance_matrix, size=n_monte_carlo_runs
)
for vector, covariance_matrix in zip(vectors, covariance_matrices)
)
return tuple_of_monte_carlo_samples_for_several_vectors
return _draw_monte_carlo_samples_for_several_vectors
@pytest.fixture(scope="module")
def complex_deconvolution_on_sets():
def _perform_complex_deconvolution_on_sets(
y_mcs_complex: np.ndarray, h_mcs_complex: np.ndarray
):
real_imag_divider = y_mcs_complex.shape[1] // 2
y_mcs = (
y_mcs_complex[..., :real_imag_divider]
+ 1j * y_mcs_complex[..., real_imag_divider:]
)
h_mcs = (
h_mcs_complex[..., :real_imag_divider]
+ 1j * h_mcs_complex[..., real_imag_divider:]
)
y_mcs_divided_by_h_mcs_complex = y_mcs / h_mcs
y_mcs_divided_by_h_mcs = np.concatenate(
(
np.real(y_mcs_divided_by_h_mcs_complex),
np.imag(y_mcs_divided_by_h_mcs_complex),
),
axis=1,
)
return y_mcs_divided_by_h_mcs
return _perform_complex_deconvolution_on_sets
@pytest.fixture(scope="module")
def _mean_of_multivariate_monte_carlo_samples():
def _compute_mean_of_multivariate_monte_carlo_samples(
monte_carlo_samples: np.ndarray,
):
y_divided_by_h_mc_mean = np.mean(monte_carlo_samples, axis=0)
return y_divided_by_h_mc_mean
return _compute_mean_of_multivariate_monte_carlo_samples
@pytest.fixture(scope="module")
def _covariance_of_multivariate_monte_carlo_samples():
def _compute_covariance_of_multivariate_monte_carlo_samples(
monte_carlo_samples: np.ndarray,
):
y_divided_by_h_mc_cov = np.cov(monte_carlo_samples, rowvar=False)
return y_divided_by_h_mc_cov
return _compute_covariance_of_multivariate_monte_carlo_samples
@given(deconvolution_input(reveal_bug=True))
@settings(deadline=None)
@pytest.mark.slow
def test_reveal_bug_in_dft_deconv_up_to_1_9(
multivariate_complex_monte_carlo, complex_deconvolution_on_sets, DFT_deconv_input
):
# Fix a bug discovered by partners of Volker Wilkens. The bug and the process of
# fixing it was processed and thus is documented in PR #220:
# https://github.com/PTB-M4D/PyDynamic/pull/220
u_deconv = DFT_deconv(**DFT_deconv_input)[1]
n_monte_carlo_runs = 2000
_, y_divided_by_h_mc_cov = multivariate_complex_monte_carlo(
vectors=(DFT_deconv_input["Y"], DFT_deconv_input["H"]),
covariance_matrices=(DFT_deconv_input["UY"], DFT_deconv_input["UH"]),
n_monte_carlo_runs=n_monte_carlo_runs,
operator=complex_deconvolution_on_sets,
)
assert_allclose(u_deconv + 1, y_divided_by_h_mc_cov + 1)
| Met4FoF/Code | PyDynamic/test/test_DFT_deconv.py | test_DFT_deconv.py | py | 7,674 | python | en | code | 0 | github-code | 13 |
16846945485 | import pickle
import copy
import pandas as pd
import spacy
nlp = spacy.load('en_core_web_sm')
import string
TAG2INDEX = '../tag2index.pickle'
ADJ_LIST = 'ED_adjacency_list.pickle'
WORDLIST = 'ED_wordlist.pickle'
INDEX2WORD = 'ED_index2word.pickle'
ED_DATA = 'mod_dataset.csv'
data = pd.read_csv(ED_DATA)
data = data.dropna()
tag2index = pickle.load(open(TAG2INDEX, 'rb'))
wordlist = pickle.load(open(WORDLIST, 'rb'))
index2word = pickle.load(open(INDEX2WORD, 'rb'))
adj = pickle.load(open(ADJ_LIST, 'rb'))
def get_pos_seq(sent):
index = len(wordlist.keys())
sent = nlp(sent)
pos = []
for token in sent:
if token.lemma_ not in wordlist.keys():
if token.text in string.punctuation or token.text == '\'s' or token.text == '' or token.text == ' ':
continue
if token.is_stop:
continue
wordlist[token.lemma_] = index
index2word[index] = token.lemma_
adj[index] = []
index += 1
pos.append(str(tag2index[token.tag_]))
return ' '.join(pos)
def get_index_seq(sent):
sent = nlp(sent)
lst = []
for token in sent:
if token.lemma_ not in wordlist.keys():
lst.append(0)
else:
lst.append(wordlist[token.lemma_])
return ' '.join([str(item) for item in lst])
def update_pos_seq(seq):
seq = [str(int(val)+1) for val in seq.split()]
return ' '.join(seq)
def logged_apply(g, func, *args, **kwargs):
"""
func - function to apply to the dataframe
*args, **kwargs are the arguments to func
The method applies the function to all the elements of the dataframe and shows progress
"""
step_percentage = 100. / len(g)
import sys
print('\rApply progress: 0%', end = "")
sys.stdout.flush()
def logging_decorator(func):
def wrapper(*args, **kwargs):
progress = wrapper.count * step_percentage
#sys.stdout.write('\033[D \033[D' * 4 + format(progress, '3.0f') + '%')
print('\rApply progress: {prog}%'.format(prog=progress), end = "")
sys.stdout.flush()
wrapper.count += 1
return func(*args, **kwargs)
wrapper.count = 0
return wrapper
logged_func = logging_decorator(func)
res = g.apply(logged_func, *args, **kwargs)
print('\rApply progress: 1 00%', end = "")
sys.stdout.flush()
print('\n')
return res
print('columns of original data')
print(data.columns)
print('length of original wordlist:')
print(len(wordlist.keys()))
print('columns of modified data:')
#data['pos_seq'] = logged_apply(data['sentence'], get_pos_seq)
#data['word index seq'] = logged_apply(data['sentence'], get_index_seq)
data['pos_seq'] = logged_apply(data['pos_seq'], update_pos_seq)
print(data.columns)
print('length of modified wordlist:')
print(len(wordlist.keys()))
print('length of modified index2word list:')
print(len(index2word.keys()))
print('length of modified adjacency list:')
print(len(adj.keys()))
data.to_csv('updated_mod_dataset.csv', index = False)
#pickle.dump(wordlist, open('ED_wordlist.pickle', 'wb'))
#pickle.dump(index2word, open('ED_index2word.pickle', 'wb'))
#pickle.dump(adj, open('ED_adjacency_list.pickle', 'wb'))
| shandilya1998/CS6251-project | data/ED/data_prep.py | data_prep.py | py | 3,278 | python | en | code | 0 | github-code | 13 |
21021618546 | #!/usr/bin/env python
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('classic')
x = np.linspace(0, 10, 100)
fig = plt.figure()
plt.plot(x, np.sin(x), '-')
plt.plot(x, np.cos(x), '--')
fig.savefig('/home/tmp/0.0.png')
| bismog/leetcode | matplotlib/line000.0.py | line000.0.py | py | 283 | python | en | code | 0 | github-code | 13 |
27910546955 | class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
curr = 0
for i in range(1, len(nums)):
if nums[i] != nums[curr]:
nums[curr+1] = nums[i]
curr += 1
return curr+1 | JinhanM/leetcode-playground | 26. 删除排序数组中的重复项.py | 26. 删除排序数组中的重复项.py | py | 316 | python | en | code | 0 | github-code | 13 |
12343845135 | # Program for computing minimum operations required from moving 0 to N.
# We are allowed to use two operations :
# 1. Add 1 to the number
# 2. Double the number
# ---------------------------------------------------------------------------
# One of the observation is that minimum operations required from 0 -> N will be same as N -> 0.
# So, we can basically move from N -> 0, and divide and subtract (instead of add and multiply as from 0-> N).
# Now, we can think that if the number is even, then divide by 2, but if the number is odd, then we can subtract by 1 unit.
# In this way min number of operations are counted .
# ----------------------------------------------------------------------------
# TIME : 0(min_operations)
def compute_min_opr(N):
count = 0
while N:
if N & 1:
N -= 1
else:
N = N // 2
count += 1
return count
if __name__ == '__main__':
print(compute_min_opr(7))
| souravs17031999/100dayscodingchallenge | arrays/min_operations_N.py | min_operations_N.py | py | 950 | python | en | code | 43 | github-code | 13 |
37490231445 | #!/bin/python3
import sys
import csv
import os
import json
from optparse import OptionParser
from collections import OrderedDict
parser = OptionParser()
parser.add_option("-o",dest="output",help="output directory")
(options,args) = parser.parse_args()
outputDir = options.output
if not outputDir.endswith(os.sep):
outputDir = outputDir + os.sep
if len(args) == 0:
print("Gimme a fyl pliz")
exit(-1000)
print("Personne ne verra jamais ce message mwahaha")
for i in range(len(args)):
print (args[i])
csvFullPath = args[i]
csvDir,csvName = os.path.split(csvFullPath)
prefix,ext = os.path.splitext(csvName)
newCsv = list()
newJson = list()
with open(csvFullPath,'r') as csvFile:
reader = csv.reader(csvFile, delimiter=',')
oldX=-1
oldY=-1
for row in reader:
frame = row[0]
x = row[1]
y = row[2]
if x == oldX and y == oldY:
continue
newCsv.append(row)
newJson.append(OrderedDict([('frame',int(frame)), ('x',int(x)), ('y',int(y))]))
oldX = x
oldY = y
jsonName=prefix + ".json"
jsonFullPath = outputDir + jsonName
with open(jsonFullPath,'w+') as jsonFile:
print('writing',jsonFullPath)
json.dump(newJson,jsonFile)
# with open(csvName,"w+") as csvFile:
# writer = csv.writer(csvFile, delimiter=',')
# for row in newCsv:
# writer.writerow(row)
| gus3000/Transversal | Cpp/manual_tracking/python/simplifyCsv.py | simplifyCsv.py | py | 1,535 | python | en | code | 0 | github-code | 13 |
13514700106 | import os
import shutil
from copy import deepcopy
import mock
import unittest
from ebcli.operations import scaleops
from .. import mock_responses
class TestScaleOps(unittest.TestCase):
def setUp(self):
self.root_dir = os.getcwd()
if not os.path.exists('testDir'):
os.mkdir('testDir')
os.chdir('testDir')
def tearDown(self):
os.chdir(self.root_dir)
shutil.rmtree('testDir')
@mock.patch('ebcli.operations.scaleops.elasticbeanstalk.describe_configuration_settings')
@mock.patch('ebcli.operations.scaleops.elasticbeanstalk.update_environment')
@mock.patch('ebcli.operations.scaleops.commonops.wait_for_success_events')
def test_scale(
self,
wait_for_success_events_mock,
update_environment_mock,
describe_configuration_settings_mock
):
configuration_settings = deepcopy(
mock_responses.DESCRIBE_CONFIGURATION_SETTINGS_RESPONSE__2['ConfigurationSettings'][0]
)
namespace = 'aws:elasticbeanstalk:environment'
setting = next((n for n in configuration_settings['OptionSettings'] if n["Namespace"] == namespace), None)
setting['Value'] = 'LoadBalanced'
describe_configuration_settings_mock.return_value = configuration_settings
update_environment_mock.return_value = 'request-id'
scaleops.scale('my-application', 'environment-1', 3, 'y', timeout=10)
update_environment_mock.assert_called_once_with(
'environment-1',
[
{
'Namespace': 'aws:autoscaling:asg',
'OptionName': 'MaxSize',
'Value': '3'
},
{
'Namespace': 'aws:autoscaling:asg',
'OptionName': 'MinSize',
'Value': '3'
}
]
)
wait_for_success_events_mock.assert_called_once_with(
'request-id',
can_abort=True,
timeout_in_minutes=10
)
@mock.patch('ebcli.operations.scaleops.elasticbeanstalk.describe_configuration_settings')
@mock.patch('ebcli.operations.scaleops.elasticbeanstalk.update_environment')
@mock.patch('ebcli.operations.scaleops.commonops.wait_for_success_events')
@mock.patch('ebcli.operations.scaleops.io.get_boolean_response')
def test_scale__single_instance(
self,
get_boolean_response_mock,
wait_for_success_events_mock,
update_environment_mock,
describe_configuration_settings_mock
):
get_boolean_response_mock.return_value = True
describe_configuration_settings_mock.return_value = mock_responses.DESCRIBE_CONFIGURATION_SETTINGS_RESPONSE__2['ConfigurationSettings'][0]
update_environment_mock.return_value = 'request-id'
scaleops.scale('my-application', 'environment-1', 3, 'y', timeout=10)
update_environment_mock.assert_called_once_with(
'environment-1',
[
{
'Namespace': 'aws:elasticbeanstalk:environment',
'OptionName': 'EnvironmentType',
'Value': 'LoadBalanced'
},
{
'Namespace': 'aws:autoscaling:asg',
'OptionName': 'MaxSize',
'Value': '3'
},
{
'Namespace': 'aws:autoscaling:asg',
'OptionName': 'MinSize',
'Value': '3'
}
]
)
wait_for_success_events_mock.assert_called_once_with(
'request-id',
can_abort=True,
timeout_in_minutes=10
)
| aws/aws-elastic-beanstalk-cli | tests/unit/operations/test_scaleops.py | test_scaleops.py | py | 3,802 | python | en | code | 150 | github-code | 13 |
32039000245 | import os
import re
words = []
file = open('diccionario-hunspell.txt', "r", encoding="utf-8")
for line in file:
words.append(line.rstrip())
len(words)
file = open('../diccionario-rae-completo.txt', "r", encoding="utf-8")
for line in file:
words.append(line.rstrip())
cleanWords = []
for word in words:
if '/' in word:
cleanWords.append(word.split('/')[0])
else:
cleanWords.append(word)
len(words)
len(cleanWords)
cleanWords = sorted(cleanWords)
words = sorted(list(set(cleanWords)))
len(words)
with open('../diccionario-rae-completo.txt', mode='wt', encoding='utf-8') as file:
file.write('\n'.join(words))
| fvillena/palabras-diccionario-rae-completo | fuentes/fromHunspell.py | fromHunspell.py | py | 644 | python | en | code | 8 | github-code | 13 |
10031195834 | meses = int(input("Ingrese la cantidad de meses: "))
adultos = 2
recien_nacidas = 0
parejas = 1
for i in range(0, (meses+1)):
parejas = adultos // 2 #Esta division entera para saber cuantas parejas de adultos tenemos y por cada pareja de adultos se genera una nueva recien nacido
adultos = adultos + recien_nacidas
recien_nacidas = parejas
# print(f"{parejas}, {adultos}, {recien_nacidas}")
print(f"En {meses} meses a partir de una pareja de adultos, obtendra:"
f"\nParejas Adultas: {parejas}\nAdultos: {adultos}\nRecien Nacidos: {recien_nacidas}") | matiasnicolassanchez/Guia10LabComp | Ej 6.py | Ej 6.py | py | 595 | python | es | code | 0 | github-code | 13 |
21268936948 | import re
with open("altmir_hit.txt","a") as hit:
hit.write("mirid\tutr_chr\tutr_start-end\tutr_strand\thit_counts\n")
chit=0
with open("s1_miranda_altmir_res_02.txt") as res:
for line in res:
if line:
if line.startswith('Performing Scan:'):
mirid = line.split()[2]
sloc = line.split()[4]
hit.write(mirid+'\t')
scan = re.split(r':|\(|\)',sloc)
hit.write(scan[0]+'\t'+scan[1]+'\t'+scan[2]+'\t')
elif line.startswith('>'):
chit+=1
elif line.startswith('Complete'):
hit.write(str(chit-1)+'\n')
chit=0
# print(line)
| chunjie-sam-liu/miRNASNP-v3 | scr/target/miranda/s3_gethit.py | s3_gethit.py | py | 592 | python | en | code | 3 | github-code | 13 |
6948084524 | from typing import *
class Solution:
def canPartition(self, nums: List[int]) -> bool:
total_sum = sum(nums)
if total_sum % 2 != 0:
return False
target = total_sum // 2
m = len(nums)
dp = [0] * (total_sum + 1)
for i in range(1, m + 1):
for j in range(target, nums[i - 1] - 1, -1):
dp[j] = max(dp[j], dp[j - nums[i - 1]] + nums[i - 1])
if dp[target] == target:
return True
return False
if __name__ == '__main__':
sol = Solution()
nums = [1, 2, 5]
print(sol.canPartition(nums))
| Xiaoctw/LeetCode1_python | 动态规划/分割等和数组_416.py | 分割等和数组_416.py | py | 611 | python | en | code | 0 | github-code | 13 |
21021343977 | import torch
import os
import numpy as np
import random
import csv
import pickle
def seed_everything(args):
random.seed(args.seed)
os.environ['PYTHONASSEED'] = str(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
torch.cuda.manual_seed(args.seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = True
def getfewshot(inpath,outpath,fewshotnum):
###read from inpath
intrain = inpath + "/train.txt"
invalid = inpath + "/valid.txt"
intest = inpath + "/test.txt"
alltrainres = []
allvalidres = []
alltestres = []
f = open(intrain,'r')
while True:
oneline = f.readline().strip()
if not oneline:
break
alltrainres.append(oneline)
f.close()
f = open(invalid, 'r')
while True:
oneline = f.readline().strip()
if not oneline:
break
allvalidres.append(oneline)
f.close()
f = open(intest, 'r')
while True:
oneline = f.readline().strip()
if not oneline:
break
alltestres.append(oneline)
f.close()
######select few shot for train valid and test
###outpath
fewtrainname = outpath + "/train.txt"
fewvalidname = outpath + "/valid.txt"
fewtestname = outpath + "/test.txt"
tousetrainres = random.sample(alltrainres, fewshotnum)
tousevalidres = random.sample(allvalidres, fewshotnum)
testnum = 1000
tousetestres = random.sample(alltestres, testnum)
f = open(fewtrainname,'w')
for one in tousetrainres:
f.write(one + "\n")
f.close()
f = open(fewvalidname, 'w')
for one in tousevalidres:
f.write(one + "\n")
f.close()
####test
f = open(fewtestname, 'w')
for one in tousetestres:
f.write(one + "\n")
f.close()
def getpromptembedding(model,tokenizer,promptnumber,taskname):
t5_embedding = model.model.get_input_embeddings()
promptinitembedding = torch.FloatTensor(promptnumber, t5_embedding.weight.size(1))
startindex = 0
alllabel = ["summarization"]
alllabel.append(taskname)
print(alllabel)
for one in alllabel:
encoderes = tokenizer.batch_encode_plus([one], padding=False, truncation=False, return_tensors="pt")
touse = encoderes["input_ids"].squeeze()[:-1]
embeddingres = t5_embedding(touse).clone().detach()
if embeddingres.shape[0] > 1:
embeddingres = torch.mean(embeddingres, 0, keepdim=True)
promptinitembedding[startindex] = embeddingres
startindex += 1
fr = open('allnumber.pickle', 'rb')
alltokens = pickle.load(fr)
sortedalltoken = sorted(alltokens.items(), key=lambda item: item[1], reverse=True)
top5000 = []
for one in sortedalltoken:
if one[0] == 2:
continue
else:
if len(top5000) < 5000:
top5000.append(one)
else:
break
vocab = tokenizer.get_vocab()
randomtokennum = promptnumber - len(alllabel)
touse = random.sample(top5000, randomtokennum)
print(touse)
for one in touse:
promptinitembedding[startindex] = t5_embedding.weight[one[0]].clone().detach()
startindex += 1
return promptinitembedding
def getmemdata(alldatafile,memdatafile,memeveryclass):
f = open(alldatafile, 'r')
alldata = []
while True:
line = f.readline().strip()
if not line:
break
linelist = line.split('\t')
if len(linelist) != 2:
continue
content = linelist[0]
label = linelist[1]
onedata = content + "\t" + label
alldata.append(onedata)
f.close()
fo = open(memdatafile,'w')
if memeveryclass < len(alldata):
thisres = random.sample(alldata, memeveryclass)
else:
thisres = alldata
allmemdata = thisres
for one in allmemdata:
fo.write(one + "\n")
fo.close()
| qcwthu/Lifelong-Fewshot-Language-Learning | Summarization/utils.py | utils.py | py | 3,958 | python | en | code | 52 | github-code | 13 |
72915473618 | import os.path
import logging
import pytest
import pytest_bdd as bdd
bdd.scenarios('sessions.feature')
@pytest.fixture(autouse=True)
def turn_on_scroll_logging(quteproc):
quteproc.turn_on_scroll_logging()
@bdd.when(bdd.parsers.parse('I have a "{name}" session file:\n{contents}'))
def create_session_file(quteproc, name, contents):
filename = os.path.join(quteproc.basedir, 'data', 'sessions',
name + '.yml')
with open(filename, 'w', encoding='utf-8') as f:
f.write(contents)
@bdd.when(bdd.parsers.parse('I replace "{pattern}" by "{replacement}" in the '
'"{name}" session file'))
def session_replace(quteproc, server, pattern, replacement, name):
# First wait until the session was actually saved
quteproc.wait_for(category='message', loglevel=logging.INFO,
message='Saved session {}.'.format(name))
filename = os.path.join(quteproc.basedir, 'data', 'sessions',
name + '.yml')
replacement = replacement.replace('(port)', str(server.port)) # yo dawg
with open(filename, 'r', encoding='utf-8') as f:
data = f.read()
with open(filename, 'w', encoding='utf-8') as f:
f.write(data.replace(pattern, replacement))
@bdd.then(bdd.parsers.parse("the session {name} should exist"))
def session_should_exist(quteproc, name):
filename = os.path.join(quteproc.basedir, 'data', 'sessions',
name + '.yml')
assert os.path.exists(filename)
@bdd.then(bdd.parsers.parse("the session {name} should not exist"))
def session_should_not_exist(quteproc, name):
filename = os.path.join(quteproc.basedir, 'data', 'sessions',
name + '.yml')
assert not os.path.exists(filename)
| qutebrowser/qutebrowser | tests/end2end/features/test_sessions_bdd.py | test_sessions_bdd.py | py | 1,800 | python | en | code | 9,084 | github-code | 13 |
26889995924 | import numpy as np
from matplotlib.path import Path
from matplotlib.patches import Ellipse, PathPatch
import validate
class Ring:
"""
The ring class is a simple object that has ring parameters:
inner_radius
outer_radius
transmission
inclination
tilt
With the additional ability to get_patch for plotting.
"""
def __init__(self,
inner_radius: float,
outer_radius: float,
transmission: float,
inclination: float = 0,
tilt: float = 0
) -> None:
"""
This is the constructor for the class taking in all the necessary
parameters.
Parameters
----------
inner_radius : float
This is the inner radius of the ring [R*].
outer_radius : float
This is the outer radius of the ring [R*].
transmission : float
This is the transmission of the ring [-], from 0 to 1.
inclination : float
This is the inclination of the ring (relation between horizontal
and vertical width in projection) [default = 0 deg].
tilt : float
This is the tilt of the ring (angle between the x-axis and the
semi-major axis of the projected ring ellipse) [default = 0 deg].
"""
self.inner_radius = inner_radius
self.outer_radius = outer_radius
self.transmission = transmission
self.inclination = inclination
self.tilt = tilt
def __str__(self) -> str:
"""
This is the print representation of the ring object.
Returns
-------
print_ring_class : str
This contains the string representation of the ring class.
"""
# get parameter strings
inner_radius_string = (f"{self.inner_radius:.4f}").rjust(8)
outer_radius_string = (f"{self.outer_radius:.4f}").rjust(8)
transmission_string = (f"{self.transmission:.4f}").rjust(8)
inclination_string = (f"{self.inclination:.4f}").rjust(9)
tilt_string = (f"{self.tilt:.4f}").rjust(16)
# write lines
lines = [""]
lines.append("============================")
lines.append("***** RING INFORMATION *****")
lines.append("============================\n")
lines.append(f"Inner Radius: {inner_radius_string} [R*]")
lines.append(f"Outer Radius: {outer_radius_string} [R*]")
lines.append(f"Transmission: {transmission_string} [-]")
lines.append(f"Inclination: {inclination_string} [deg]")
lines.append(f"Tilt: {tilt_string} [deg]")
lines.append("\n============================")
# get print string
print_ring_class = "\n".join(lines)
return print_ring_class
@property
def inner_radius(self) -> float:
"""
This method gets the inner radius of the ring.
Returns
-------
inner_radius : float
This is the inner radius of the ring [R*].
"""
return self._inner_radius
@inner_radius.setter
def inner_radius(self, inner_radius: float) -> None:
"""
This method sets the inner radius of the ring.
Parameters
----------
inner_radius : float
This is the inner radius of the ring [R*].
"""
# initialisation except block
try:
upper_bound = self.outer_radius
except Exception:
upper_bound = np.inf
# correct for pyppluss simulation of light curves
if inner_radius == 0.:
inner_radius = 1e-16
self._inner_radius = validate.number(inner_radius, "inner_radius",
lower_bound=0., upper_bound=upper_bound, exclusive=True)
@property
def outer_radius(self) -> float:
"""
This method gets the outer radius of the ring
Returns
-------
outer_radius : float
This is the outer radius of the ring [R*].
"""
return self._outer_radius
@outer_radius.setter
def outer_radius(self, outer_radius: float) -> None:
"""
This method sets the outer radius.
Parameters
----------
outer_radius : float
This is the outer radius of the ring [R*].
"""
self._outer_radius = validate.number(outer_radius, "outer_radius",
lower_bound=self.inner_radius, exclusive=True)
@property
def transmission(self) -> None:
"""
This method gets the transmission of the ring.
Returns
-------
transmission : float
This is the transmission of the ring [-], from 0 to 1.
"""
return self._transmission
@transmission.setter
def transmission(self, transmission: float) -> None:
"""
This method sets the transmission of the ring.
Parameters
----------
transmission : float
This is the transmission of the ring [-], from 0 to 1.
"""
self._transmission = validate.number(transmission, "transmission",
lower_bound=0., upper_bound=1.)
@property
def inclination(self) -> float:
"""
This method gets the inclination of the ring.
Returns
-------
inclination : float
This is the inclination of the ring [deg], from 0 to 90.
"""
return self._inclination
@inclination.setter
def inclination(self, inclination: float) -> None:
"""
This method sets the inclination of the ring.
Parameters
----------
inclination : float
This is the inclination of the ring [deg], from 0 to 90.
"""
self._inclination = validate.number(inclination, 'inclination',
lower_bound=0, upper_bound=90)
@property
def tilt(self) -> float:
"""
This method gets the tilt of the ring.
Returns
-------
tilt: float
This is the tilt of the ring [deg], from 0 to 90.
"""
return self._tilt
@tilt.setter
def tilt(self, tilt: float) -> None:
"""
This method sets the tilt of the ring.
Parameters
----------
tilt : float
This is the tilt of the ring [deg], from -180 to 180.
"""
self._tilt = validate.number(tilt, 'tilt', lower_bound=-180,
upper_bound=180)
def get_patch(self,
x_shift: float = 0,
y_shift: float = 0,
face_color: str = "black"
) -> None:
"""
This function has been edited from a function written by Matthew
Kenworthy. The variable names, comments and documentation have been
changed, but the functionality has not.
Parameters
----------
x_shift : float
The x-coordinate of the centre of the ring [default = 0].
y_shift : float
The y-coordinate of the centre of the ring [default = 0].
inclination : float
This is the tip of the ring [deg], from 0 deg (face-on) to 90 deg
(edge-on) [default = 0].
tilt : float
This is the CCW angle [deg] between the orbital path and the semi-major
axis of the ring [default = 0].
face_color : str
The color of the ring system components [default = "black"].
Returns
-------
patch : matplotlib.patch
Patch of the ring with input parameters.
"""
x_shift = validate.number(x_shift, "x_shift")
y_shift = validate.number(y_shift, "y_shift")
face_color = validate.string(face_color, "face_color")
# get ring system and ring parameters
inc = np.deg2rad(self.inclination)
phi = np.deg2rad(self.tilt)
opacity = 1 - self.transmission
# centre location
ring_centre = np.array([x_shift, y_shift])
# get an Ellipse patch that has an ellipse defined with eight CURVE4
# Bezier curves actual parameters are irrelevant - get_path() returns
# only a normalised Bezier curve ellipse which we then subsequently
# transform
ellipse = Ellipse((1, 1), 1, 1, 0)
# get the Path points for the ellipse (8 Bezier curves with 3
# additional control points)
vertices = ellipse.get_path().vertices
codes = ellipse.get_path().codes
# define rotation matrix
rotation_matrix = np.array([[np.cos(phi), np.sin(phi)],
[np.sin(phi), -np.cos(phi)]])
# squeeze the circle to the appropriate ellipse
outer_annulus = self.outer_radius * vertices * ([ 1., np.cos(inc)])
inner_annulus = self.inner_radius * vertices * ([-1., np.cos(inc)])
# rotate and shift the ellipses
outer_ellipse = ring_centre + np.dot(outer_annulus, rotation_matrix)
inner_ellipse = ring_centre + np.dot(inner_annulus, rotation_matrix)
# produce the arrays neccesary to produce a new Path and Patch object
ring_vertices = np.vstack((outer_ellipse, inner_ellipse))
ring_codes = np.hstack((codes, codes))
# create the Path and Patch objects
ring_path = Path(ring_vertices, ring_codes)
ring_patch = PathPatch(ring_path, facecolor=face_color,
edgecolor=(0., 0., 0., 1.), alpha=opacity, lw=2)
return ring_patch | dmvandam/beyonce | Ring.py | Ring.py | py | 9,644 | python | en | code | 0 | github-code | 13 |
33049827109 | import os
from flask import Flask
from xgb_api import api_predict
app = Flask(__name__)
@app.route('/')
def hello():
return 'hello, world!'
@app.route('/predict')
def predict():
data = {
'PassengerId': [1],
'Pclass': [3],
'Age': [35],
'Sex': ['male'],
'SibSp': [1],
'Parch': [0],
'Fare': [12.75],
'Sex_cat': [1],
'Embarked_cat': [2],
}
res = api_predict(data)
return res
| sonhmai/titanic | app.py | app.py | py | 469 | python | en | code | 0 | github-code | 13 |
28326036387 | from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class Exemption(models.Model):
_name = "hr.contribution.exemption"
_description = "Contribution Exemption"
name = fields.Char()
employee_id = fields.Many2one(
comodel_name="hr.employee", string="Employee"
)
reason = fields.Text(string="Reason for Exemption", required=False)
date_start = fields.Date(string="Start Date of Exemption", required=False)
date_end = fields.Date(string="End Date of Exemption", required=False)
@api.constrains("date_start", "date_end")
def _constrain_mutual_insurance_date(self):
for exemption in self:
if (
exemption.date_start
and exemption.date_end
and exemption.date_start > exemption.date_end
):
raise ValidationError(
_(
"The start date of mutual insurance must be before the "
"end date"
)
)
| odoo-cae/odoo-addons-hr-incubator | hr_cae_contribution/models/hr_exemption.py | hr_exemption.py | py | 1,063 | python | en | code | 0 | github-code | 13 |
72523246737 | from numpy.random import randn
from scipy.linalg import qr
from scipy.linalg import svd
from scipy.sparse import csc_matrix
from numpy import allclose, outer
from sparsesvd import sparsesvd
def mysparsesvd(sparsematrix, m):
Ut, S, Vt = sparsesvd(sparsematrix, m)
return Ut.T, S, Vt.T
extra_dim = 50
power_num = 5
def randsvd(M, m):
Z = M * randn(M.shape[1], m + extra_dim)
Q, _ = qr(Z, mode='economic')
for _ in range(power_num):
Z = M.T * Q
Q, _ = qr(Z, mode='economic')
Z = M * Q
Q, _ = qr(Z, mode='economic')
U_low, svals, Vt = svd(Q.T * M, full_matrices=False)
svals = svals[:m]
U = csc_matrix(Q) * U_low[:,:m] # bring U back to the original dimension
V= Vt.T[:, :m]
return U, svals, V
def randsvd_centered(M, v1, v2, m):
T = randn(M.shape[1], m + extra_dim)
Z = M * T - v1 * (v2.T * T)
Q, _ = qr(Z, mode='economic')
for _ in range(power_num):
Z = M.T * Q - v2 * (v1.T * Q)
Q, _ = qr(Z, mode='economic')
Z = M * Q - v1 * (v2.T * Q)
Q, _ = qr(Z, mode='economic')
B = Q.T * M - (Q.T * v1) * v2.T
U_low, svals, Vt = svd(B, full_matrices=False)
svals = svals[:m]
U = csc_matrix(Q) * U_low[:,:m] # bring U back to the original dimension
V= Vt.T[:, :m]
return U, svals, V
if __name__=='__main__':
M = randn(100,300)
v1 = randn(100,1)
v2 = randn(300,1)
m = 60
O = M - outer(v1, v2)
U_svd, svals_svd, Vt_svd = svd(O)
U_svd = U_svd[:,:m]
svals_svd = svals_svd[:m]
Vt_svd = Vt_svd[:m,:]
U_approx1, svals_approx1, Vt_approx1 = randsvd(csc_matrix(O), m)
U_approx2, svals_approx2, Vt_approx2 = randsvd_centered(csc_matrix(M), csc_matrix(v1), csc_matrix(v2), m)
assert(allclose(svals_svd, svals_approx1) and allclose(svals_svd, svals_approx2))
| karlstratos/cca | src/svd.py | svd.py | py | 1,888 | python | en | code | 10 | github-code | 13 |
74838274256 | from cmath import e
import json
from re import template
from tkinter import E
def main(env, request_handler, method):
"""Simple to do app
Args:
env (Environment): renders environment for our template
request_handler(Request_handler): instance of request handler
method(str): GET or POST
"""
if method == "POST":
content_length = int(request_handler.headers['Content-Length']) # <--- Gets the size of data
post_data = request_handler.rfile.read(content_length) # <--- Gets the data itself\
post_data = post_data.decode()
# convert url data into dictionary
items = []
for x in post_data.split('&'):
items.append(x.split('='))
post_data = dict(items)
# check for the data in new.txt file. If there is data update the tasklist
# if not create a new file and use it to store the tasks
try:
with open('new.txt', 'r+') as f:
data = f.read()
if data:
data = json.loads(data)
data['tasks'] += [post_data['taskname']]
else:
data = { 'tasks': [post_data['taskname']] }
except FileNotFoundError:
data = { 'tasks': [post_data['taskname']] }
with open('new.txt', 'w') as f:
f.write(json.dumps(data))
template = env.get_template('task.html')
return template.render(**data)
template = env.get_template('new.html')
return template.render()
| canjey/pesapal-application | Problem1/sampleapp/__init__.py | __init__.py | py | 1,584 | python | en | code | 0 | github-code | 13 |
42252430005 | import logging
import requests
import json
from time import sleep
from src.webdriver import get_token
def maesk_get_location(cityname:str):
url = "https://api.maersk.com/locations"
querystring = {"cityName": cityname,"type":"city","sort":"cityName"}
response = requests.get(url, params=querystring)
if response.status_code == 404:
raise Exception(json.dumps({ "code": response.status_code, "message": "Paramêtro inválido..."}))
if response.status_code == 403:
raise Exception(json.dumps({ "code": response.status_code, "message": "IP bloqueado ou temporariamente banido..."}))
if response.status_code == 401:
raise Exception(json.dumps({ "code": response.status_code, "message": "verifique as suas credenciais..."}))
if response.status_code != 200:
raise Exception(json.dumps({ "code": response.status_code, "message": "Erro de requisição" }))
content = response.content.decode()
content = content[content.find("{"):content.find("}")+1]
data = json.loads(content)
return {
"city": data["cityName"],
"maerskGeoLocationId": data["maerskGeoLocationId"]
}
def maesk_get_ship_price(**kwargs):
url = "https://api.maersk.com/productoffer/v2/productoffers"
payload = {
"from": {
"name": kwargs.get("from_name"), #"Santos (Sao Paulo), Brazil",
"maerskGeoId": kwargs.get("from_geoid"), #"1BX66GARX9UAH",
"maerskServiceMode": "CY"
},
"to": {
"name": kwargs.get("to_name"), #"Singapore, Singapore",
"maerskGeoId": kwargs.get("to_geoid"), #"0XOP5ISJZK0HR",
"maerskServiceMode": "CY"
},
"commodity": {
"name": kwargs.get("commodity"), #"(With Lithium Batteries) Electronics, electronic appliances, audio, video equipment, telecommunication equipment",
"isDangerous": False,
"dangerousDetails": []
},
"containers": [
{
"isoCode": "22G1",
"name": "20 Dry Standard",
"size": "20",
"type": "DRY",
"weight": 18000,
"quantity": 1,
"isReefer": False,
"isNonOperatingReefer": False,
"isShipperOwnedContainer": False
}
],
"unit": "KG",
"shipmentPriceCalculationDate": kwargs.get("send_date"),#"2022-10-31",
"brandCode": "MAEU",
"customerCode": "30501103219",
"isSameRequest": False,
"loadAFLS": False,
"weekOffset": 0
}
headers = {
"authority": "api.maersk.com",
"accept": "application/json, text/plain, */*",
"akamai-bm-telemetry": kwargs.get("akamai_telemetry") ,
"authorization": kwargs.get("bearer_token"),
"content-type": "application/json",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36"
}
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 401:
logging.info("Token expired! getting new token")
get_token(new_bearer=True)
maesk_get_ship_price(**kwargs)
if response.status_code != 200:
raise Exception(json.dumps({
"code": response.status_code,
"message": "Verifique as suas credenciais..."
}))
return response.json()
| mx-jeff/naval_fretes | src/api/maesk.py | maesk.py | py | 3,490 | python | en | code | 0 | github-code | 13 |
37173080443 | # -*- coding: utf-8 -*-
from Tkinter import *
import Tkinter
import Tkinter as tk
import tkMessageBox
import sqlite3 as lite
import sys
con = lite.connect('paliwko.db')
cur = con.cursor()
paliwo = []
fuel = Tk()
fuel.title("Dziennik tankowan")
with con:
cur = con.cursor()
cur.execute("SELECT * FROM tankowanie")
rows = cur.fetchall()
for row in rows:
paliwo.append(row)
ost = row
with con:
cur = con.cursor()
cur.execute("SELECT MIN(cena) FROM tankowanie;")
najtansze_rows = cur.fetchall()
najtansze = najtansze_rows
with con:
cur = con.cursor()
cur.execute("SELECT MAX(cena) FROM tankowanie;")
najdrozsze_rows = cur.fetchall()
najdrozsze = najdrozsze_rows
with con:
cur = con.cursor()
cur.execute("SELECT MAX(ilosc) FROM tankowanie;")
naj_paliwa_rows = cur.fetchall()
naj_paliwa = naj_paliwa_rows
class Application(Frame):
def createWidgets(self):
self.QUIT = Button(self)
self.QUIT["text"] = "Wstecz"
self.QUIT["command"] = self.quit
self.QUIT.pack({"side": "bottom"})
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.createWidgets()
var = StringVar()
label = Label( fuel, textvariable=var)
var.set("Wszystkie tankowania.")
label.pack({"side":"top"})
w_tankowania = Text(fuel, height = 6, width = 42)
w_tankowania.insert(INSERT, paliwo)
w_tankowania.pack({"side":"top"})
var = StringVar()
label = Label( fuel, textvariable=var)
var.set("Ostatnie tankowanie.")
label.pack({"side":"top"})
ost_tankowanie = Text(fuel, height = 1, width = 42)
ost_tankowanie.insert(INSERT, ost)
ost_tankowanie.pack({"side":"top"})
var = StringVar()
label = Label( fuel, textvariable=var)
var.set("Najniższa cena paliwa.")
label.pack({"side":"top"})
ost_tankowanie = Text(fuel, height = 1, width = 42)
ost_tankowanie.insert(INSERT, najtansze[0])
ost_tankowanie.pack({"side":"top"})
var = StringVar()
label = Label( fuel, textvariable=var)
var.set("Najwyższa cena paliwa.")
label.pack({"side":"top"})
ost_tankowanie = Text(fuel, height = 1, width = 42)
ost_tankowanie.insert(INSERT, najdrozsze[0])
ost_tankowanie.pack({"side":"top"})
var = StringVar()
label = Label( fuel, textvariable=var)
var.set("Największa ilość zatankowanego paliwa.")
label.pack({"side":"top"})
ost_tankowanie = Text(fuel, height = 1, width = 42)
ost_tankowanie.insert(INSERT, naj_paliwa[0])
ost_tankowanie.pack({"side":"top"})
fuel = Application(master=fuel)
fuel.mainloop()
| kamilpek/python-paliwko | dziennik.py | dziennik.py | py | 2,513 | python | pl | code | 1 | github-code | 13 |
70869657619 | """Tests for unit functionalities."""
import os
import pandas as pd
import pytest
from app.ETL import extract_excel, load_em_um_novo_excel, transforma_em_um_unico
# Sample data for testing
df1 = pd.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]})
df2 = pd.DataFrame({"A": [4, 5, 6], "B": ["d", "e", "f"]})
@pytest.fixture
def mock_input_folder(tmpdir):
"""
Fixture to create mock input folder with sample Excel files for testing.
"""
# Criando arquivos Excel de exemplo para testes
input_folder = tmpdir.mkdir("input_folder")
df1.to_excel(
input_folder.join("file1.xlsx"), index=False
) # Retirado engine='openpyxl'
df2.to_excel(
input_folder.join("file2.xlsx"), index=False
) # Retirado engine='openpyxl'
return str(input_folder)
@pytest.fixture
def mock_output_folder(tmpdir):
"""Fixture to create a mock output folder for testing."""
return str(tmpdir.mkdir("output_folder"))
def test_extract(mock_input_folder):
"""Test the extraction of data from the input folder."""
extracted_data = extract_excel(mock_input_folder)
assert len(extracted_data) == 2 # Expecting two DataFrames
assert all(isinstance(df, pd.DataFrame) for df in extracted_data)
def test_extract_no_files(tmpdir):
"""Test extraction functionality with an empty input folder."""
# Criando uma pasta vazia
empty_folder = tmpdir.mkdir("empty_folder")
with pytest.raises(ValueError, match="No Excel files found"):
extract_excel(str(empty_folder))
def test_transform():
"""Test the transformation of dataframes."""
data = [df1, df2]
consolidated_df = transforma_em_um_unico(data)
assert len(consolidated_df) == 6 # 3 rows from df1 + 3 rows from df2
assert list(consolidated_df.columns) == ["A", "B"]
def test_transform_empty_list():
"""Test the transformation functionality with an empty list."""
empty_list = []
with pytest.raises(ValueError, match="No data to transform"):
transforma_em_um_unico(empty_list)
def test_load_no_permission(tmpdir):
"""Test the load functionality with a protected output folder."""
# Supondo que a pasta não tenha permissões de gravação
protected_folder = tmpdir.mkdir("protected_folder")
os.chmod(str(protected_folder), 0o444) # Somente permissões de leitura
df = pd.DataFrame({"A": [1], "B": ["a"]})
with pytest.raises(PermissionError):
load_em_um_novo_excel(df, str(protected_folder), "test.xlsx")
def test_load(mock_output_folder):
"""Test the load functionality."""
df = pd.concat([df1, df2], axis=0, ignore_index=True)
output_file_name = "consolidated.xlsx"
load_em_um_novo_excel(df, mock_output_folder, output_file_name)
assert os.path.exists(os.path.join(mock_output_folder, output_file_name))
# Verifying the contents of the loaded file
loaded_df = pd.read_excel(
os.path.join(mock_output_folder, output_file_name)
) # Retirado engine='openpyxl'
pd.testing.assert_frame_equal(loaded_df, df)
| lvgalvao/DataProjectStarterKit | tests/test_unitarios.py | test_unitarios.py | py | 3,049 | python | en | code | 23 | github-code | 13 |
71758469457 | import json
import os
import requests as rq
import datetime as dt
import pandas as pd
import ast
TOKEN_FILE = "token_info.json"
class Spotify():
def __init__(self):
if os.path.exists(TOKEN_FILE):
with open(TOKEN_FILE) as tkfile:
data = json.load(tkfile)
if data['timestamp'] < dt.datetime.timestamp(dt.datetime.now()):
if not self.get_token():
raise Exception("Unable to connect to Spotify!")
else:
self.token = data['access_token']
self.timeout = data['timestamp']
def get_token(self):
SPOTIFY_CLIENT_ID = os.getenv("SPOTIFY_CLIENT_ID")
SPOTIFY_CLIENT_SECRET = os.getenv("SPOTIFY_CLIENT_SECRET")
if SPOTIFY_CLIENT_ID is None or SPOTIFY_CLIENT_SECRET is None:
raise Exception("Environment variable not accessed")
# print(SPOTIFY_CLIENT_ID,SPOTIFY_CLIENT_SECRET)
request_body = {
"grant_type": "client_credentials",
"client_id": SPOTIFY_CLIENT_ID,
"client_secret": SPOTIFY_CLIENT_SECRET,
}
r = rq.post("https://accounts.spotify.com/api/token", data=request_body)
if r.status_code == 200:
resp = r.json()
self.timeout = resp['timestamp'] = dt.datetime.timestamp(dt.datetime.now()) + 3600
with open(TOKEN_FILE, "w") as tkfile:
tkfile.write(json.dumps(resp))
self.token = resp['access_token']
return True
return False
def get_track_metadata(self, track_id, flag=False):
if self.timeout < dt.datetime.timestamp(dt.datetime.now()):
if not self.get_token():
raise Exception("Unable to connect to Spotify!")
headers = {'Content-Type': 'application/json', "Authorization": f"Bearer {self.token}"}
label = ""
if not flag:
response = rq.get(f"https://api.spotify.com/v1/tracks/{track_id}", headers=headers)
if response.status_code == 200:
label = response.json()["name"]
response = rq.get(f"https://api.spotify.com/v1/audio-features/{track_id}", headers=headers)
if response.status_code == 200:
data = response.json()
if not flag:
data['label'] = label
data = data_prep(data)
return data
else:
return "unable to get track info"
def get_playlist_metadata(self, playlist_id):
if self.timeout < dt.datetime.timestamp(dt.datetime.now()):
if not self.get_token():
raise Exception("Unable to connect to Spotify!")
headers = {'Content-Type': 'application/json', "Authorization": f"Bearer {self.token}"}
response = rq.get(f"https://api.spotify.com/v1/playlists/{playlist_id}/tracks", headers=headers)
# if response.status_code == 200:
df = pd.DataFrame(response.json())
processed_info = pd.json_normalize(df['items'].apply(only_dict).tolist()).add_prefix('items_')
track_data = []
for ind, row in processed_info.iterrows():
temp = self.get_track_metadata(row["items_track.id"], True)
temp['label'] = row["items_track.name"]
track_data.append(temp)
return data_prep(track_data)
def data_prep(data):
final_params = ['acousticness', 'danceability', 'duration_ms', 'energy', 'instrumentalness', 'liveness',
'loudness', 'mode', 'speechiness', 'tempo', 'valence', 'key_0', 'key_1', 'key_2', 'key_3',
'key_4', 'key_5', 'key_6', 'key_7', 'key_8', 'key_9', 'key_10', 'key_11', 'time_signature_1.0',
'time_signature_3.0', 'time_signature_4.0', 'time_signature_5.0']
initial_parameters = ["acousticness", "danceability", "duration_ms", "energy", "instrumentalness", "key",
"liveness", "loudness", "mode", "speechiness", "tempo", "time_signature", "valence"]
if isinstance(data, dict):
data[f"key_{data['key']}"] = 1
del data["key"]
data[f"time_signature_{float(data['time_signature'])}"] = 1
del data["time_signature"]
data = [data]
data = pd.DataFrame(data)
else:
data = pd.DataFrame(data)
print(data)
data = pd.concat([data, pd.get_dummies(data['key'])], axis=1)
data['time_signature'] = data['time_signature'].astype(float)
data = pd.concat([data, pd.get_dummies(data['time_signature'])], axis=1)
unwanted_keys = set(data.keys()) - set(final_params)
unwanted_keys.remove("label")
data.drop(columns=list(unwanted_keys), inplace=True)
for i in final_params:
if i not in data.columns:
data[i] = [0] * len(data)
# print(data.columns)
return data
def only_dict(d):
try:
evaluated_json = ast.literal_eval(
str(d).replace("None", '\"None\"').replace("True", '\"True\"').replace("False", '\"False\"'))
return evaluated_json
except ValueError:
corrected = "\'" + str(d).replace("None", '\"None\"').replace("True", '\"True\"').replace("False",
'\"False\"') + "\'"
evaluated_json = ast.literal_eval(corrected)
return evaluated_json
"""def search_track(query_string=""):
headers = {
'Content-Type': 'application/json',
}
params = {
"query": "track:{}".format(urllib3.request.urlencode(query_string)),
'type': 'track',
'include_external': 'audio',
}
response = rq.get(\'https://api.spotify.com/v1/search\', headers=headers, params=params)
if response.status_code == 200:
return"""
"""
https://open.spotify.com/track/59hSaWp9MXxrpYTUHNEKNj
"""
| jdscifi/VinylRec | spotify_tasks.py | spotify_tasks.py | py | 5,857 | python | en | code | 0 | github-code | 13 |
43089321371 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen
from kivy.uix.popup import Popup
# The Label widget is for rendering text.
from kivy.uix.label import Label
from kivy.uix.button import Button
# The GridLayout arranges children in a matrix.
# It takes the available space and
# divides it into columns and rows,
# then adds widgets to the resulting “cells”.
from kivy.uix.gridlayout import GridLayout
# to change the kivy default settings we use this module config
from kivy.config import Config
# 0 being off 1 being on as in true / false
# you can use 0 or 1 && True or False
import time
import os
Config.set('graphics', 'resizable', True)
birthdayFile = 'data/bdayfile.dat'
Builder.load_string("""
<UpdatesScreen>
name: 'updates'
ScrollView:
id: scroll
do_scroll_x: False
BoxLayout:
orientation: 'vertical'
size_hint_y: None
height: dp(800)
padding: dp(15)
spacing: dp(15)
Image:
source: 'img/Realestate.jpeg'
allow_stretch: True
MDLabel:
font_style: 'Body1'
theme_text_color: 'Secondary'
text: ut.get_data('texts')['alerts']
""")
class UpdatesScreen(Screen):
def on_enter(self):
filename = open(birthdayFile, 'r')
today = time.strftime('%m%d')
flag = 0
for line in filename:
if today in line:
line = line.split(' ')
flag = 1
# line[1] contains Name and line[2] contains Surname
msg = line[1] + "Rent Collection Pending"
layout = GridLayout(cols=1, padding=10)
popupLabel = Label(text=msg)
closeButton = Button(text="Close the pop-up")
layout.add_widget(popupLabel)
layout.add_widget(closeButton)
popup = Popup(title='Alert',
content=layout,
size_hint=(None, None), size=(500, 600))
popup.open()
closeButton.bind(on_press=popup.dismiss)
| ketan-mk/pho-ga | screens/updates.py | updates.py | py | 2,219 | python | en | code | 0 | github-code | 13 |
3914380437 | from aiogram import exceptions as aiogram_exc
from NekoGram import Menu
import asyncio
from const import SEARCH_LIST, ADMIN_IDS, RUN_INTERVAL, NEKO, STORAGE
from loggers import main_logger
import scrappers
import menus
async def send_data(data: Menu, user: int):
while True:
try:
await NEKO.bot.send_message(
chat_id=user,
text=data.text,
reply_markup=data.markup,
parse_mode=data.parse_mode
)
break
except aiogram_exc.RetryAfter as e:
await asyncio.sleep(e.timeout)
except aiogram_exc.TelegramAPIError:
break
await asyncio.sleep(.2)
async def notify_error(scrapper: str):
main_logger.error(f'Error in {scrapper}')
for user in ADMIN_IDS:
data = await NEKO.build_menu(name='notification_failed', obj=None, user_id=user, auto_build=False)
await data.build(text_format={'scrapper': scrapper})
await send_data(data=data, user=user)
async def notify_found(item_name: str, store_name: str, url: str):
for user in ADMIN_IDS:
data = await NEKO.build_menu(name='notification_found', obj=None, user_id=user, auto_build=False)
await data.build(text_format={'item': item_name, 'store': store_name}, markup_format={'url': url})
await send_data(data=data, user=user)
async def scrape_urls():
while True:
for item in SEARCH_LIST:
main_logger.info(f'Looking up {item}')
for scrapper in [s for s in dir(scrappers) if s[0].isupper()]:
scrapper_class = getattr(scrappers, scrapper)
r = await getattr(scrapper_class, 'search')(item)
main_logger.info(f'Results: {r}')
if r is None:
await notify_error(scrapper=scrapper)
for result in r:
if not await STORAGE.check('SELECT url FROM search_cache WHERE url = ?', result):
await STORAGE.apply('INSERT INTO search_cache (url) VALUES (?)', result)
await notify_found(item_name=item, store_name=getattr(scrapper_class, 'NAME'), url=result)
await asyncio.sleep(RUN_INTERVAL)
async def startup(_):
NEKO.attach_router(menus.util.formatters.ROUTER)
await NEKO.storage.acquire_pool()
# Import database structure
with open('db.sql', 'r') as f:
for statement in f.read().split('--'):
await NEKO.storage.apply(statement)
asyncio.get_event_loop().create_task(scrape_urls())
async def shutdown(_):
await NEKO.storage.close_pool()
if __name__ == '__main__':
NEKO.start_polling(on_startup=startup, on_shutdown=shutdown)
| lyteloli/ProductLookuper | main.py | main.py | py | 2,732 | python | en | code | 0 | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.