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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|
32710979605
|
import gym
import pytest
@pytest.mark.skip(reason='suspected as slow, > 5min. TODO (peterz) fix')
def test_treechop_smoke():
with gym.make('minerl:MineRLTreechop-v0') as env:
env.reset()
for _ in range(10):
env.step(env.action_space.sample())
|
sihangw/minerl
|
tests/env_smoke_test.py
|
env_smoke_test.py
|
py
| 277 |
python
|
en
|
code
| null |
github-code
|
50
|
21238320601
|
from datetime import datetime
from typing import List
from json import load, dump
from os.path import exists
from nextcord import Embed, Member, Message
from nextcord.ext.commands import Cog, Context
from pytz import timezone
from ..bot import RF
from ..utils import Moderation
class Log(Cog):
def __init__(self, bot: RF):
self.bot = bot
self.Moderation = Moderation(bot)
@Cog.listener()
async def on_member_update(self, before: Member, after: Member) -> None:
if before.roles != after.roles:
if len(after.roles) < len(before.roles): # Remove roles
filter_role = list(filter(lambda r: r not in after.roles, before.roles))
if len(filter_role) > 1:
sorted_roles = sorted(filter_role, key=lambda r: r.position, reverse=True)
roles = ", ".join([role.mention for role in sorted_roles])
description = f"{after.mention} was removed from the roles:\n{roles}"
else:
description = f"{after.mention} was removed from {filter_role[0].mention}"
else: # Receive roles
filter_role = list(filter(lambda r: r not in before.roles, after.roles))
if len(filter_role) > 1:
sorted_roles = sorted(filter_role, key=lambda r: r.position, reverse=True)
roles = ", ".join([role.mention for role in sorted_roles])
description = f"{after.mention} was given the roles:\n{roles}"
else:
description = f"{after.mention} was given the {filter_role[0].mention} role"
embed = Embed(colour=0xFF470F,timestamp=datetime.now(tz=timezone("Asia/Ho_Chi_Minh")),description=f"**{description}**",)
embed.set_author(name=after, icon_url=after.display_avatar)
embed.set_footer(text=f"Author: {after}, ID: {after.id}")
await self.Moderation.logSend(after.guild, embed=embed)
@Cog.listener()
async def on_message_edit(self, before: Message, after: Message) -> None:
if not after.author.bot:
if before.content != after.content:
embed = Embed(colour=0x337FD5, timestamp=datetime.now(tz=timezone("Asia/Ho_Chi_Minh")), description=f"**Message edited in** {after.channel.mention} [Jump to message]({after.jump_url})",)
embed.set_footer(text=f"User ID: {after.author.id}")
embed.set_author(name=after.author, icon_url=after.author.display_avatar)
fields = [("Before", before.content, False), ("After", after.content, False),]
for name, value, inline in fields:
embed.add_field(name=name, value=value, inline=inline)
await self.Moderation.logSend(after.guild, embed=embed)
def sniperUser(self, message: Message):
filePath = f"./RF/cogs/MessageLog/{message.guild.id}-sniper.json"
def logMessage(message: Message):
with open(filePath, "r+") as f:
data = load(f)
data[str(message.author.id)] = message.content
data[str(message.guild.id)] = {message.author.id: message.content}
f.seek(0)
dump(data, f, indent=4)
f.truncate()
if not exists(filePath):
with open(filePath, "w") as f:
f.write("{}")
logMessage(message)
else:
logMessage(message)
@Cog.listener()
async def on_message_delete(self, message: Message) -> None:
if not message.author.bot:
embed = Embed(description=f"**Message sent by {message.author.mention} deleted in {message.channel.mention}** \n{message.content}", colour=0xFF470F, timestamp=datetime.now(tz=timezone("Asia/Ho_Chi_Minh")),)
embed.set_footer(text=f"User ID: {message.author.id} | Message ID: {message.id}")
embed.set_author(name=message.author, icon_url=message.author.display_avatar)
self.sniperUser(message)
await self.Moderation.logSend(message.guild, embed=embed)
@Cog.listener()
async def on_command_completion(self, ctx: Context) -> None:
embed = Embed(colour=0x2F3136, description=f"Used `{ctx.command}` command in {ctx.channel.mention} \n{ctx.message.content}", timestamp=datetime.now(tz=timezone("Asia/Ho_Chi_Minh")),)
embed.set_author(name=ctx.author, icon_url=ctx.author.display_avatar)
await self.Moderation.logSend(ctx.guild, embed=embed)
@Cog.listener()
async def on_bulk_message_delete(self, messages: List[Message]) -> None:
with open(f"./RF/cogs/MessageLog/{messages[0].guild.id}.txt", "w") as f:
f.write(f"{len(messages)} messages deleted in #{messages[0].channel.name}:\n\n\n")
for message in messages:
f.write(f"{message.author} (User ID: {message.author.id} Message ID: {message.id})\n{message.content}\n\n\n")
await self.Moderation.logSend(messages[0].guild, file=f)
@Cog.listener()
async def on_ready(self):
if not self.bot.ready:
self.bot.cogs_ready.ready_up("Log")
def setup(bot):
bot.add_cog(Log(bot))
|
codacy-badger/RF-911-Bot
|
RF/cogs/Log.py
|
Log.py
|
py
| 5,272 |
python
|
en
|
code
| 0 |
github-code
|
50
|
13567613364
|
import scrapy
import re
#import BaseSpider
import sys
sys.path.append('/home/shige/sg/sg')
from sg.items import SgItem
#import Selector
from scrapy.selector import Selector
class NewsSpider(scrapy.Spider):
name = "news"
# allowed_domains = ["http://news.hitwh.edu.cn/"]
start_urls = ['http://news.hitwh.edu.cn/']
def parse(self, response):
for href in response.css('a::attr(href)').extract():
try:
new = re.findall(r"[i][d][=]\d{5}", href)[0]
url = 'http://news.hitwh.edu.cn/news_detail.asp?' + new
yield scrapy.Request(url, callback=self.parse_news)
except:
continue
def parse_news(self, response):
sel = Selector(response)
item = SgItem()
item['url'] = response.url
item['title'] = sel.xpath("//div[@id='newsTitle']").extract()
item['body'] = sel.xpath("//div[@id='newsContnet']//p//text()").extract()
return item
|
hitwhsg/hitwhsg
|
news.py
|
news.py
|
py
| 984 |
python
|
en
|
code
| 0 |
github-code
|
50
|
42634935603
|
__author__ = 'Aaron Yang'
__email__ = '[email protected]'
__date__ = '12/18/2020 11:28 AM'
class Solution:
def exchange(self, nums):
left, right = 0, len(nums) - 1
while left < right:
while left < len(nums) and nums[left] % 2 != 0:
left += 1
while right >= 0 and nums[right] % 2 == 0:
right -= 1
if left < right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
else:
break
return nums
Solution().exchange([1, 3, 5])
|
AaronYang2333/CSCI_570
|
records/12-18/asd223.py
|
asd223.py
|
py
| 618 |
python
|
en
|
code
| 107 |
github-code
|
50
|
4443340570
|
from google_images_search import GoogleImagesSearch
import zipfile
import os
# you can provide API key and CX using arguments,
# or you can set environment variables: GCS_DEVELOPER_KEY, GCS_CX
gis = GoogleImagesSearch(
'AIzaSyBpIAcN5IIIcmfLwGq3j6fAV5QkW6vn4N0', '2e5dded9ae895e14b', validate_images=True)
# define search params:
def search(keyword, imageNumber):
_search_params = {
'q': keyword,
'num': imageNumber,
# 'safe': 'medium',
# 'fileType': 'jpg',
# 'imgType': 'photo',
# 'imgSize': 'MEDIUM',
# 'imgDominantColor': 'brown',
# 'rights': 'cc_publicdomain'
}
gis.search(search_params=_search_params, path_to_dir='./images/')
handle = zipfile.ZipFile('images.zip', 'w')
os.chdir('./images/')
for x in os.listdir():
handle.write(x, compress_type=zipfile.ZIP_DEFLATED)
os.remove(x)
handle.close()
os.chdir("../")
os.rmdir("./images/")
# for files in os.walk('./'):
# for imagefile in files:
# return imagefile.endswith('.zip')
|
raj-chinagundi/Piccauto
|
searching.py
|
searching.py
|
py
| 1,123 |
python
|
en
|
code
| 0 |
github-code
|
50
|
2338189529
|
# team.images.utils.py
from team.images import app_config
def list_to_str(lst):
'''Creates string from string list separated using default separator'''
list_as_string = ''
if isinstance(lst, str) is False:
for iterator in range(0, len(lst)):
if iterator == 0:
list_as_string = str(lst[iterator])
else:
list_as_string = list_as_string + app_config.LIST_SEPARATOR + str(lst[iterator])
return list_as_string
def get_column_descriptions():
STR_SEPARATOR = app_config.STR_SEPARATOR
return 'file_name' + STR_SEPARATOR\
+ 'file_size' + STR_SEPARATOR\
+ 'metadata_image_format' + STR_SEPARATOR\
+ 'metadata_image_width' + STR_SEPARATOR\
+ 'metadata_image_height' + STR_SEPARATOR\
+ 'metadata_image_dpi' + STR_SEPARATOR\
+ 'product_code_from_file_name' + STR_SEPARATOR\
+ 'possible_product_codes' + STR_SEPARATOR\
+ 'filename_logo_removed' + STR_SEPARATOR\
+ 'filename_is_box_offer' + STR_SEPARATOR\
+ 'filename_is_offer' + STR_SEPARATOR\
+ 'filename_is_label' + STR_SEPARATOR\
+ 'filename_arranged' + STR_SEPARATOR\
+ 'filename_dpi' + STR_SEPARATOR\
+ 'logo_removed' + STR_SEPARATOR\
+ 'filename_image_sequence' + STR_SEPARATOR\
+ 'product_code_from_db' + STR_SEPARATOR\
+ 'new_filename' + STR_SEPARATOR\
+ 'products' + STR_SEPARATOR\
+ 'warnings' + STR_SEPARATOR\
+ 'errors'
def rreplace(given_string, old, new, occurrence):
split_list = given_string.rsplit(old, occurrence)
return new.join(split_list)
def exif_str_2_tuple(input_string):
converted_list = list()
for char in input_string:
char2int = ord(char)
if char2int < 256:
converted_list.append(char2int)
converted_list.append(0)
else:
converted_list.append(char2int%256)
converted_list.append(floor(char2int/256))
converted_list.append(0)
converted_list.append(0)
return tuple(converted_list)
def exif_tuple_2_str(input_tuple):
output_string = ''
for ix in range(0, len(input_tuple)):
if ix % 2 == 0:
lo_byte = input_tuple[ix]
hi_byte = input_tuple[ix + 1]#this is risky in case tuple has not even number of values
if lo_byte > 0 or hi_byte > 0:
output_string = output_string + chr(hi_byte * 256 + lo_byte)
#ix = ix + 1
return output_string
|
slobodz/team.images
|
team/images/service/utils.py
|
utils.py
|
py
| 2,543 |
python
|
en
|
code
| 0 |
github-code
|
50
|
32086595559
|
import sys
from collections import defaultdict
input = lambda:sys.stdin.readline()
graph=defaultdict(list)
N = int(input())
for _ in range(N-1):
u, v = map(int, input().split())
graph[u].append(v)
graph[v].append(u)
q = int(input())
for _ in range(q):
t, k = map(int, input().split())
if t == 1:
if len(graph[k]) < 2:
print('no')
else:
print('yes')
else:
print('yes')
|
sami355-24/2023SummerVacationCodingTestCamp
|
lsm/230922-lsm-14675.py
|
230922-lsm-14675.py
|
py
| 442 |
python
|
en
|
code
| 0 |
github-code
|
50
|
40993511170
|
"""
Errors terminates the python code been executed
- Syntax error
- shows the error with ^
- most IDE catches this error
- exceptions: errors that occur during execution
- code is syntactically correct
- but error occurs when you try to execute it
exception handling:
Try: block of code that might generate error / run this code
except: handle the exception
else: execute code when there is no error
finally: executes whether an error occurs or not
"""
try:
print(10/2)
except:
print("print nothing")
else:
print("No error")
finally:
print("I occur regardless of an error")
try:
x = 10
y = [10, 2, 3, 0, 4, 6]
z = [x/m for m in y]
except:
print("error")
finally:
print("I occur regardless of an error")
"""
Example: database connection
try: make a connection
except: error
finally: close the connection
read and write to a file
try: read the file
write to a file
except: error that occurs
finally/else: close the fail
"""
"""
types of Exceptions
- Arithmetic error : Zerodivision Error eg10/0
OverflowError
- Assertion error: when assertion fails
- EOF error
- Import error
- ModuleNotFound error
- Index error
- Key error
- Name error
"""
try:
print(name)
except NameError as err: #named exceptions
msg = err
print(f"A new message: {err}")
except:
print("other errors")
"""Creating customized Exceptions"""
class NoNegativeInList(Exception):
pass
"""raise exceptions"""
list1 = [10, 4, 5, 6, -1, 7, 7]
for x in list1:
if x < 0:
raise NoNegativeInList("Negative values shouldn't be in a list")
|
PavelKo41/SDAtraining
|
venv/exceptions.py
|
exceptions.py
|
py
| 1,647 |
python
|
en
|
code
| 0 |
github-code
|
50
|
1685923786
|
import math
import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from paddle3d.apis import manager
from paddle3d.models.common import pointnet2_stack as pointnet2_stack_modules
from paddle3d.models.heads.roi_heads.roi_head_base import RoIHeadBase
from paddle3d.models.layers import (constant_init, kaiming_normal_init,
xavier_normal_init)
@manager.HEADS.add_component
class PVRCNNHead(RoIHeadBase):
def __init__(self, input_channels, model_cfg, num_class=1, **kwargs):
super().__init__(num_class=num_class, model_cfg=model_cfg)
self.roi_grid_pool_layer, num_c_out = pointnet2_stack_modules.build_local_aggregation_module(
input_channels=input_channels,
config=self.model_cfg["roi_grid_pool"])
grid_size = self.model_cfg["roi_grid_pool"]["grid_size"]
pre_channel = grid_size * grid_size * grid_size * num_c_out
self.pre_channel = pre_channel
shared_fc_list = []
for k in range(0, self.model_cfg["shared_fc"].__len__()):
shared_fc_list.extend([
nn.Conv1D(
pre_channel,
self.model_cfg["shared_fc"][k],
kernel_size=1,
bias_attr=False),
nn.BatchNorm1D(self.model_cfg["shared_fc"][k]),
nn.ReLU()
])
pre_channel = self.model_cfg["shared_fc"][k]
if k != self.model_cfg["shared_fc"].__len__(
) - 1 and self.model_cfg["dp_ratio"] > 0:
shared_fc_list.append(nn.Dropout(self.model_cfg["dp_ratio"]))
self.shared_fc_layer = nn.Sequential(*shared_fc_list)
self.cls_layers = self.make_fc_layers(
input_channels=pre_channel,
output_channels=self.num_class,
fc_list=self.model_cfg["cls_fc"])
self.reg_layers = self.make_fc_layers(
input_channels=pre_channel,
output_channels=self.box_coder.code_size * self.num_class,
fc_list=self.model_cfg["reg_fc"])
self.init_weights(weight_init='xavier')
def init_weights(self, weight_init='xavier'):
if weight_init not in ['kaiming', 'xavier', 'normal']:
raise NotImplementedError
for m in self.sublayers():
if isinstance(m, nn.Conv2D) or isinstance(m, nn.Conv1D):
if weight_init == 'normal':
m.weight.set_value(
paddle.normal(mean=0, std=0.001, shape=m.weight.shape))
elif weight_init == 'kaiming':
kaiming_normal_init(
m.weight, reverse=isinstance(m, nn.Linear))
elif weight_init == 'xavier':
xavier_normal_init(
m.weight, reverse=isinstance(m, nn.Linear))
if m.bias is not None:
constant_init(m.bias, value=0)
elif isinstance(m, nn.BatchNorm1D):
constant_init(m.weight, value=1)
constant_init(m.bias, value=0)
self.reg_layers[-1].weight.set_value(
paddle.normal(
mean=0, std=0.001, shape=self.reg_layers[-1].weight.shape))
def roi_grid_pool(self, batch_dict):
"""
Args:
batch_dict:
batch_size:
rois: (B, num_rois, 7 + C)
point_coords: (num_points, 4) [bs_idx, x, y, z]
point_features: (num_points, C)
point_cls_scores: (N1 + N2 + N3 + ..., 1)
point_part_offset: (N1 + N2 + N3 + ..., 3)
Returns:
"""
batch_size = batch_dict['batch_size']
rois = batch_dict['rois']
point_coords = batch_dict['point_coords']
point_features = batch_dict['point_features']
point_features = point_features * batch_dict[
'point_cls_scores'].reshape([-1, 1])
global_roi_grid_points, local_roi_grid_points = self.get_global_grid_points_of_roi(
rois, grid_size=self.model_cfg["roi_grid_pool"]
["grid_size"]) # (BxN, 6x6x6, 3)
global_roi_grid_points = global_roi_grid_points.reshape(
[batch_size, -1, 3]) # (B, Nx6x6x6, 3)
xyz = point_coords[:, 1:4]
xyz_batch_cnt = paddle.zeros((batch_size, ), dtype='int32')
batch_idx = point_coords[:, 0]
for k in range(batch_size):
xyz_batch_cnt[k] = (batch_idx == k).sum().astype(
xyz_batch_cnt.dtype)
new_xyz = global_roi_grid_points.reshape([-1, 3])
new_xyz_batch_cnt = paddle.full((batch_size, ),
global_roi_grid_points.shape[1],
dtype='int32')
pooled_points, pooled_features = self.roi_grid_pool_layer(
xyz=xyz,
xyz_batch_cnt=xyz_batch_cnt,
new_xyz=new_xyz,
new_xyz_batch_cnt=new_xyz_batch_cnt,
features=point_features,
) # (M1 + M2 ..., C)
pooled_features = pooled_features.reshape([
-1, self.model_cfg["roi_grid_pool"]["grid_size"]**3,
pooled_features.shape[-1]
]) # (BxN, 6x6x6, C)
return pooled_features
def forward(self, batch_dict):
"""
:param input_data: input dict
:return:
"""
targets_dict = self.proposal_layer(
batch_dict,
nms_config=self.model_cfg["nms_config"]
['train' if self.training else 'test'])
if self.training:
targets_dict = batch_dict.get('roi_targets_dict', None)
if targets_dict is None:
targets_dict = self.assign_targets(batch_dict)
batch_dict['rois'] = targets_dict['rois']
batch_dict['roi_labels'] = targets_dict['roi_labels']
# RoI aware pooling
pooled_features = self.roi_grid_pool(batch_dict) # (BxN, 6x6x6, C)
grid_size = self.model_cfg["roi_grid_pool"]["grid_size"]
pooled_features = pooled_features.transpose([0, 2, 1])
shared_features = self.shared_fc_layer(
pooled_features.reshape([-1, self.pre_channel, 1]))
rcnn_cls = self.cls_layers(shared_features).transpose(
[0, 2, 1]).squeeze(axis=1) # (B, 1 or 2)
rcnn_reg = self.reg_layers(shared_features).transpose(
[0, 2, 1]).squeeze(axis=1) # (B, C)
if not self.training:
batch_cls_preds, batch_box_preds = self.generate_predicted_boxes(
batch_size=batch_dict['batch_size'],
rois=batch_dict['rois'],
cls_preds=rcnn_cls,
box_preds=rcnn_reg)
batch_dict['batch_cls_preds'] = batch_cls_preds
batch_dict['batch_box_preds'] = batch_box_preds
batch_dict['cls_preds_normalized'] = False
else:
targets_dict['rcnn_cls'] = rcnn_cls
targets_dict['rcnn_reg'] = rcnn_reg
self.forward_ret_dict = targets_dict
return batch_dict
|
PaddlePaddle/Paddle3D
|
paddle3d/models/heads/roi_heads/pvrcnn_head.py
|
pvrcnn_head.py
|
py
| 7,124 |
python
|
en
|
code
| 479 |
github-code
|
50
|
17194158385
|
"""
This scripts receives OSC messages via the pyOSC library
and controls APA102 LEDs with the Adafruit DotStar library.
It is used for displaying video or test data on LED stripes.
"""
import os
import OSC
import time
from subprocess import call
from dotstar import Adafruit_DotStar
""" Setup DotStar strip for use in manual mode"""
strip = Adafruit_DotStar()
strip.begin()
strip.setBrightness(0)
"""
Load three different txt files that contain the video data.
It is saved as hex arrays, one line per frame.
"""
with open("/home/pi/frames/frames1.txt", "rb") as fp:
fone = fp.readlines()
foneNumFrames = sum(1 for _ in fone) - 1
foneIndex = -1
with open("/home/pi/frames/frames2.txt", "rb") as fp:
ftwo = fp.readlines()
ftwoNumFrames = sum(1 for _ in ftwo) - 1
ftwoIndex = -1
with open("/home/pi/frames/frames3.txt", "rb") as fp:
fthree = fp.readlines()
fthreeNumFrames = sum(1 for _ in fthree) - 1
fthreeIndex = -1
""" Load the videos for test mode and blinking """
with open("/home/pi/frames/rgbColors.txt", "rb") as fp:
testFrames = fp.readlines()
with open("/home/pi/frames/testmode.txt", "rb") as fp:
testmode = fp.readlines()
activeTest = -1
"""
These functions are executed, when a 'timecode' is received.
The range is remapped from 0-1 to 0-number of frames.
When the frame number wasn't received before, the corresponding line is read from the file.
This line is then handed to the show function of the DotStar library as a byte array.
"""
def recFoneIndex(addr, tags, data, client_address):
global foneIndex
global fone
global foneNumFrames
index = int(data[0] * foneNumFrames)
if index != foneIndex:
foneIndex = index
f = fone[index].rstrip()
strip.show(bytearray.fromhex(f))
return
def recFtwoIndex(addr, tags, data, client_address):
global ftwoIndex
global ftwo
global ftwoNumFrames
index = int(data[0] * ftwoNumFrames)
if index != ftwoIndex:
ftwoIndex = index
f = ftwo[index].rstrip()
strip.show(bytearray.fromhex(f))
return
def recFthreeIndex(addr, tags, data, client_address):
global fthreeIndex
global fthree
global fthreeNumFrames
index = int(data[0] * fthreeNumFrames)
if index != fthreeIndex:
fthreeIndex = index
f = fthree[index].rstrip()
strip.show(bytearray.fromhex(f))
return
def recTestmode(addr, tags, data, client_address):
global activeTest
global testmode
indexIn = int(data[0] * 499)
if indexIn != activeTest:
activeTest = indexIn
fr = testmode[indexIn].rstrip()
strip.show(bytearray.fromhex(fr))
return
"""
This function makes the LED blink any number of times.
Colors are: 0=Black, 1=100% Red, 2=100% Green, 3=100% Blue
4=50% Red, 5=50% Green, 6=50% Blue
"""
def Blink(color, count):
global testFrames
for i in range(count):
f = testFrames[color].rstrip()
strip.show(bytearray.fromhex(f))
time.sleep(0.2)
f = testFrames[0].rstrip()
strip.show(bytearray.fromhex(f))
time.sleep(0.2)
return
"""
This test functions cycles through all LEDs
to make sure the mapping is right.
"""
def recStripTest(addr, tags, data, client_address):
with open("/home/pi/frames/rgbTest.txt", "rb") as fp:
pixs = fp.readlines()
for i in range(1500):
f = pixs[i].rstrip()
strip.show(bytearray.fromhex(f))
time.sleep(0.02)
Blink(0,1)
return
def recConnectTest(addr, tags, data, client_address):
Blink(7,3)
return
def recBlack(addr, tags, data, client_address):
Blink(0,1)
return
def recExit(addr, tags, data, client_address):
Blink(0,1)
s.close()
return
def recShutdown(addr, tags, data, client_address):
Blink(5,3)
s.close()
call("sudo shutdown -h now", shell=True)
return
def recReboot(addr, tags, data, client_address):
Blink(0,1)
call("sudo reboot", shell=True)
return
def recCpu(addr, tags, data, client_address):
print(str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip()))
return
def recRam(addr, tags, data, client_address):
call("free -h", shell=True)
return
def recSampleRate(addr, tags, stuff, source):
pass
s = OSC.OSCServer(("",7000))
s.addDefaultHandlers()
s.addMsgHandler('default', recSampleRate) #all not explicitly handled OSC messages
s.addMsgHandler('/_samplerate', recSampleRate)
s.addMsgHandler('/leds/fone', recFoneIndex)
s.addMsgHandler('/leds/ftwo', recFtwoIndex)
s.addMsgHandler('/leds/fthree', recFthreeIndex)
s.addMsgHandler('leds/striptest', recStripTest)
s.addMsgHandler('/leds/connecttest', recConnectTest)
s.addMsgHandler('/leds/black', recBlack)
s.addMsgHandler('/leds/exit', recExit)
s.addMsgHandler('/leds/reboot', recReboot)
s.addMsgHandler('/leds/shutdown', recShutdown)
s.addMsgHandler('/leds/ram', recRam)
s.addMsgHandler('/leds/cpu', recCpu)
s.addMsgHandler('/leds/testmode',recTestmode)
Blink(6,3)
s.serve_forever()
|
DFortmann/Wireless-LEDs
|
oscServer3.py
|
oscServer3.py
|
py
| 4,792 |
python
|
en
|
code
| 3 |
github-code
|
50
|
261175975
|
"""
Here the calculations for the forcasts and the tomorrow value will be calculated.
"""
from datetime import datetime, timedelta, timezone
import pandas
class Forecasts:
def __init__(self, csv_location="weather.csv"):
self.weather_dataframe = pandas.read_csv(csv_location)
def get_forecast(self, now, then):
belief_horizon_in_sec = self.get_belief_horizon_in_sec(now, then)
then_in_datasource_format = self.transform_then_to_datasource_format(then)
forecast = {}
for sensor_type in ["temperature", "irradiance", "wind speed"]:
forecast[sensor_type] = self.get_latest_forecast(
then_in_datasource_format, belief_horizon_in_sec, sensor_type
)
return forecast
def get_latest_forecast(self, then, belief_horizon_in_sec, sensor_type):
forecasts_dataframe = self.weather_dataframe[
(self.weather_dataframe["event_start"] == then)
& (self.weather_dataframe["sensor"] == sensor_type)
& (self.weather_dataframe["belief_horizon_in_sec"] >= belief_horizon_in_sec)
]
if forecasts_dataframe.empty:
return "No forecasts for this date range"
event_value = forecasts_dataframe.loc[
forecasts_dataframe["belief_horizon_in_sec"].idxmin()
]["event_value"]
return event_value
def get_belief_horizon_in_sec(self, now, then):
belief_horizon_in_sec = (then - now).total_seconds()
return belief_horizon_in_sec
def transform_then_to_datasource_format(self, then):
then = datetime(
then.year, then.month, then.day, then.hour, 0, tzinfo=timezone.utc
).isoformat()
then_in_datasource_format = then[:-3].replace("T", " ")
return then_in_datasource_format
def get_tommorow(self, now):
tommorow = now + timedelta(days=1)
# get the next day
# get the latest forecast for each time
# get the max forecast for the 3 booleans
pass
def get_tomorrow_datetime_in_datasource_format(self, now):
tommorow = now + timedelta(days=1)
tommorow_start = datetime(
tommorow.year, tommorow.month, tommorow.day, 0, 0, tzinfo=timezone.utc
).isoformat()
tommorow_end = datetime(
tommorow.year, tommorow.month, tommorow.day, 24, 0, tzinfo=timezone.utc
).isoformat()
tommorow_start_in_datasource_format = tommorow_start[:-3].replace("T", " ")
tommorow_end_in_datasource_format = tommorow_end[:-3].replace("T", " ")
return tommorow_start_in_datasource_format, tommorow_end_in_datasource_format
|
GustaafL/weather_forecast
|
src/weather_forecast/forecasts.py
|
forecasts.py
|
py
| 2,673 |
python
|
en
|
code
| 0 |
github-code
|
50
|
69892425115
|
from django.shortcuts import render
from django.http import HttpResponse
from . import mqtt as mqtt_module
import time
MQTT_HOST = "77.234.202.168"
MQTT_PORT = 1883
MQTT_KEEPALIVE_INTERVAL = 60
def index(request):
return HttpResponse("<h2>QR_Reader module is loaded here</h2>")
def qr_reader(request):
# this loads the view inside templates folder inside this app
# but django treats all the templates folder of different apps as one single /templates folder
# so it will be wise to namespace them according to the app to remove any possibility of conflict
#(optional) a mqtt request is to be made to the server to get the current_state
# this can be optional as in real world its not relevant to the SGB
return render(request,"qr_reader/waste_bin.html")
def qr_reader_sabin(request):
# psabin is supposed to edit here
return render(request,"qr_reader/index-sabin.html")
def custom_waste_bin(request):
return render(request,"qr_reader/custom_bin.html")
def mqtt_ajax_authenticate(request):
decoded_qr = request.POST.get("code","error getting code")
client = mqtt_module.client
client.on_connect = mqtt_module.on_connect
client.on_subscribe = mqtt_module.on_subscribe
client.on_message = mqtt_module.on_message
client.on_publish = mqtt_module.on_publish
# establish mqtt connection subscribe to message topic from server
client.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL)
client.loop_start()
# publish qr_code to server
client.subscribe(mqtt_module.SUB_AUTHENTICATE_TOPIC,0)
client.publish(mqtt_module.PUB_AUTHENTICATE_TOPIC, decoded_qr);
#waiting period of to receive a reply
time.sleep(5)
client.disconnect()
client.loop_stop()
return HttpResponse(mqtt_module.RESPONSE["open"])
def mqtt_ajax_waste(request):
waste_meta_data = request.POST.get("waste_meta_data","error getting code")
client = mqtt_module.client
client.on_connect = mqtt_module.on_connect
client.on_subscribe = mqtt_module.on_subscribe
client.on_message = mqtt_module.on_message
client.on_publish = mqtt_module.on_publish
# establish mqtt connection subscribe to message topic from server
client.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL)
client.loop_start()
# publish qr_code to server
client.subscribe(mqtt_module.SUB_WASTE_TOPIC,0)
client.publish(mqtt_module.PUB_WASTE_TOPIC, waste_meta_data);
#waiting period of to receive a reply
time.sleep(5)
client.disconnect()
client.loop_stop()
return HttpResponse(mqtt_module.RESPONSE)
|
itmo-swm/SGB-Simulation
|
qr_reader/views.py
|
views.py
|
py
| 2,484 |
python
|
en
|
code
| 0 |
github-code
|
50
|
24893180562
|
#숫자 카드
import sys
N=int(input())
N_list = list(map(int, sys.stdin.readline().strip().split()))
M=int(input())
M_list=list(map(int, sys.stdin.readline().strip().split()))
N_list.sort()
for i in M_list:
MIN, MAX = 0, len(N_list)
while True:
if MIN > MAX:
MAX = MAX+1
break
mid = (MIN+MAX)//2
if 0 <= mid < len(N_list):
if N_list[mid] < i:
MIN = mid+1
else:
MAX = mid-1
else:
break
if 0 <= MAX < len(N_list):
if N_list[MAX]==i:
print(1,end=" ")
else:
print(0,end=" ")
else:
print(0,end=" ")
|
AlPomo/AlgorithmReview
|
Baekjoon/Week04/10815_G.py
|
10815_G.py
|
py
| 687 |
python
|
en
|
code
| 0 |
github-code
|
50
|
18608030
|
from __future__ import division
from __future__ import print_function
from astropy.io import fits
import argparse
import numpy as np
import re
import sys
def readfits(infile, iext=0):
"""Read FITS file.
Parameters
----------
infile : string
Input file name to be read.
iext : int
Extension number (0=first HDU)
Returns
-------
image2d : 2d numpy array, floats
Data array.
main_header: fits header
Primary header.
header : fits header
Header corresponding to the extension read. When the extension
is zero, 'header' and 'main_header' are the same.
"""
hdulist = fits.open(infile)
main_header = hdulist[0].header
header = hdulist[iext].header
image2d = hdulist[iext].data.astype(np.float)
# Only to ckeck the images dimensions
NAXIS1 = main_header.get('NAXIS1')
NAXIS2 = main_header.get('NAXIS2')
# print(NAXIS1)
# print(NAXIS2)
hdulist.close()
return image2d, main_header, header
def trimming_images(image2, offsetx, offsety):
"""Trimming of images.
Parameters
----------
image2 : 2d numpy array (float)
Successive ramps.(Not the first)
offsetx: int
Offset in x between image2 and image1
offysety: int
Offset in y between image2 and image1
Returns
-------
IMP2 : 2d numpy array, floats
Data array corresponding to trimmed image
"""
i1 = j1 = 0
i2 = image2.shape[0]
j2 = image2.shape[1]
IMP2= np.zeros((i2,j2))
if offsetx >= 0 and offsety > 0 :
IMP = image2[(i1+offsety):i2, j1:(j2-offsetx)]
IMP2[:(i2-offsety), (j1+offsetx):] = IMP
elif offsetx <= 0 and offsety < 0 :
IMP= image2[i1:(i2+offsety), (j1-offsetx):j2]
IMP2[(i1-offsety):,: (j2+offsetx)]=IMP
elif offsetx < 0 and offsety >= 0 :
IMP= image2[(i1+offsety):i2, (j1-offsetx):j2]
IMP2[:(i2-offsety), : (j2+offsetx)]=IMP
elif offsetx > 0 and offsety <= 0 :
IMP= image2[i1:(i2+offsety), j1:(j2-offsetx)]
IMP2[(i1-offsety):, (j1+ offsetx):]=IMP
else : # both offsets are zero
IMP2 = np.copy(image2)
return IMP2
if __name__ == "__main__":
# define expected command-line arguments
parser = argparse.ArgumentParser()
parser.add_argument("input_list",
help='"txt file with list of initial file names. Initial ramps"')
parser.add_argument("input_offsets",
help='"txt file with list of offsets between ramps"')
parser.add_argument("--cube_with_ramps",
help="generate cube with ramps",
action="store_true")
parser.add_argument("--trimmed_images",
help="generate the trimmed ramps",
action="store_true")
args = parser.parse_args()
# read list with file names
list_files = np.genfromtxt(args.input_list, dtype=[('filename_initial', '|S100')])
filename_initial = list_files['filename_initial']
nfiles_initial = filename_initial.size
# nfiles_initial = number of ramps
list_offsets = np.genfromtxt(args.input_offsets,
dtype=[('iflag', '<i8'), ('filename', '|S100'),('dark', '|S100'),
('offx', '<i8'), ('offy', '<i8')] )
filename = list_offsets['filename']
offx = list_offsets['offx']
offy = list_offsets['offy']
# Print the offsets between ramps
for val in zip(filename, offx, offy):
print(val)
if offx[0] != 0 or offy[0] != 0:
sys.exit("ERROR!!: Reference image has offsets different to zero")
naxis1 = 2048
naxis2 = 2048
image3d = np.zeros((nfiles_initial , naxis2, naxis1))
for k in range(nfiles_initial):
image, main_header, dum = readfits(filename_initial[k])
if image.shape != (naxis2, naxis1):
sys.exit("ERROR!!: unexpected image dimensions")
if k == 0:
image3d[0,:,:] = image[:,:]
else:
T_image = trimming_images(image, offx[k], -offy[k] )
image3d[k,:,:] = T_image[:,:]
median = np.median(image3d, axis=0)
# Generating the median image of the ramps
outfile2 = re.sub('ramp1.fits$', 'median.fits', filename_initial[0])
print("Generating the median of the ramps:\n" + outfile2)
hdu = fits.PrimaryHDU(median, main_header)
hdu.writeto(outfile2, clobber=True)
# Generating cube with the ramps (corrected the offsets)
# In principle we dont need generate the cube.fits
if args.cube_with_ramps:
outfile = re.sub('ramp1.fits$', 'cube_with_ramps.fits', filename_initial[0])
print("Generating datacube with all the ramps:\n" + outfile)
hdu = fits.PrimaryHDU(image3d, main_header)
hdu.writeto(outfile, clobber=True)
# Generating the trimmed images of the ramps.
# In principle we dont need generate the trimmed images
if args.trimmed_images:
list_cube_split = []
for k in range(nfiles_initial):
list_cube_split.append(image3d[k,:,:])
outfile1 = re.sub('.fits$', '_trimmed.fits', filename_initial[k])
print("Generating trimmed images:\n" + outfile1)
hdu = fits.PrimaryHDU(list_cube_split[k], main_header)
hdu.writeto(outfile1, clobber=True)
|
criscabe/CIRCE
|
code/Data_reduction/median_of_ramps.py
|
median_of_ramps.py
|
py
| 5,633 |
python
|
en
|
code
| 2 |
github-code
|
50
|
18051536698
|
# importando as lib necessárias
import pandas as pd
import zipfile
# Descompactando arquivo 'dados.zip'
with zipfile.ZipFile('dados.zip', 'r') as zip_dados:
zip_dados.extractall('C:\\Users\\Asus\\PycharmProjects')
# Criando dataframes com os arquivos cvs descompactados
df_origem = pd.read_csv('C:\\Users\\Asus\\PycharmProjects\\origem-dados.csv')
df_tipos = pd.read_csv('C:\\Users\\Asus\\PycharmProjects\\tipos.csv')
# Filtrando apenas as linhas onde 'status' é = a 'critico'
filtro = df_origem[df_origem['status'] == 'CRITICO']
# Mesclar resultado do filtro com df_tipos
filtro = pd.merge(filtro, df_tipos[['id', 'nome']], left_on='tipo', right_on='id', how='left')
#excluir a coluna 'id' que veio de df_tipos, pois não foi pedida no exercicio
filtro = filtro.drop('id', axis=1)
# Alterar nome da coluna 'nome' para nome_tipo
filtro = filtro.rename(columns={'nome': 'nome_tipo'})
#ordenar pela coluna 'created_at'
filtro = filtro.sort_values('created_at')
# Gerar o arquivo 'insert.sql'
with open('insert-dados.sql', 'w') as insert:
# ler cada linha do dataframe filtro
for index, row in filtro.iterrows():
values = (
row['created_at'],
row['product_code'],
row['customer_code'],
row['status'],
row['tipo'],
row['nome_tipo']
)
insert_stmt = "INSERT INTO dados_finais " \
"('created_at', 'product_code', 'customer_code', 'status', 'tipo', 'nome_tipo') " \
"VALUES ({}, {}, {}, {}, {}, {});\n".format(*values)
# Escrevendo no arquivo 'insert-dados.sql'
insert.write(insert_stmt)
print('Arquivo insert-dados.sql, gerado com sucesso!')
|
gustavofranco88/pandas
|
criar_arquivo_sql.py
|
criar_arquivo_sql.py
|
py
| 1,713 |
python
|
pt
|
code
| 0 |
github-code
|
50
|
74418461276
|
# https://stackoverflow.com/questions/34588464/python-how-to-capture-image-from-webcam-on-click-using-opencv
import cv2
import opencv.gridReaderFinal as gr
def screenshot(size: int):
'''Returns the grid from the captured image.
If no image was captured, returns empty string.
NOTE: Save path changes depending on which directory makes the call to this module.'''
return_grid = ""
cam = cv2.VideoCapture(1) # THIS LINE WILL CHANGE TO FIT DESIRED CAMERA
cv2.namedWindow("test")
ret, frame = cam.read()
if not ret:
print("Failed to grab frame: Camera not found")
else:
while True:
ret, frame = cam.read()
cv2.imshow("test", frame)
k = cv2.waitKey(1)
if k%256 == 27:
# ESC pressed
print("Escape hit, closing...")
break
elif k%256 == 32:
# SPACE pressed
img_name = "opencv_frame_0.png" # Same image gets overwritten with every capture. No multiple images
cv2.imwrite(img_name, frame)
print("{} written!".format(img_name))
res = gr.GridReader(img_name, size) # Grid size shouldn't be hardcoded for the future
return_grid = res.readGrid()
print(return_grid)
if cv2.getWindowProperty("test", cv2.WND_PROP_VISIBLE) < 1:
print("User pressed X on the window")
break
cam.release()
cv2.destroyAllWindows()
return return_grid
if __name__ == "__main__":
screenshot()
|
TimTwigg/Research
|
opencv/gridcapture.py
|
gridcapture.py
|
py
| 1,620 |
python
|
en
|
code
| 2 |
github-code
|
50
|
36363999649
|
from flask import Blueprint
from CTFd.plugins.challenges import BaseChallenge
from .models import DynamicInstanceChallenges
class DynamicInstanceChallenge(BaseChallenge):
id = "dynamic_instance" # Unique identifier used to register challenges
name = "dynamic_instance" # Name of a challenge type
templates = { # Templates used for each aspect of challenge editing & viewing
"create": "/plugins/CTFd-DCI/templates/create.html",
"update": "/plugins/CTFd-DCI/templates/update.html",
"view": "/plugins/CTFd-DCI/templates/view.html",
}
scripts = { # Scripts that are loaded when a template is loaded
"create": "/plugins/CTFd-DCI/assets/create.js",
"update": "/plugins/CTFd-DCI/assets/update.js",
"view": "/plugins/CTFd-DCI/assets/view.js",
}
# Route at which files are accessible. This must be registered using register_plugin_assets_directory()
route = "/plugins/CTFd-DCI/assets/"
# Blueprint used to access the static_folder directory.
blueprint = Blueprint(
"dynamic_instance",
__name__,
template_folder="templates",
static_folder="assets",
)
challenge_model = DynamicInstanceChallenges
|
PeronGH/CTFd-DCI
|
CTFd-DCI/challenge_type.py
|
challenge_type.py
|
py
| 1,219 |
python
|
en
|
code
| 0 |
github-code
|
50
|
3950322746
|
import speech_recognition as sr
r = sr.Recognizer()
# Define audio file
audio = 'peacock.wav'
# Process the audio file speech to text
with sr.AudioFile(audio) as source:
audio = r.record(source)
print('Done')
try:
text = r.recognize_google_cloud(audio)
print(text)
except Exception as e:
print(e)
|
MichaelZLai/interactive_notetaking
|
quick_stt.py
|
quick_stt.py
|
py
| 321 |
python
|
en
|
code
| 0 |
github-code
|
50
|
4893132817
|
def solve(ds):
n, m = [int(i) for i in ds[0].split(' ')]
fib = [1, 1]
for i in range(2, n, 1):
if 0 <= i - (m+1) < len(fib): # takes into account dying rabbits
temp = fib[i-2] + fib[i-1] - fib[i - (m+1)]
elif i == m: # first batch of dying rabbits
temp = fib[i-2] + fib[i-1] - 1
else: # before i == m
temp = fib[i-2] + fib[i-1]
fib.append(temp)
print(fib[-1])
if __name__ == '__main__':
f = open('ds.txt', 'r')
ds = [line.strip() for line in f]
solve(ds)
|
Plezo/rosalind_solutions
|
FIBD.py
|
FIBD.py
|
py
| 567 |
python
|
en
|
code
| 0 |
github-code
|
50
|
44561341438
|
#!/usr/bin/env python3
import pyquil.api as api
from classical import rand_graph, classical, bitstring_to_path, calc_cost
from pyquil.paulis import sI, sZ, sX, exponentiate_commuting_pauli_sum
from scipy.optimize import minimize
from pyquil.api import WavefunctionSimulator
from pyquil.gates import H
from pyquil import Program
from collections import Counter
from tsp_qaoa_updated import binary_state_to_points_order
import sys
# returns the bit index for an alpha and j
def bit(alpha, j):
return j * num_cities + alpha
def D(alpha, j):
b = bit(alpha, j)
return .5 * (sI(b) - sZ(b))
"""
weights and connections are numpy matrixes that define a weighted and unweighted graph
penalty: how much to penalize longer routes (penalty=0 pays no attention to weight matrix)
"""
def build_cost(penalty, num_cities, weights, connections):
ret = 0
# constraint (a)
for i in range(num_cities):
cur = sI()
for j in range(num_cities):
cur -= D(i, j)
ret += cur**2
# constraint (b)
for i in range(num_cities):
cur = sI()
for j in range(num_cities):
cur -= D(j, i)
ret += cur**2
# constraint (c)
for i in range(num_cities-1):
cur = sI()
for j in range(num_cities):
for k in range(num_cities):
if connections[j, k]:
cur -= D(j, i) * D(k, i+1)
ret += cur
# constraint (d) (the weighting)
for i in range(num_cities-1):
cur = sI()
for j in range(num_cities):
for k in range(num_cities):
if connections[j, k]:
cur -= D(j, i) * D(k, i+1) * weights[j, k]
ret += cur * penalty
return ret
def qaoa_ansatz(betas, gammas, h_cost, h_driver):
pq = Program()
pq += [exponentiate_commuting_pauli_sum(h_cost)(g) + exponentiate_commuting_pauli_sum(h_driver)(b) for g,b in zip(gammas,betas)]
return pq
def qaoa_cost(params, h_cost, h_driver, init_state_prog):
half = int(len(params)/2)
betas, gammas = params[:half], params[half:]
program = init_state_prog + qaoa_ansatz(betas, gammas, h_cost, h_driver)
return WavefunctionSimulator().expectation(prep_prog=program, pauli_terms=h_cost)
if __name__ == '__main__':
"""
sys.argv ARGS:
num_cities (int): number of cities in graph
# Example command line call:
python quantum.py 3
"""
name, num_cities = sys.argv
num_cities = int(num_cities)
best_path = None
best_cost = float("inf")
weights, connections = None, None
while not best_path:
weights, connections = rand_graph(num_cities)
best_cost, best_path = classical(weights, connections, loop=False)
num_bits = num_cities**2
num_params = 4
# Optimize parameters
init_state_prog = sum([H(i) for i in range(num_bits)], Program())
penalty = .01
h_cost = build_cost(penalty, num_cities, weights, connections)
h_driver = -1. * sum(sX(i) for i in range(num_bits))
result = minimize(qaoa_cost, x0=[.5]*num_params, args=(h_cost, h_driver, init_state_prog), method='Nelder-Mead')
betas, gammas = result.x[0:int(num_params/2)], result.x[int(num_params/2):]
qvm = api.QVMConnection()
# Sample the circuit for the most frequent path i.e. least costly
SAMPLES = 1000 # Number of samples
bitstring_samples = qvm.run_and_measure(qaoa_ansatz(betas, gammas, h_cost, h_driver), list(range(num_bits)), trials=SAMPLES)
best_quantum_cost = float("inf")
best_quantum_path = None
best_bitstring = None
for bitstring in bitstring_samples:
path = bitstring_to_path(bitstring)
if not path:
continue
cost = calc_cost(path, weights, connections)
if cost < best_quantum_cost:
best_quantum_cost = cost
best_quantum_path = path
best_bitstring = bitstring
print()
print("Output:")
print("=============")
print("Weights")
print(weights)
print("-------------")
print("Best quantum path")
print("(Cost = {}, Path = {})".format(best_quantum_cost, best_quantum_path))
print("-------------")
print("Classical solution:")
print("(Cost = {}, Path = {})".format(best_cost, best_path))
|
murphyjm/cs269q_radzihovsky_murphy_swofford
|
quantum.py
|
quantum.py
|
py
| 4,285 |
python
|
en
|
code
| 5 |
github-code
|
50
|
42088448727
|
# -*- coding: utf-8 -*-
import logging
import sys
from loguru import logger
class InterceptHandler(logging.Handler):
""" Intercept logging messages and reroute them to the loguru. """
def emit(self, record):
# Get corresponding Loguru level if it exists
try:
level = logger.level(record.levelname).name
except ValueError:
level = record.levelno
# Find caller from where originated the logged message
frame, depth = logging.currentframe(), 2
while frame.f_code.co_filename == logging.__file__:
frame = frame.f_back
depth += 1
(logger.opt(depth=depth, exception=record.exc_info)
.log(level, record.getMessage()))
logging.basicConfig(handlers=[InterceptHandler()], level=0)
# Put together a formatting string for the logger.
# Split into pieces to improve legibility.
tim_fmt = "<green>{time:YYYY-MM-DD HH:mm:ss}</green>"
lvl_fmt = "<level>{level: <8}</level>"
src_fmt = "<cyan>{module}</cyan>:<cyan>{function}</cyan>"
msg_fmt = "<level>{message}</level>"
fmt = " | ".join([tim_fmt, lvl_fmt, src_fmt, msg_fmt])
config = {
"handlers": [
{"sink": sys.stderr,
"level": "INFO",
"format": fmt},
# {"sink": "{time:YYYYMMDD_HHmmss}_crystalball.log",
# "level": "DEBUG",
# "format": fmt,
# }
],
}
logger.configure(**config)
|
caracal-pipeline/crystalball
|
crystalball/logger_init.py
|
logger_init.py
|
py
| 1,423 |
python
|
en
|
code
| 2 |
github-code
|
50
|
72242345115
|
import pytest
from flask import session
from conftest import create_test_game
from assassin_server.db_models import Players, Games, db, table_to_dict
#For this test we'll run a 10 person game
def test_mock_game(client, app):
game_size = 10
# Now we'll start the game!
players_info = create_test_game(client, game_size, 1)
game_code = None
with app.app_context():
game_code = db.session.query(
Players.game_code
).filter_by(
player_first_name = players_info[0]['player_first_name']
).first().game_code
creator_id = None
with app.app_context():
creator_id = db.session.query(
Players.player_id
).filter_by(
player_first_name = players_info[0]['player_first_name']
).first().player_id
assert isinstance(creator_id, int)
#make sure each player has a target, and that the targeting function has cycle length 4
with app.app_context():
current_id = creator_id
for i in range(game_size):
target_id = db.session.query(
Players.target_id
).filter_by(
player_id = current_id
).first().target_id
assert target_id is not None
if i < game_size-1:
assert target_id is not None and target_id != creator_id
else:
assert target_id == creator_id
current_id=target_id
# start getting players
# first we'll the first player get their target
dead_player_index = player_got_target(app, client, players_info, 0, False)
# now we'll find the index of a player other than the first who is alive. We'll let them win
winner_index = None
for i in range(1, game_size):
if i != dead_player_index:
winner_index = i
# find the number of players left
num_players_alive = None
with app.app_context():
num_players_alive = len(
db.session.query(
Players.player_id
).filter_by(
game_code = game_code
).all()
)
assert num_players_alive > 0
# kill all the other players
for i in range(num_players_alive-1):
if i == num_players_alive-2:
player_got_target(app, client, players_info, winner_index, True)
else:
player_got_target(app, client, players_info, winner_index, False)
# make sure there's 1 player left
with app.app_context():
num_players_alive = len(
db.session.query(
Players.player_id
).filter_by(
game_code = game_code
).all()
)
assert num_players_alive == 1
# finally the winner asks to be removed from the game
headers = {'Authorization' : 'Bearer ' + players_info[winner_index]['access_token']}
response=client.get(
'/player_access/remove_from_game',
headers=headers
)
assert response.status_code == 200
#Make sure both the winner and the game are deleted
with app.app_context():
assert db.session.query(
Players.player_id
).filter_by(
player_first_name = players_info[winner_index]['player_first_name']
).scalar() is None
assert db.session.query(
Players.player_id
).filter_by(
game_code = game_code
).scalar() is None
assert db.session.query(
Games.game_id
).filter_by(
game_code = game_code
).scalar() is None
# get's the target of a player and returns their new target's id
def player_got_target(app, client, players_info, getter_index, is_winning_got):
headers = {'Authorization' : 'Bearer ' + players_info[getter_index]['access_token']}
response=client.get(
'/player_access/request_target',
headers=headers
)
target_name = response.get_json()
assert response.status_code == 200
target_index = None
for i in range(len(players_info)):
if players_info[i]['player_first_name'] == target_name['target_first_name']:
target_index = i
target_kill_code = db.session.query(
Players.player_kill_code
).filter_by(
player_first_name = players_info[target_index]['player_first_name']
).first().player_kill_code
#get your target
headers=headers = {'Authorization' : 'Bearer ' + players_info[getter_index]['access_token']}
response=client.post(
'/player_access/got_target',
headers=headers,
json={'guessed_target_kill_code' : target_kill_code}
)
assert response.status_code == 200
assert response.get_json().get('win') == is_winning_got
headers = {'Authorization' : 'Bearer ' + players_info[target_index]['access_token']}
response=client.get(
'/player_access/remove_from_game',
headers=headers
)
assert response.status_code == 200
# make sure the target was killed and removed
with app.app_context():
assert db.session.query(
Players.player_id
).filter_by(
player_first_name =target_name['target_first_name']
).scalar() is None
assert db.session.query(
Players.target_first_name
).filter_by(
player_first_name = players_info[getter_index]['player_first_name']
).first().target_first_name != target_name['target_first_name']
return target_index
# In this game, the other player quits from a 2 person game
def test_quitter_game(app, client):
players_info = create_test_game(client, 2, 1)
# we'll find the game code
game_code = None
with app.app_context():
game_code = db.session.query(
Players.game_code
).filter_by(
player_first_name = players_info[0]['player_first_name']
).first().game_code
# we'll make the creator quit
headers = {'Authorization' : 'Bearer ' + players_info[0]['access_token']}
response=client.get(
'/player_access/quit_game',
headers=headers
)
assert response.status_code == 200
# make sure they're gone
with app.app_context():
assert db.session.query(
Players.player_id
).filter_by(
player_first_name = players_info[0]['player_first_name']
).scalar() is None
assert response.status_code == 200
# then the other player will check the game status
response = client.post(
'/status_access/game_state',
json={
'game_code':game_code
}
)
assert response.status_code == 200
assert response.get_json().get('game_state') == 2
# make sure there's 1 player left
with app.app_context():
num_players_alive = len(
db.session.query(
Players.player_id
).filter_by(
game_code = game_code
).all()
)
assert num_players_alive == 1
# now the winner asks to be removed from the game
headers = {'Authorization' : 'Bearer ' + players_info[1]['access_token']}
response=client.get(
'/player_access/remove_from_game',
headers=headers
)
assert response.status_code == 200
# make sure both the winner and the game are deleted
with app.app_context():
assert db.session.query(
Players.player_id
).filter_by(
player_first_name = players_info[1]['player_first_name']
).scalar() is None
assert db.session.query(
Players.player_id
).filter_by(
game_code = game_code
).scalar() is None
assert db.session.query(
Games.game_id
).filter_by(
game_code = game_code
).scalar() is None
|
grahamammal/comp225-server
|
tests/test_example_game.py
|
test_example_game.py
|
py
| 7,923 |
python
|
en
|
code
| 1 |
github-code
|
50
|
29597226637
|
from .views import *
from django.urls import path
urlpatterns = [
path('seller_blank_pages/', seller_blank_pages, name='seller_blank_pages'),
path('seller_bootstrap_alert/', seller_bootstrap_alert,name='seller_bootstrap_alert'),
path('seller_bootstrap_badge/',seller_bootstrap_badge,name='seller_bootstrap_badge'),
path('seller_bootstrap_breadcrumb/',seller_bootstrap_breadcrumb,name='seller_bootstrap_breadcrumb'),
path('seller_bootstrap_card/',seller_bootstrap_card,name='seller_bootstrap_card'),
path('seller_bootstrap_carousel/',seller_bootstrap_carousel,name='seller_bootstrap_carousel'),
path('seller_bootstrap_dropdown/',seller_bootstrap_dropdown,name='seller_bootstrap_dropdown'),
path('seller_bootstrap_list_group/',seller_bootstrap_list_group,name='seller_bootstrap_list_group'),
path('seller_bootstrap_modal/',seller_bootstrap_modal,name='seller_bootstrap_modal'),
path('seller_bootstrap_nav/',seller_bootstrap_nav,name='seller_bootstrap_nav'),
path('seller_bootstrap_pagination/',seller_bootstrap_pagination,name='seller_bootstrap_pagination'),
path('seller_bootstrap_progress/',seller_bootstrap_progress,name='seller_bootstrap_progress'),
path('seller_bootstrap_spinner/',seller_bootstrap_spinner,name='seller_bootstrap_spinner'),
path('seller_buttons/',seller_buttons,name='seller_buttons'),
path('seller_chart_apexcharts/',seller_chart_apexcharts,name='seller_chart_apexcharts'),
path('seller_chart_chartjs/',seller_chart_chartjs,name='seller_chart_chartjs'),
path('seller_chatboxs/',seller_chatboxs,name='seller_chatboxs'),
path('seller_component_avatar/',seller_component_avatar,name='seller_component_avatar'),
path('seller_component_hero/',seller_component_hero,name='seller_component_hero'),
path('seller_component_sweet_alert/',seller_component_sweet_alert,name='seller_component_sweet_alert'),
path('seller_component_toastify/',seller_component_toastify,name='seller_component_toastify'),
path('seller_credits/',seller_credits,name='seller_credits'),
path('seller_default/',seller_default,name='seller_default'),
path('seller_layout_top_navigation/',seller_layout_top_navigation,name='seller_layout_top_navigation'),
path('seller_editor/',seller_editor,name='seller_editor'),
path('seller_email/',seller_email,name='seller_email'),
path('seller_errors_403/',seller_errors_403,name='seller_errors_403'),
path('seller_errors_404/',seller_errors_404,name='seller_errors_404'),
path('seller_errors_500/',seller_errors_500,name='seller_errors_500'),
path('seller_errors_503/',seller_errors_503,name='seller_errors_503'),
path('seller_forgot_password/',seller_forgot_password,name='seller_forgot_password'),
path('seller_forms_checkbox/',seller_forms_checkbox,name='seller_forms_checkbox'),
path('seller_icons_boostrap/',seller_icons_boostrap,name='seller_icons_boostrap'),
path('seller_index/',seller_index,name='seller_index'),
path('seller_pricing/',seller_pricing,name='seller_pricing'),
path('seller_profile/',seller_profile,name='seller_profile'),
path('seller_radio/',seller_radio,name='seller_radio'),
path('seller_register/',seller_register,name='seller_register'),
path('seller_reset_password/',seller_reset_password,name='seller_reset_password'),
path('seller_header/',seller_header,name='seller_header'),
path('seller_forms_validation/',seller_forms_validation,name='seller_forms_validation'),
path('seller_widgets_email/',seller_widgets_email,name='seller_widgets_email'),
path('seller_login/',seller_login,name='seller_login'),
path('seller_logout/',seller_logout,name='seller_logout'),
path('seller_add_product/',seller_add_product,name='seller_add_product'),
path('seller_otp/' ,seller_otp, name='seller_otp' ),
path('my_product/' ,my_product, name='my_product' ),
path('product_edit/<int:pk>' ,product_edit, name='product_edit' ),
path('product_delete/<int:pk>' ,product_delete, name='product_delete' ),
]
|
JenilAnghan/Project
|
seller/urls.py
|
urls.py
|
py
| 4,052 |
python
|
en
|
code
| 0 |
github-code
|
50
|
42241845977
|
import multiprocessing
import ConfigParser
import sys
import os
CONF_FILE = "config.conf"
def get_physical_mem_size():
mem_bytes = os.sysconf('SC_PAGE_SIZE') * os.sysconf('SC_PHYS_PAGES')
mem_gib = round(mem_bytes/(1024.**3))
return mem_gib
def get_worker_threads_count():
cpu_count = multiprocessing.cpu_count()
mem_size = get_physical_mem_size()
if (mem_size <= cpu_count):
return cpu_count
max_threads = cpu_count * 5
return max_threads if mem_size >= max_threads else mem_size
def print_line(text="_"):
part = "_" * 30
line = part + text + part
print("\n{}\n".format(line[:70]))
def read_conf_file():
config = {}
conf = ConfigParser.SafeConfigParser()
if os.path.exists(CONF_FILE):
conf.read([CONF_FILE])
else:
return {}
for sec in conf.sections():
for k, v in conf.items(sec):
config[k] = v
return config
|
amit-pub/tasks
|
image-downloader/download-to-local-FS/util.py
|
util.py
|
py
| 933 |
python
|
en
|
code
| 1 |
github-code
|
50
|
8100032419
|
__author__ = "Noreddine Kessa"
__copyright__ = "!"
__license__ = "MIT License"
from NKTransitions import *
from NKTransition import *
class NKConfigToTransitions:
def __init__(self, ConfigPath=""):
self.ConfigPath =ConfigPath
self.transitions = NKTransitions(Name="" , initialState="" , errorSate ="")
def read(self , ConfigPath):
self.ConfigPath =ConfigPath
file1 = open(ConfigPath, 'r')
Lines = file1.readlines()
#Strips the newline character
for line in Lines:
print (f"Processing line:{line}")
words = line.split(",")
#process two words lines
if len (words) >=2:
if (words[0]=="$NAME"):
self.transitions.Name = words[1]
elif (words[0]=="$INITIALSTATE"):
self.transitions.initialState = words[1]
elif (words[0]=="$ERRORSTATE"):
self.transitions.errorSate = words[1]
#process multiple words lines
if len(words)>= 5:
if (words[0]=="$TRANSITION"):
self.transitions.append(NKTransition(OriginalState=words[1], Event=words[2], NewState=words[3] , TransitionHandler=words[4], Condition=words[5], Comment=words[6]))
#look for applicable OnEnter and OnExit handlers and add them to each transaction
for line in Lines:
words = line.split(",")
if len (words) >=2:
if (words[0]=="$ONEXIT"):
for transaction in self.transitions.transitions:
if transaction.OriginalState==words[1]:
transaction.setOnExit(words[2])
if (words[0]=="$ONENTER"):
for transaction in self.transitions.transitions:
if transaction.NewState==words[1]:
transaction.setOnEnter(words[2])
if (self.transitions.Name==""):
print("Error: $NAME not defind\n")
return False
if (self.transitions.initialState==""):
print("Error: $INITIALSTATE not defind\n")
return False
if (self.transitions.errorSate==""):
print("Error: $ERRORSTATE not defind\n")
return False
if len(self.transitions.transitions) <1:
print("Error: $TRANSITION not defind\n")
return False
return True
def getTransitions(self):
return self.transitions
|
knor12/NKFSMCompiler
|
NKFSMCompiler/NKConfigToTransitions.py
|
NKConfigToTransitions.py
|
py
| 2,837 |
python
|
en
|
code
| 0 |
github-code
|
50
|
15715570292
|
data = input()
# 0이나 1일 경우에는 더하는게 맞다.
answer = int(data[0])
for index in range(1, len(data)):
num = int(data[index])
if num <= 1 or answer <= 1:
answer += num
else:
answer *= num
print(answer)
|
BTOCC24/Algorithm
|
This is codingTest/그리디/곱하기 혹은 더하기/곱하기 혹은 더하기.py
|
곱하기 혹은 더하기.py
|
py
| 248 |
python
|
ko
|
code
| 1 |
github-code
|
50
|
28596250625
|
"""Implementation of the Skeleton model
"""
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../src')))
from classes import BaseModelImpl
from torch import nn
from layers.causalcall import CausalCallConvBlock
class CausalCallModel(BaseModelImpl):
"""CasualCall Model
"""
def __init__(self, convolution = None, decoder = None, load_default = False, *args, **kwargs):
super(CausalCallModel, self).__init__(*args, **kwargs)
"""
Args:
convolution (nn.Module): module with: in [batch, channel, len]; out [batch, channel, len]
decoder (nn.Module): module with: in [len, batch, channel]; out [len, batch, channel]
"""
self.convolution = convolution
self.decoder = decoder
if load_default:
self.load_default_configuration()
def forward(self, x):
"""Forward pass of a batch
"""
x = self.convolution(x)
x = x.permute(2, 0, 1) # [len, batch, channels]
x = self.decoder(x)
return x
def build_cnn(self):
num_blocks = 5
num_channels = 256
kernel_size = 3
dilation_multiplier = 2
dilation = 1
layers = list()
for i in range(num_blocks):
if i == 0:
layers.append(CausalCallConvBlock(kernel_size, num_channels, 1, dilation))
else:
layers.append(CausalCallConvBlock(kernel_size, num_channels, int(num_channels/2), dilation))
dilation *= dilation_multiplier
convolution = nn.Sequential(*layers)
return convolution
def get_defaults(self):
defaults = {
'cnn_output_size': 128,
'cnn_output_activation': 'relu',
'encoder_input_size': None,
'encoder_output_size': None,
'cnn_stride': 1,
}
return defaults
def load_default_configuration(self, default_all = False):
"""Sets the default configuration for one or more
modules of the network
"""
if self.convolution is None or default_all:
self.convolution = self.build_cnn()
self.cnn_stride = self.get_defaults()['cnn_stride']
if self.decoder is None or default_all:
self.decoder = self.build_decoder(encoder_output_size = 128, decoder_type = 'ctc')
self.decoder_type = 'ctc'
|
marcpaga/basecalling_architectures
|
models/causalcall/model.py
|
model.py
|
py
| 2,462 |
python
|
en
|
code
| 5 |
github-code
|
50
|
19601138102
|
from __future__ import annotations
from typing import Dict, TYPE_CHECKING, Union, Type
from assistants.deployments.aws.api_endpoint import ApiEndpointWorkflowState
from assistants.deployments.aws.api_gateway import ApiGatewayResponseWorkflowState
from assistants.deployments.aws.cloudwatch_rule import ScheduleTriggerWorkflowState
from assistants.deployments.aws.lambda_function import LambdaWorkflowState
from assistants.deployments.aws.sns_topic import SnsTopicWorkflowState
from assistants.deployments.aws.sqs_queue import SqsQueueWorkflowState
from assistants.deployments.diagram.errors import InvalidDeployment
from assistants.deployments.diagram.types import StateTypes, RelationshipTypes
if TYPE_CHECKING:
from assistants.deployments.diagram.workflow_states import WorkflowState
from assistants.deployments.aws.aws_deployment import AwsDeployment
WorkflowStateTypes = Type[Union[
LambdaWorkflowState, ApiEndpointWorkflowState, SqsQueueWorkflowState,
SnsTopicWorkflowState, ScheduleTriggerWorkflowState
]]
def workflow_state_from_json(credentials, deploy_diagram: AwsDeployment, workflow_state_json: Dict) -> WorkflowState:
node_id = workflow_state_json["id"]
node_type = workflow_state_json["type"]
try:
state_type = StateTypes(workflow_state_json["type"])
except ValueError as e:
raise InvalidDeployment(f"workflow state {node_id} has invalid type {node_type}")
state_type_to_workflow_state: Dict[StateTypes, WorkflowStateTypes] = {
StateTypes.LAMBDA: LambdaWorkflowState,
StateTypes.API_ENDPOINT: ApiEndpointWorkflowState,
StateTypes.SQS_QUEUE: SqsQueueWorkflowState,
StateTypes.SNS_TOPIC: SnsTopicWorkflowState,
StateTypes.SCHEDULE_TRIGGER: ScheduleTriggerWorkflowState,
StateTypes.API_GATEWAY_RESPONSE: ApiGatewayResponseWorkflowState
}
workflow_state_type = state_type_to_workflow_state.get(state_type)
if workflow_state_json is None:
raise InvalidDeployment(f"invalid workflow state type: {state_type} for workflow state: {node_id}")
workflow_state = workflow_state_type(
credentials,
workflow_state_json.get("id"),
workflow_state_json.get("name"),
state_type
)
workflow_state.setup(deploy_diagram, workflow_state_json)
return workflow_state
def workflow_relationship_from_json(deploy_diagram: AwsDeployment, workflow_relationship_json: Dict):
try:
relation_type = RelationshipTypes(workflow_relationship_json["type"])
except ValueError as e:
relation_id = workflow_relationship_json["id"]
relation_type = workflow_relationship_json["type"]
raise InvalidDeployment(f"workflow relationship {relation_id} has invalid type {relation_type}")
origin_node_id = workflow_relationship_json["node"]
next_node_id = workflow_relationship_json["next"]
origin_node = deploy_diagram.lookup_workflow_state(origin_node_id)
next_node = deploy_diagram.lookup_workflow_state(next_node_id)
origin_node.create_transition(
deploy_diagram, relation_type, next_node, workflow_relationship_json)
|
refinery-labs/refinery
|
api/assistants/deployments/aws/new_workflow_object.py
|
new_workflow_object.py
|
py
| 2,966 |
python
|
en
|
code
| 2 |
github-code
|
50
|
33862318363
|
class Solution:
def maxProfit(self, prices: List[int]) -> int:
dp = [0 for _ in range(len(prices) + 1)]
for i in range(1,len(prices)):
if dp[i]:
return dp[i]
dp[i] = max(0, dp[i-1] + prices[i] - prices[i-1])
return max(dp)
|
mykoabe/Competetive-Programming
|
All collections/121-best-time-to-buy-and-sell-stock/121-best-time-to-buy-and-sell-stock.py
|
121-best-time-to-buy-and-sell-stock.py
|
py
| 304 |
python
|
en
|
code
| 1 |
github-code
|
50
|
86766993796
|
# Django
from django.shortcuts import render_to_response, redirect, HttpResponseRedirect
from django.contrib.auth import authenticate, login
from django.contrib import messages
from django.conf import settings
from django.contrib.auth.decorators import login_required
# Apps
from misc.utils import * #Import miscellaneous functions
from apps.walls.utils import query_newsfeed
# Decorators
# Models
from django.contrib.auth.models import User
from apps.walls.models import Post, Comment
from notifications.models import Notification
# Forms
# View functions
# Misc
from django.templatetags.static import static
# Python
import os
# Docs for attachments
@login_required
def home (request, *args, **kwargs):
"""
The home page that people will see when the login or go to the root URL
- Redirects to newsfeed if logged in
- Redirects to login page if not logged in
"""
user = request.user
if settings.SOCIAL_AUTH_FORCE_FB and user.social_auth.filter(provider="facebook").count() == 0:
return redirect("apps.users.views.associate")
if user.is_authenticated(): # Check if user is already logged in
if "role" not in request.session.keys():
return HttpResponseRedirect(reverse("identity")) # Redirect to home page
return redirect("apps.home.views.newsfeed")
@login_required
def newsfeed(request):
user = request.user
notifications_list = query_newsfeed(user, page=1)
local_context = {
"current_page" : "newsfeed",
"notifications" : notifications_list,
}
return render_to_response("pages/newsfeed.html", local_context, context_instance= global_context(request))
@login_required
def portals(request):
# notifications = request.user.notifications.unread()
local_context = {}
return render_to_response("pages/portals.html", local_context, context_instance= global_context(request))
@login_required
def read_notification(request, notif_id):
user = request.user
if notif_id == "all":
all_notifs = user.notifications.unread()
for i in all_notifs:
i.public = False
i.save()
all_notifs.mark_all_as_read()
return redirect(reverse("newsfeed"))
try:
notif_id = int(notif_id)
except ValueError:
notif_id = None
if not ( type(notif_id) is int ):
raise InvalidArgumentTypeException
try:
notif = user.notifications.get(id = notif_id)
except Notification.DoesNotExist:
raise InvalidArgumentValueException
# Logic
notif.public = False #Use this to check if a notification was "read" by recipient, or another notif was added for same post
notif.save()
notif.mark_as_read()
return redirect(reverse("wall", kwargs={ "wall_id" : notif.target.wall.id }) + "#post_" + str(notif.target.id))
@login_required
def contacts(request):
local_context = {
}
return render_to_response("pages/contacts.html", local_context, context_instance= global_context(request))
@login_required
def markdown(request):
return HttpResponseRedirect("http://sourceforge.net/p/misaki/discussion/markdown_syntax")
|
The-WebOps-Club/fest-api
|
apps/home/views.py
|
views.py
|
py
| 3,170 |
python
|
en
|
code
| 12 |
github-code
|
50
|
5112566879
|
import http.client
domainFootballApi = "v3.football.api-sports.io"
keyFootballApi = "..."
headers = {
'x-apisports-key': keyFootballApi
}
def getRequest(queryLine):
connection = http.client.HTTPSConnection(domainFootballApi)
if (queryLine[0] != "/"):
queryLine = "/" + queryLine
connection.request("GET", queryLine, headers = headers)
response = connection.getresponse()
data = response.read()
dataDecoded = data.decode("utf-8")
return dataDecoded
def doesFootballClubPlayToday(footballClub):
queryLine = "/fixtures?live=all"
dataDecoded = getRequest(queryLine)
indexFootballClub = dataDecoded.find(footballClub)
if (indexFootballClub >= 0):
return True
else:
return False
|
petartotev/PT_Library_Python_UltimatePythotev
|
libraries/pythotev_library_http_football_api.py
|
pythotev_library_http_football_api.py
|
py
| 696 |
python
|
en
|
code
| 0 |
github-code
|
50
|
40158298450
|
import FWCore.ParameterSet.Config as cms
process = cms.Process("TEST")
process.options = cms.untracked.PSet(
numberOfStreams = cms.untracked.uint32(1)
)
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(3)
)
process.source = cms.Source("PoolSource",
fileNames = cms.untracked.vstring('file:testDetSetVectorThinningTest1.root')
)
process.slimmingTestA = cms.EDAnalyzer("ThinningDSVTestAnalyzer",
parentTag = cms.InputTag('thingProducer'),
thinnedTag = cms.InputTag('slimmingThingProducerA'),
associationTag = cms.InputTag('slimmingThingProducerA'),
trackTag = cms.InputTag('trackOfThingsProducerA'),
parentWasDropped = cms.bool(True),
thinnedSlimmedCount = cms.int32(1),
refSlimmedCount = cms.int32(1),
expectedParentContent = cms.VPSet(
cms.PSet(id = cms.uint32(1), values = cms.vint32(range(0,50))),
cms.PSet(id = cms.uint32(2), values = cms.vint32(range(50,100))),
cms.PSet(id = cms.uint32(3), values = cms.vint32(range(100,150))),
),
expectedThinnedContent = cms.VPSet(
cms.PSet(id = cms.uint32(1), values = cms.vint32(range(0,9))),
cms.PSet(id = cms.uint32(2), values = cms.vint32(range(50,59))),
cms.PSet(id = cms.uint32(3), values = cms.vint32(range(100,109))),
),
expectedIndexesIntoParent = cms.vuint32(
list(range(0,9)) +
list(range(50,59)) +
list(range(100,109))
),
expectedNumberOfTracks = cms.uint32(8*3),
expectedValues = cms.vint32(
list(range(0,9)) +
list(range(50,59)) +
list(range(100,109))
)
)
process.p = cms.Path(
process.slimmingTestA
)
|
cms-sw/cmssw
|
FWCore/Integration/test/DetSetVectorThinningTest2_cfg.py
|
DetSetVectorThinningTest2_cfg.py
|
py
| 1,656 |
python
|
en
|
code
| 985 |
github-code
|
50
|
11237801787
|
import os
import transformers
import pandas as pd
from utils import text_to_dataloader
from bert_embedding import BertEmbeddingExtractorVanilla
HEADER_CONST = "# sent_id = "
TEXT_CONST = "# text = "
STOP_CONST = "\n"
WORD_OFFSET = 1
LABEL_OFFSET = 3
NUM_OFFSET = 0
def txt_to_dataframe(data_path):
'''
read UD text file and convert to df format
'''
with open(data_path, "r") as fp:
df = pd.DataFrame(
columns={
"text",
"word",
"label"
}
)
for line in fp.readlines():
if TEXT_CONST in line:
words_list = []
labels_list = []
num_list = []
text = line.split(TEXT_CONST)[1]
# this is a new text, need to parse all the words in it
elif line is not STOP_CONST and HEADER_CONST not in line:
temp_list = line.split("\t")
num_list.append(temp_list[NUM_OFFSET])
words_list.append(temp_list[WORD_OFFSET])
labels_list.append(temp_list[LABEL_OFFSET])
if line == STOP_CONST:
# this is the end of the text, adding to df
cur_df = pd.DataFrame(
{
"text": len(words_list) * [text],
"word": words_list,
"word_offset": num_list,
"label": labels_list,
"word_count" : len(words_list)
}
)
df = pd.concat([df, cur_df])
return df
if __name__ == '__main__':
#MODEL_NAME = "bert-base-uncased"
MODEL_NAME = "roberta-base"
train_path = os.path.join("data", "en_partut-ud-train.conllu")
df_train = txt_to_dataframe(train_path)
bert_tokenizer = transformers.AutoTokenizer.from_pretrained(MODEL_NAME)
df_train, dataloader_train = text_to_dataloader(df_train.head(), "cuda", 32, bert_tokenizer, 256)
print()
bex = BertEmbeddingExtractorVanilla(1, MODEL_NAME)
embedding_df = bex.extract_embedding(dataloader_train, "sum")
print()
|
ErezSC42/bert_pos_analysis
|
test_embedding_extractor.py
|
test_embedding_extractor.py
|
py
| 2,169 |
python
|
en
|
code
| 0 |
github-code
|
50
|
1171679180
|
from launch import LaunchDescription
from ament_index_python.packages import get_package_share_directory
from launch_ros.actions import Node
from launch.actions import ExecuteProcess
import os.path
def generate_launch_description():
ld = LaunchDescription()
sim_node = Node(
package="robot_projects_simulator",
executable="ekf_sim_world",
output={"both": "screen"}
)
vis_node = Node(
package="rviz2",
executable="rviz2",
arguments=["-d", os.path.join(get_package_share_directory("robot_projects_ekf_localization"), "config", "ekf_sim_world.rviz")],
output={"both": "screen"}
)
test_act_node = Node(
package="teleop_twist_keyboard",
executable="teleop_twist_keyboard",
output='screen',
prefix = 'xterm -e'
)
topics = ['/cmd_vel', '/pt_sensor/reading', '/imu/reading', '/pose_sensor/reading', 'tf']
bag_process = ExecuteProcess(
cmd=['ros2', 'bag', 'record'] + topics
)
ld.add_action(sim_node)
ld.add_action(vis_node)
ld.add_action(test_act_node)
ld.add_action(bag_process)
return ld
|
lessthantrue/RobotProjects2
|
robot_projects_ekf_localization/launch/make_evaluate_bag.launch.py
|
make_evaluate_bag.launch.py
|
py
| 1,144 |
python
|
en
|
code
| 0 |
github-code
|
50
|
40577424537
|
import torch
from torch import optim
# Text text processing library and methods for pretrained word embeddings
import torchtext
from torchtext.vocab import Vectors, GloVe
# Named Tensor wrappers
from namedtensor import ntorch, NamedTensor
from namedtensor.text import NamedField
# Our input $x$
TEXT = NamedField(names=('seqlen',))
# Our labels $y$
LABEL = NamedField(sequential=False, names=(), unk_token=None)
train, val, test = torchtext.datasets.SST.splits(
TEXT, LABEL,
filter_pred=lambda ex: ex.label != 'neutral')
TEXT.build_vocab(train)
LABEL.build_vocab(train)
device=torch.device("cpu")
train_iter, val_iter, test_iter = torchtext.data.BucketIterator.splits(
(train, val, test), batch_size=10, device=device)
# Build the vocabulary with word embeddings
url = 'https://s3-us-west-1.amazonaws.com/fasttext-vectors/wiki.simple.vec'
TEXT.vocab.load_vectors(vectors=Vectors('wiki.simple.vec', url=url))
def test_code(model):
"All models should be able to be run with following command."
upload = []
# Update: for kaggle the bucket iterator needs to have batch_size 10
test_iter = torchtext.data.BucketIterator(test, train=False, batch_size=10)
for batch in test_iter:
# Your prediction data here (don't cheat!)
probs = model(batch.text)
# here we assume that the name for dimension classes is `classes`
_, argmax = probs.max('classes')
upload += argmax.tolist()
with open("predictions.txt", "w") as f:
f.write("Id,Category\n")
for i, u in enumerate(upload):
f.write(str(i) + "," + str(u) + "\n")
class logisticRegression(ntorch.nn.Module):
#uses binarized version
def __init__(self, vocabSize, embedSize):
super(logisticRegression, self).__init__()
self.vocabSize = vocabSize
self.embedSize = embedSize
# self.Wb = ntorch.nn.Linear(self.embedSize, 1)
#self.W = Variable ntorch.tensor(torch.zeros((self.vocabSize), requires_grad=True), ("vocab",)))
self.W = ntorch.nn.Linear(self.vocabSize, 1).spec("vocab", "singular")
#self.b = ntorch.tensor(0., names=())
self.lossfn = ntorch.nn.CrossEntropyLoss().spec("classes")
def predict(self, x):
# y = self.Wb
#y = (self.W.index_select('vocab', x.long()).sum('vocab') + self.b).sigmoid()
y_ = self.W(x).sigmoid().sum('singular').sigmoid() # this is a huge hack
y = ntorch.stack([y_, 1-y_], 'classes') #.log_softmax('classes')
return y
def forward(self, batchText):
x = self.convertToX(batchText)
return self.predict(x)
def convertToX(self, batchText):
#this function makes the feature vectors wth scatter
x = ntorch.tensor( torch.zeros(self.vocabSize, batchText.shape['batch'], device=device), ('vocab', 'batch'))
y = ntorch.tensor( torch.ones(batchText.shape['seqlen'], batchText.shape['batch'], device=device), ('seqlen', 'batch'))
x.scatter_('vocab', batchText, y, 'seqlen')
#print("len x:", len(x))
return x
def loss(self, batch):
prediction = self(batch.text) # probabilities
#print("predict", prediction)
#print('predict size', prediction.shape)
#print("label", batch.label)
return self.lossfn(prediction, batch.label)
def train(lrModel, dataset):
optimizer = optim.Adam(lrModel.parameters(), lr=0.01)
# in your training loop:
optimizer.zero_grad() # zero the gradient buffers
losses = []
for i, batch in enumerate(dataset):
optimizer.zero_grad() # zero the gradient buffers
loss = lrModel.loss(batch) #loss = (batch.label.float() - prediction).abs().sum('batch')
loss.backward()
optimizer.step()
losses.append(loss.item())
if i%200==0 and not i==0:
print(f"iteration {i}")
print(f"moving average loss={sum(losses[-1-100:-1])/100.}")
val_losses = []
for vbatch in val_iter:
val_losses.append( lrModel.loss(vbatch).item())
val_loss = sum(val_losses)/len(val_losses)
print(f"val loss: {val_loss}")
#import ipdb; ipdb.set_trace()
if __name__=='__main__':
#print("params", lr.parameters())
lrModel = logisticRegression(TEXT.vocab.vectors.size()[0], None)
for i in range(10):
print(f"epoch {i}")
train(lrModel, train_iter)
test_code(lrModel)
|
mtensor/cs287
|
ps1/logistic_regression.py
|
logistic_regression.py
|
py
| 4,453 |
python
|
en
|
code
| 0 |
github-code
|
50
|
24833699202
|
#öyle bir fonksiyon yazın ki kullanıcının adını gönderdiğinizde hoşgeldin isim yazsın.
isim=input("İsminizi yazın. :")
print("Hoşgeldin", isim)
#kendisine girilen sayının karesinin karesini hesaplasın.
sayi=int(input("Sayı gir:"))
def hesapla(a):
print(a*a*a*a)
hesapla(sayi)
#girilen bu sayının çift mi tek mi olduğunu ekrana yazsın.
def tekmi(b):
if b%2 == 0:
print("Bu sayı çift bir sayıdır.")
else:
print("Bu sayı tek bir sayıdır.")
tekmi(sayi)
|
progamerofTR/bilsem2
|
fonksiyon uygulama 2.py
|
fonksiyon uygulama 2.py
|
py
| 536 |
python
|
tr
|
code
| 0 |
github-code
|
50
|
27576108554
|
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 2 12:41:14 2021
@author: hp
"""
from flask import Flask, render_template, request
from wtforms import Form, TextAreaField, validators
import pickle
import sqlite3
import os
import numpy as np
import joblib
loaded_model=joblib.load(r"D:/ML_Project\model.pkl")
loaded_stop=joblib.load(r"D:/ML_Project\stopwords.pkl")
loaded_vec=joblib.load(r"D:/ML_Project\vectorizer.pkl")
app = Flask(__name__)
def classify(document):
label = {0: 'non-hate', 1: 'hate'}
X = loaded_vec.transform([document])
y = loaded_model.predict(X)[0]
proba = np.max(loaded_model.predict_proba(X))
if proba >= 0.85:
return label[0], proba
else:
return label[1], proba
class TweetForm(Form):
tweet = TextAreaField('',[validators.DataRequired(),validators.length(min=15)])
@app.route(r'/')
def index():
form = TweetForm(request.form)
return render_template('tweetform.html', form=form)
@app.route('/results', methods=['POST'])
def results():
form = TweetForm(request.form)
if request.method == 'POST' and form.validate():
tweet = request.form['tweet']
y, proba = classify(tweet)
print(proba)
return render_template('results.html', content=tweet, prediction=y, probability=round(proba*100, 2))
return render_template('tweetform.html', form=form)
if __name__ == '__main__':
app.run(debug=True)
|
ankitaanjali1202/Twitter-Senti-Meter
|
app.py
|
app.py
|
py
| 1,464 |
python
|
en
|
code
| 1 |
github-code
|
50
|
31023238558
|
import pygame
import time
import random
from pygame.locals import*
from time import sleep
############################
########## Mario ###########
############################
class Mario():
def __init__(self, model):
self.model = model
self.x = 0
self.y = 0
self.model.scrollPos = self.x - 350
self.prev_x = 0
self.prev_y = 0
self.w = 60
self.h = 95
self.vvel = 0
self.mframe = 0
self.facingRight = True
self.runningRight = False
self.runningLeft = False
self.onTop = False
self.marioPics = []
self.marioPics.append(pygame.image.load("mario1.png"))
self.marioPics.append(pygame.image.load("mario2.png"))
self.marioPics.append(pygame.image.load("mario3.png"))
self.marioPics.append(pygame.image.load("mario4.png"))
self.marioPics.append(pygame.image.load("mario5.png"))
self.marioPics.append(pygame.image.load("mario1left.png"))
self.marioPics.append(pygame.image.load("mario2left.png"))
self.marioPics.append(pygame.image.load("mario3left.png"))
self.marioPics.append(pygame.image.load("mario4left.png"))
self.marioPics.append(pygame.image.load("mario5left.png"))
def collision(self, x, y, w, h):
if self.x + self.w <= x:
return False
if self.x >= x + w:
return False
if self.y + self.h <= y:
return False
if self.y >= y + h:
return False
return True
def leaveBlock(self, x, y, w, h):
if self.y + self.h > y and self.prev_y + self.h <= y:
self.vvel = 0
self.y = y - self.h
self.onTop = True
if self.y < y + h and self.prev_y >= y + h:
self.y = y + h
self.vvel = 0.1
if self.x + self.y > x and self.prev_x + self.w <= x:
self.runningRight = False
self.model.scrollPos = x - 350 - self.w
self.x = x - self.w
if self.x < x + w and self.prev_x >= x + w:
self.runningLeft = False
self.model.scrollPos = x - 350 + w
self.x = x + w
def notePrevious(self):
self.prev_x = self.x
self.prev_y = self.y
def update(self):
#gravity
self.vvel += 3.14159
self.y += self.vvel
#ground
if self.y > 355:
self.y = 355
self.vvel = 0
#run
if self.runningLeft:
self.x -= 10
self.model.scrollPos -= 10
self.facingRight = False
if self.runningRight:
self.x +=10
self.model.scrollPos += 10
self.facingRight = True
#collision detection
if self.collision(self.model.brick1.x, self.model.brick1.y, self.model.brick1.w, self.model.brick1.h):
self.leaveBlock(self.model.brick1.x, self.model.brick1.y, self.model.brick1.w, self.model.brick1.h)
if self.collision(self.model.brick2.x, self.model.brick2.y, self.model.brick2.w, self.model.brick2.h):
self.leaveBlock(self.model.brick2.x, self.model.brick2.y, self.model.brick2.w, self.model.brick2.h)
if self.collision(self.model.coinBlock1.x, self.model.coinBlock1.y, self.model.coinBlock1.w, self.model.coinBlock1.h):
self.leaveBlock(self.model.coinBlock1.x, self.model.coinBlock1.y, self.model.coinBlock1.w, self.model.coinBlock1.h)
if self.collision(self.model.coinBlock2.x, self.model.coinBlock2.y, self.model.coinBlock2.w, self.model.coinBlock2.h):
self.leaveBlock(self.model.coinBlock2.x, self.model.coinBlock2.y, self.model.coinBlock2.w, self.model.coinBlock2.h)
############################
########## Brick ###########
############################
class Brick():
def __init__(self, x, y):
self.x = x
self.y = y
self.w = 100
self.h = 100
self.brickPic = pygame.image.load("Brick_Block.png")
############################
######## CoinBlock #########
############################
class CoinBlock():
def __init__(self, model, x, y):
self.x = x
self.y = y
self.w = 90
self.h = 90
self.coinCount = 5
self.model = model
self.coinBlockPic = pygame.image.load("coinBlock2.png")
self.emptyCoinBlockPic = pygame.image.load("emptyCoinBlock2.png")
def update(self):
if(self.model.mario.y == self.y + self.h and self.model.mario.x + self.model.mario.w > self.x and self.model.mario.x < self.x + self.w):
if self.coinCount > 0:
self.vvelocity = -30.0
self.n = random.randint(1, 50)
if self.n%2 == 0:
self.hvelocity = self.n%15
else:
self.hvelocity = -(self.n%15)
self.model.coins.append(Coin(self.hvelocity, self.vvelocity, self.x, self.y, self.model))
self.coinCount -= 1
############################
########## Coin ############
############################
class Coin():
def __init__(self, hvel, vvel, x, y, model):
self.x = x
self.y = y
self.w = 0
self.h = 0
self.hvel = hvel
self.vvel = vvel
self.model = model
self.coinPic = pygame.image.load("coin.png")
def update(self):
self.vvel += 3.14159
self.y += self.vvel
self.x += self.hvel
if self.y > 1000:
self.vvel = 0
self.hvel = 0
self.y = 1000
############################
########## Model ###########
############################
class Model():
def __init__(self):
self.scrollPos = 0
self.mario = Mario(self)
self.brick1 = Brick(100, 200)
self.brick2 = Brick(600, 350)
self.coinBlock1 = CoinBlock(self, 900, 200)
self.coinBlock2 = CoinBlock(self, 1200, 230)
self.coins = list(())
def update(self):
self.mario.update()
self.coinBlock1.update()
self.coinBlock2.update()
for i in range(len(self.coins)):
self.coins[i].update()
############################
########## View ############
############################
class View():
def __init__(self, model):
screen_size = (800,600)
self.screen = pygame.display.set_mode(screen_size, 32)
self.model = model
self.model.rect = self.model.mario.marioPics[0].get_rect()
self.model.rect = self.model.brick1.brickPic.get_rect()
def update(self):
#draw the sky(sunny)
self.screen.fill([0,200,200])
#draw the ground
pygame.draw.rect(self.screen, (0, 128, 0), (0, 450, 800, 600))
#draw bricks
self.screen.blit(self.model.brick1.brickPic, (self.model.brick1.x - self.model.scrollPos, self.model.brick1.y), self.model.rect)
self.screen.blit(self.model.brick2.brickPic, (self.model.brick2.x - self.model.scrollPos, self.model.brick2.y), self.model.rect)
#draw coin blocks
if self.model.coinBlock1.coinCount > 0:
self.screen.blit(self.model.coinBlock1.coinBlockPic, (self.model.coinBlock1.x - self.model.scrollPos, self.model.coinBlock1.y), self.model.rect)
else:
self.screen.blit(self.model.coinBlock1.emptyCoinBlockPic, (self.model.coinBlock1.x - self.model.scrollPos, self.model.coinBlock1.y), self.model.rect)
if self.model.coinBlock2.coinCount > 0:
self.screen.blit(self.model.coinBlock2.coinBlockPic, (self.model.coinBlock2.x - self.model.scrollPos, self.model.coinBlock2.y), self.model.rect)
else:
self.screen.blit(self.model.coinBlock2.emptyCoinBlockPic, (self.model.coinBlock2.x - self.model.scrollPos, self.model.coinBlock2.y), self.model.rect)
#draw the coins
for i in range(len(self.model.coins)):
self.screen.blit(self.model.coins[i].coinPic, (self.model.coins[i].x - self.model.scrollPos, self.model.coins[i].y - 30), self.model.rect)
#animate mario
if self.model.mario.facingRight: #if he's facing right, animate right
#increment mframe
self.model.mario.mframe+=1
if self.model.mario.mframe > 4: self.model.mario.mframe = 0
#if keyRight and mario is on a surface, draw him running
if self.model.mario.runningRight and (self.model.mario.onTop or self.model.mario.y == 355):
self.screen.blit(self.model.mario.marioPics[self.model.mario.mframe], (350, self.model.mario.y), self.model.rect)
#else draw him standing still
else: self.screen.blit(self.model.mario.marioPics[3], (350, self.model.mario.y), self.model.rect)
else: #if he's facing left, animate left
#increment mframe
self.model.mario.mframe+=1
if self.model.mario.mframe < 5 or self.model.mario.mframe > 9: self.model.mario.mframe = 5
#if keyLeft and mario is on a surface, draw him running
if self.model.mario.runningLeft and (self.model.mario.onTop or self.model.mario.y == 355):
self.screen.blit(self.model.mario.marioPics[self.model.mario.mframe], (350, self.model.mario.y), self.model.rect)
#else draw him standing still
else: self.screen.blit(self.model.mario.marioPics[7], (350, self.model.mario.y), self.model.rect)
#idk
pygame.display.flip()
############################
####### Controller #########
############################
class Controller():
def __init__(self, model):
self.model = model
self.keep_going = True
def update(self):
for event in pygame.event.get():
if event.type == QUIT:
self.keep_going = False
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
self.keep_going = False
keys = pygame.key.get_pressed()
self.model.mario.notePrevious()
self.model.mario.runningRight = False
self.model.mario.runningLeft = False
if keys[K_LEFT]:
self.model.mario.runningLeft = True
if keys[K_RIGHT]:
self.model.mario.runningRight = True
if keys[K_SPACE] and (self.model.mario.y == 355 or self.model.mario.onTop) and self.model.mario.vvel == 0:
self.model.mario.vvel = -35
############################
########## Main ############
############################
print("Use the arrow keys to move. Press Esc to quit.")
pygame.init()
m = Model()
v = View(m)
c = Controller(m)
while c.keep_going:
c.update()
m.update()
v.update()
sleep(0.04)
print("Goodbye")
|
wws002/pyMario
|
game.py
|
game.py
|
py
| 9,260 |
python
|
en
|
code
| 0 |
github-code
|
50
|
23781955007
|
from cube import Config
from cube.activities.utils import Utils
import subprocess, os
from shutil import copyfile
# the alignment file probably needs to be checked
class Conservationist:
def __init__(self, upload_handler):
# directories
self.job_id = upload_handler.job_id
self.workdir = "{}/{}".format(Config.WORK_DIRECTORY, self.job_id)
self.work_path = "{}/{}".format(Config.WORK_PATH, self.job_id)
# input
self.original_seqfile_path = upload_handler.original_seqfile_path
self.seq_input_types = upload_handler.seq_input_types
self.input_aligned = upload_handler.aligned
self.original_structure_path = upload_handler.original_structure_path
self.chain = upload_handler.chain if upload_handler.chain else "-"
self.ref_seq_name = upload_handler.ref_seq_name
self.method = upload_handler.method
# output
self.specs_outname = "specs_out"
self.png_input = "png_in"
self.illustration_range = 400
self.run_ok = False
self.errmsg = None
self.score_file = None
self.png_files = []
self.preprocessed_afa = ""
self.xls = None
self.pdbseq = None
self.clean_structure_path = None
self.pse_zip = None
self.pml = None
self.workdir_zip = None
self.warn = None
# toolbox
self.utils = Utils(self.job_id)
return
def _write_cmd_file(self):
prms_string = ""
prms_string += "patch_sim_cutoff 0.4\n"
prms_string += "patch_min_length 0.4\n"
prms_string += "sink 0.3 \n"
prms_string += "skip_query \n"
prms_string += "\n"
prms_string += "align %s\n" % self.preprocessed_afa
prms_string += "refseq %s\n" % self.ref_seq_name
prms_string += "method %s\n" % self.method
prms_string += "\n";
prms_string += "outn %s/%s\n" % (self.work_path, self.specs_outname)
if self.clean_structure_path:
prms_string += "pdbf %s\n" % self.clean_structure_path
prms_string += "pdbseq %s\n" % self.pdbseq
#dssp_file && (prms_string += "dssp dssp_file\n");
outf = open("%s/cmd"%self.work_path, "w")
outf.write(prms_string)
outf.close()
def prepare_run(self):
self.preprocessed_afa = self.utils.construct_afa_name(self.original_seqfile_path)
if self.input_aligned:
filetype = self.seq_input_types[self.original_seqfile_path]
if filetype=='fasta':
# TODO check all seqs the same length
copyfile(self.original_seqfile_path, self.preprocessed_afa)
elif filetype=='gcg':
# convert to afa
if not self.utils.msf2afa(self.original_seqfile_path, self.preprocessed_afa):
self.errmsg = self.utils.errmsg
return None
# again check if the same length
else:
# if not aligned - align
if not self.utils.align(self.original_seqfile_path, self.preprocessed_afa):
self.errmsg = self.utils.errmsg
return None
# choose reference sequence if we do not have one
if not self.ref_seq_name:
cmd = "grep '>' {} | head -n1".format(self.preprocessed_afa)
output = subprocess.run([cmd], stdout=subprocess.PIPE, shell=True).stdout
self.ref_seq_name = output[1:].decode('utf8').strip().split(" ")[0]
# restrict to query
afa_prev = self.preprocessed_afa
restrict_to_qry_script = "{}/{}".format(Config.SCRIPTS_PATH, Config.SCRIPTS['restrict_afa_to_query'])
self.preprocessed_afa = "{}/alnmt_restricted_to_ref_seq.afa".format(self.work_path)
cmd = "{} {} {} > {}".format(restrict_to_qry_script, afa_prev, self.ref_seq_name, self.preprocessed_afa)
process = subprocess.run([cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
if process.returncode!=0:
self.warn = "Problem restricting to reference sequence"
self.preprocessed_afa = afa_prev
# cleanup pdb and extract chain
afa_prev = self.preprocessed_afa
if self.original_structure_path:
# (note that it will also produce file with the corresponding sequence)
pdb_cleanup_script = "{}/{}".format(Config.SCRIPTS_PATH, Config.SCRIPTS['pdb_cleanup'])
self.pdbseq = ".".join(self.original_structure_path.split("/")[-1].split(".")[:-1])+self.chain
cmd = "{} {} {} {} {}".format(pdb_cleanup_script, self.original_structure_path,
self.pdbseq, self.chain, self.work_path)
process = subprocess.run([cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
if process.returncode!=0:
self.original_structure_path = None
self.warn = "Problem with the structure file"
else:
self.clean_structure_path = "{}/{}.pdb".format(self.work_path, self.pdbseq)
# align pdbseq to the rest of the alignment
mafft = Config.DEPENDENCIES['mafft']
self.preprocessed_afa = "{}/alnmt_w_pdb_seq.afa".format(self.work_path)
cmd = "{} --add {} {} > {}".format(mafft, self.clean_structure_path.replace('.pdb', '.seq'), afa_prev, self.preprocessed_afa)
process = subprocess.run([cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
if process.returncode!=0:
self.preprocessed_afa = afa_prev
self.warn = "Problem running mafft"
self.original_structure_path = None
return None
self._write_cmd_file()
return True
def check_run_ok(self, process):
if process.returncode != 0:
self.errmsg = process.stdout.decode("utf-8").strip()
self.errmsg += process.stderr.decode("utf-8").strip()
self.run_ok = False
return False
if "Unrecognized amino acid code" in process.stdout.decode("utf-8"):
self.errmsg = process.stdout.decode("utf-8")
self.run_ok = False
return False
self.score_file = "{}/{}.score".format(self.work_path, self.specs_outname)
return True
def conservation_map(self):
# extract the input for the java file
specs_score_file = "{}/{}.score".format(self.work_path, self.specs_outname)
inf = open(specs_score_file,"r")
png_input_file = "{}/{}".format(self.work_path, self.png_input)
outf = open(png_input_file,"w")
resi_count = 0
for line in inf:
fields = line.split()
if '%' in fields[0] or '.' in fields[3]: continue
outf.write(" ".join([fields[2], fields[3], fields[4]])+"\n")
resi_count += 1
inf.close()
outf.close()
pngmaker = Config.LIBS['seqreport.jar']
png_root = 'conservation_map'
for i in range(0,resi_count, self.illustration_range):
seq_frm = i+1
seq_to = min(resi_count, i+self.illustration_range)
out_fnm = "{}.{}_{}" .format(png_root, seq_frm, seq_to)
cmd = f"java -jar {pngmaker} {png_input_file} {self.work_path}/{out_fnm} {seq_frm} {seq_to} "
cmd += f" > {self.work_path}/seqreport.out 2>&1"
process = subprocess.run([cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
if process.returncode==0:
self.png_files.append(out_fnm+".png")
return
def excel_spreadsheet(self):
output_name_root = "conservation_on_the_sequence"
output_path = "{}/{}".format(self.work_path, output_name_root)
# if we have the annotation, add the annotation
#
xls_script = "{}/{}".format(Config.SCRIPTS_PATH, Config.SCRIPTS['specs2xls'])
# the basic input is the specs score file
cmd = "{} {} {}".format(xls_script, self.score_file, output_path)
process = subprocess.run([cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
if process.returncode==0:
self.xls = "{}/{}.xls".format(self.workdir,output_name_root)
return
def pymol_script(self):
pml_args = [self.original_structure_path, self.method, self.score_file, self.chain]
ret = self.utils.pymol_script("cons", pml_args)
if ret: [self.pml, self.pse_zip] = ret
def directory_zip(self):
curr = os.getcwd()
os.chdir(Config.WORK_PATH)
shellzip = Config.DEPENDENCIES['zip']
archive_name = "cube_workdir_{}.zip".format(self.job_id)
cmd = "{} -r {} {} > /dev/null ".format(shellzip, archive_name, self.job_id)
process = subprocess.run([cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
if process.returncode ==0:
os.rename(archive_name, "{}/{}".format(self.work_path, archive_name))
self.workdir_zip = "{}/{}".format(self.workdir, archive_name)
os.chdir(curr)
return
###################################################
def run(self):
os.mkdir(self.work_path)
### from this point on we are in the workdir
currpath = os.getcwd()
os.chdir(self.work_path)
### prepare
if not self.prepare_run(): return
### specs
specs = Config.DEPENDENCIES['specs']
cmd = "{} {}/cmd ".format(specs, self.work_path)
process = subprocess.run([cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
### check specs finshed ok
if not self.check_run_ok(process): return
### postprocess
self.conservation_map()
self.excel_spreadsheet()
self.pymol_script()
self.directory_zip()
self.run_ok = True
return
|
ivanamihalek/cube_server
|
cube/activities/conservation.py
|
conservation.py
|
py
| 8,595 |
python
|
en
|
code
| 0 |
github-code
|
50
|
10860308596
|
from AsyncDjangoApp.celery import app
from App.models import Tasks
from time import sleep
import random
@app.task(bind=True)
def process(self, job_name=None):
b = Tasks(task_id=self.request.id, job_name=job_name)
b.save()
self.update_state(state='Dispatching', meta={'progress': '33'})
sleep(random.randint(5, 10)) # pre-processing the dataset in machine learning pipeline,...
self.update_state(state='Running', meta={'progress': '66'})
sleep(random.randint(5, 10)) # training the algorithm,...
self.update_state(state='Finishing', meta={'progress': '100'})
sleep(random.randint(5, 10)) # reporting metrics, saving the model,...
|
mahdi-ghelichi/AsyncDjangoApp
|
App/tasks.py
|
tasks.py
|
py
| 671 |
python
|
en
|
code
| 7 |
github-code
|
50
|
17169184421
|
from collections import OrderedDict
import json
from .logger import Logger
from .handlers import ConsoleHandler, JsonFileHandler
json_serializer = json.dumps
STR_FMT_DICT = dict(
progress=' [{0: <20}]',
metrics=' [{0: <28}]',
default=' [{0: <10}]'
)
def get_str_format(key):
if key not in STR_FMT_DICT:
key = 'default'
return STR_FMT_DICT[key]
class ConsoleFormatter:
def __init__(self):
pass
def __call__(self, message):
now = message['time']
log_str = '{}-{}'.format(now.strftime('%y/%m/%d'), now.strftime('%H:%M:%S'))
for key in message:
if key == 'time':
continue
_msg = message[key]
if isinstance(_msg, dict):
_msg_list = [f'{k}: {v}' for k, v in _msg.items()]
_log_str = ' '.join(_msg_list)
else:
_log_str = f'{key}: {_msg}'
log_str += get_str_format(key).format(_log_str)
log_str += '\n'
return log_str
class JsonFormatter:
def __init__(self):
pass
def __call__(self, message):
_message = message.copy()
now = _message['time']
_message['time'] = OrderedDict(
timestamp=now.timestamp(),
date=now.strftime('%y/%m/%d'),
time=now.strftime('%H:%M:%S')
)
log_str = "{}\n".format(json_serializer(_message))
return log_str
class TrainingLogger(Logger):
def __init__(self, log_name, handlers=[], **kwargs):
handlers = [
ConsoleHandler(formatter=ConsoleFormatter()),
JsonFileHandler(
formatter=JsonFormatter(), filepath=log_name, flush_freq=10)
]
super().__init__(handlers=handlers)
|
Deep-Spark/DeepSparkHub
|
cv/semantic_segmentation/unet3d/pytorch/ixpylogger/training_logger.py
|
training_logger.py
|
py
| 1,769 |
python
|
en
|
code
| 28 |
github-code
|
50
|
28333036923
|
# A* Search Algorithm
#
# let openList equal empty list of nodes
# let closedList equal empty list of nodes
# put startNode on the openList (leave it's f at zero)
# while openList is not empty
# let currentNode equal the node with the least f value
# remove currentNode from the openList
# add currentNode to the closedList
# if currentNode is the goal
# You've found the exit!
# let children of the currentNode equal the adjacent nodes
# for each child in the children
# if child is in the closedList
# continue to beginning of for loop
# child.g = currentNode.g + distance b/w child and current
# child.h = distance from child to end
# child.f = child.g + child.h
# if child.position is in the openList's nodes positions
# if child.g is higher than the openList node's g
# continue to beginning of for loop
# add the child to the openList
class Graph:
def __init__(self, adjacency_list):
self.adjacency_list = adjacency_list
def get_neighbors(self, v):
return self.adjacency_list[v]
# heuristic function with distances from the current node to the goal node
def h(self, n):
H = {
'A': 11,
'B': 6,
'C': 99,
'D': 1,
'E': 7,
'G': 0
}
return H[n]
def a_star_algorithm(self, start_node, stop_node):
# open_list is a list of nodes which have been visited, but who's neighbors
# haven't all been inspected, starts off with the start node
# closed_list is a list of nodes which have been visited
# and who's neighbors have been inspected
open_list = set([start_node])
closed_list = set([])
# g contains current distances from start_node to all other nodes
# the default value (if it's not found in the map) is +infinity
g = {}
g[start_node] = 0
# parents contains an adjacency map of all nodes
parents = {}
parents[start_node] = start_node
while len(open_list) > 0:
n = None
# find a node with the lowest value of f() - evaluation function
for v in open_list:
if n == None or g[v] + self.h(v) < g[n] + self.h(n):
n = v;
if n == None:
print('Path does not exist!')
return None
# if the current node is the stop_node
# then we begin reconstructin the path from it to the start_node
if n == stop_node:
reconst_path = []
while parents[n] != n:
reconst_path.append(n)
n = parents[n]
reconst_path.append(start_node)
reconst_path.reverse()
print('Path found: {}'.format(reconst_path))
return reconst_path
# for all neighbors of the current node do
for (m, weight) in self.get_neighbors(n):
# if the current node isn't in both open_list and closed_list
# add it to open_list and note n as it's parent
if m not in open_list and m not in closed_list:
open_list.add(m)
parents[m] = n
g[m] = g[n] + weight
# otherwise, check if it's quicker to first visit n, then m
# and if it is, update parent data and g data
# and if the node was in the closed_list, move it to open_list
else:
if g[m] > g[n] + weight:
g[m] = g[n] + weight
parents[m] = n
if m in closed_list:
closed_list.remove(m)
open_list.add(m)
# remove n from the open_list, and add it to closed_list
# because all of his neighbors were inspected
open_list.remove(n)
closed_list.add(n)
print('Path does not exist!')
return None
adjac_lis = {
'A': [('B', 2), ('E', 3)],
'B': [('C', 1), ('G', 9)],
'C': None,
'D': [('G', 1)],
'E': [('D', 6)]
}
graph = Graph(adjac_lis)
graph.a_star_algorithm('A', 'G')
|
PROxZIMA/Academic-Codes
|
Semester 6/LP2/A2/A2.py
|
A2.py
|
py
| 4,343 |
python
|
en
|
code
| 47 |
github-code
|
50
|
886111389
|
import os
import subprocess
import math
import random as rd
import numpy as np
import automated_compiling as autcom
NbDim = 8 # 5 elts in a solution (n1,n2,n3,nb_t,nb_it,tblk1,tblk2,tblk3) (opt and simdType not used yet)
size = 256
lmin = [32, 32, 32, 1, 100, 16, 16, 16]
lmax = [272, 272, 272, 8, 100, 80, 80, 80]
def rand_multiple(fac, a, b):
"""Returns a random multiple of fac between a and b."""
min_multi = math.ceil(float(a) / fac)
max_multi = math.floor(float(b) / fac)
return fac * rd.randint(min_multi, max_multi)
def generateS0():
# rd.seed(Me+1000*(1+SeedInc))
S0 = np.empty(NbDim,dtype=np.int)
for i in range(NbDim):
if(i == 0 or i == 5 or i == 6 or i == 7 ):
S0[i] = rand_multiple(16, lmin[i], lmax[i]+1)
elif (i == 4):
S0[i] = 100
else:
S0[i] = rd.randrange(lmin[i],lmax[i]+1,1)
return(S0)
def Neighborhood(S, param_indices):
LNgbh = []
for i in param_indices:
S1 = S.copy()
if(i == 0 or i == 5 or i == 6 or i == 7):
S1[i] += 16
if S1[i] <= lmax[i]:
LNgbh.append(S1)
S2 = S.copy()
if(i == 0 or i == 5 or i == 6 or i == 7):
S1[i] -= 16
if S2[i] >= lmin[i]:
LNgbh.append(S2)
return LNgbh
def HillClimbing(S0,IterMax,param_list,cost_type): #T0, la, ltl unused in HC
#SO: initial solution
#IterMax: max nb of iteration
#T0: initial temperature for "simulated annealing"
#la: T = T*la: temperature evolution law for "simulated annealing"
#ltl: length of Tabu list for "Tabu List" method
#simIdx: version of the simulator (cost function)
Sb = S0
eb = autcom.Cost(Sb, cost_type = "flops")
iter = 0
#local search
S = Sb
LNgbh = Neighborhood(S, param_list)
LNgbh = Neighborhood(S, param_list)
while iter < IterMax and len(LNgbh): #BetterSolFound:
k = rd.randrange(len(LNgbh))
Sk = LNgbh.pop(k)
ek = autcom.Cost(Sb, cost_type = "flops")
if ek < eb:
Sb = Sk
eb = ek
LNgbh = Neighborhood(Sb, param_list)
iter += 1
#return best Energy, best Solution, and nb of iter
return eb,Sb,iter
|
MarcelKondo/Proj-intel-repo
|
mpi_HillClimbing.py
|
mpi_HillClimbing.py
|
py
| 2,327 |
python
|
en
|
code
| 1 |
github-code
|
50
|
20397466874
|
import os
import json
import datetime as dt
import logging
import pika
import psycopg2
from sqlalchemy import create_engine
from sqlalchemy import Column, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from database import DataBaseConnection
logging.basicConfig(filename=__name__,
filemode='a',
format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s \n\n',
datefmt='%H:%M:%S',
level=logging.DEBUG)
class MqItemConsumer():
def __init__(self, *args, **kwargs):
try:
self.amqp_url = kwargs['AMQP_URL']
self.routing_key = kwargs['ROUTING_KEY']
except KeyError as ke:
logging.exception(f'Exception in MqItemComsumer Initialization:\n {ke}')
self.db_connection = DataBaseConnection(**kwargs)
self.db_connection.connect()
mq_connection = None
mq_channel = None
def callback(self, channel, method, properties, body):
decoded_body = json.loads(body.decode('UTF-8'))
logging.info(f'inserted data:::::::::\n {decoded_body}')
self.db_connection.write_to_database(decoded_body)
def connect_consume(self):
try:
self.mq_connection = pika.BlockingConnection(
pika.ConnectionParameters(host=self.amqp_url))
except pika.exceptions.AMQPConnectionError as error:
logging.exception(f'error in connection::::: {error}')
if self.mq_connection.is_open:
self.mq_channel = self.mq_connection.channel()
self.mq_channel.queue_declare(queue=self.routing_key, durable=True)
self.mq_channel.basic_consume(queue=self.routing_key,
on_message_callback=self.callback,
auto_ack=True,)
try:
self.mq_channel.start_consuming()
except KeyboardInterrupt:
self.mq_channel.stop_consuming()
self.stop()
def stop(self):
self.mq_channel.close()
self.mq_connection.close()
self.db_connection.close()
|
WolfusFlow/Virtual_data_generator
|
orchestrator/MqItemConsumer.py
|
MqItemConsumer.py
|
py
| 2,275 |
python
|
en
|
code
| 0 |
github-code
|
50
|
23334016212
|
#!/usr/bin/python3
import xml.etree.ElementTree
import argparse
import sys
import os.path
import pprint
import logging
def process_cmdline():
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--fsroot', help='fsroot that was given to dar create')
parser.add_argument('files', metavar='FILE', nargs='*', help='files to read, if empty, stdin is used')
defaults = { 'fsroot': '__FSROOT__' }
parser.set_defaults( **defaults )
return parser.parse_args()
def read_xml( args ):
xtree = None
if len( args.files ) > 0:
xtree = xml.etree.ElementTree.parse( args.files[0] )
else:
xtree = xml.etree.ElementTree.parse( sys.stdin )
return xtree
def xml2filenames( path, elem ):
logging.debug( 'Enter: path={}, {}'.format( path, pprint.pformat( elem ) ) )
for child in elem:
logging.debug( 'Processing: {}'.format( pprint.pformat( child ) ) )
if child.tag in ( 'Catalog', 'Attributes' ):
continue
newpath = os.path.join( path, child.attrib[ 'name' ] )
if child.tag == 'Directory':
xml2filenames( newpath, child )
elif child.tag in ( 'File', 'Symlink', 'Socket', 'Pipe' ):
print( newpath )
else:
raise UserWarning( "Unknown Element tag '{}'".format( child.tag ) )
def run():
args = process_cmdline()
xtree = read_xml( args )
root = xtree.getroot()
xml2filenames( args.fsroot, root )
if __name__ == '__main__':
# logging.basicConfig( level=logging.DEBUG )
logging.basicConfig( level=logging.WARNING )
run()
|
ncsa/pdbkup
|
bin/dar_parse_xml.py
|
dar_parse_xml.py
|
py
| 1,598 |
python
|
en
|
code
| 0 |
github-code
|
50
|
38131098194
|
# this is to keep mypy happy
from .pyrosetta_import import pyrosetta
import warnings
from typing import List, Tuple
class _IgorBase:
def __init__(self):
warnings.warn('Virtual only method: THIS METHOD SHOULD NOT BE RUN. CALL `Igor`', category=SyntaxWarning)
self.pose = pyrosetta.Pose()
self.constraint_file = ''
self.ligand_residue: List[int] = []
self.key_residues: List[int] = []
self.atom_pair_constraint = 10
self.angle_constraint = 10
self.coordinate_constraint = 1
self.fa_intra_rep = 0.005 # default
def _vector2residues(self, vector: pyrosetta.Vector1) -> List[int]:
"""
This method is for machines. See ``residues_in_vector`` instead.
"""
return [i + 1 for i, v in enumerate(vector) if v == 1]
|
matteoferla/Fragmenstein
|
fragmenstein/igor/_igor_base.py
|
_igor_base.py
|
py
| 817 |
python
|
en
|
code
| 132 |
github-code
|
50
|
1745617578
|
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 30 17:36:17 2022
@author: noemie
"""
import xarray as xr
import numpy as np
#import pandas as pd
import os
import random
#import pyproj as proj
from sklearn.decomposition import PCA
import copy as cp
from sklearn.decomposition import KernelPCA
from sklearn.preprocessing import normalize
from sklearn.model_selection import KFold
from sklearn.metrics.pairwise import cosine_similarity, linear_kernel
from sklearn import cluster
import wpca
def remove_short(ds):
l = [len(ds.sel(traj=i).dropna(dim='obs').obs) for i in ds.traj]
keep = np.array([i for i in range(len(l)) if l[i] > 90]) # more than 3 months
ds2 = ds.sel(traj=xr.DataArray(keep)).rename_dims({'dim_0':'traj'})
return ds2
def get_traj_sub(year_init, year_final, delta_year, files, length_days):
dslist = []
for yr in range(year_init,year_final+1,delta_year):
print(yr)
filesS = files[np.where(np.array([int(files[i][-7:-3]) for i in range(len(files))]) == yr)[0][0]]
dsl = xr.open_dataset(filesS)
dsl = remove_short(dsl) # remove short trajectories -- to avoid memory errors
dsl = dsl.sel(obs = np.arange(length_days+366))
dslist.append(dsl)
ds = xr.concat(dslist, dim='traj')
return ds
def random_sample(N_particles, ds):
random.seed(4)
sample = random.sample(list(ds.traj.values), k=N_particles)
ds_samp = ds.sel(traj=xr.DataArray(sample)).rename_dims({'dim_0':'traj'}) # select the random particles
return ds_samp
def Part_0_make_subset(Dataset_path, init_year,final_year, delta_year, files, length_days, N_particles):
ds = get_traj_sub(init_year, final_year, delta_year, files, length_days)
ds_samp = random_sample(N_particles, ds)
ds_samp.to_netcdf(Dataset_path)
return None
def lons_in_interval(start_lon, lons):
#this should shift all longitudes so it lies in start_lon + 360.
if start_lon<0 :
print('start_lons should be in [0-360[')
return None
else:
lons_shifted = lons
while np.any(lons_shifted<0):
lons_shifted[lons_shifted<0] = lons_shifted[lons_shifted<0]+360
lons_2 = cp.copy(lons_shifted)
lons_2[lons_shifted>=start_lon] = lons_shifted[lons_shifted>=start_lon] - start_lon
lons_2[lons_shifted<start_lon] = lons_shifted[lons_shifted<start_lon] - start_lon +360
return cp.copy(lons_2)
def extract(path, length_days, start_lon) :
ds = xr.open_dataset(path)
ds = remove_short(ds)
lats = ds.lat[:,0:length_days].values
lons_i = ds.lon[:,0:length_days].values
lons = lons_in_interval(start_lon, lons_i)
temps = ds.temperature[:,0:length_days].values
sal = ds.salinity[:,0:length_days].values
date = ds.time[:,0].values
return lats, lons, temps, sal, date
def extract_all_per_year(yr, length_days, all_filles, start_lon) :
file = all_filles[np.where(np.array([int(all_filles[i][-7:-3]) for i in range(len(all_filles))]) == yr)[0][0]]
lats, lons, temps, sal, date = extract(file, length_days, start_lon)
return lats, lons, temps, sal, date
def translate(lat, lon):
return lat-np.repeat(lat[:,0][:, np.newaxis], lat.shape[1], axis=1), lon-np.repeat(lon[:,0][:, np.newaxis], lon.shape[1], axis=1)
def resample(lats, lons, length_days):
lats_resamp = np.zeros(lats.shape)
lons_resamp = np.zeros(lats.shape)
for i in range(lats.shape[0]):
latsl = lats[i,:]#lats_proj ?
latsl = latsl[~np.isnan(latsl)]
xp = np.linspace(0,len(latsl),length_days)
lats_resamp[i,:] = np.interp(xp, range(len(latsl)), latsl)
lonsl = lons[i,:] #lons_proj ?
lonsl = lonsl[~np.isnan(lonsl)]
lons_resamp[i,:] = np.interp(xp, range(len(lonsl)), lonsl)
return lats_resamp, lons_resamp
def weightPCA(lats, wtype):
if wtype == 'cos' :
w = np.cos( np.radians(lats) )
elif wtype == 'sqrt-cos' :
w = np.sqrt(abs(np.cos( np.radians(lats) )))
elif wtype == False:
w = np.ones(lats.shape)
return w
def PCA_Kernelized(Xlat_lon, n_components, copy, whiten, svd_solver, w, kernel, degreek):
# weight PCA
s = int(Xlat_lon.shape[1]/2)
Xlat_lon[:,s:] = Xlat_lon[:,s:]*w
pca = PCA(n_components=n_components, copy=copy, whiten=whiten, svd_solver = svd_solver)
X_reduced = pca.fit_transform(Xlat_lon)
N_features_PCA = pca.n_features_
N_samples_PCA = pca.n_samples_
N_components_PCA = pca.n_components_
Explained_variance_ratio_PCA = pca.explained_variance_ratio_
print('The number of initial features was: ', N_features_PCA)
print('The number of selected features is: ', N_components_PCA)
print('The number of samples is: ', N_samples_PCA)
print('The explained variance desired is:', n_components, '%, the obtained variance explained is: ', np.sum(Explained_variance_ratio_PCA), '%')
pca = KernelPCA(n_components=N_components_PCA, copy_X=copy, eigen_solver=svd_solver, kernel=kernel, degree=degreek, fit_inverse_transform=True)
X_reduced = pca.fit_transform(Xlat_lon)
return X_reduced, pca
def Part_1_pre_processing_one_sort(t, la, lo, resamp, length_days, wtype, norm):
if t == True :
lats_train_pp, lons_train_pp = translate(la, lo)
if resamp == True:
lats_train_pp, lons_train_pp = resample(lats_train_pp, lons_train_pp, length_days)
w = weightPCA(lats_train_pp, wtype)
# Reshape
X_lats_lons_train = np.concatenate((lats_train_pp, lons_train_pp), axis = 1) #concatenation of features to make it in the correct shape
if resamp == False:
X_lats_lons_train[np.isnan(X_lats_lons_train)] = 0
w[np.isnan(w)]=0
# Normalize
if norm == True:
X_lats_lons_train = normalize(X_lats_lons_train, copy=True)
return w, X_lats_lons_train
def Part_1_pre_processing(Dataset_path, length_days, perctest, perctrain, norm, t, resamp,wtype, start_lon):
lats_all,lons_all, temps_all, sals_all, date_all = extract(Dataset_path, length_days, start_lon)
lats_test, lons_test, lats_train, lons_train, lats_valid, lons_valid, temps_train, temps_test, temps_valid, sals_train, sals_test, sals_valid = split_sets(lats_all, lons_all,temps_all, sals_all, perctest, perctrain)
print('Pre_processing')
# PRE-PROCESSING
w_train, X_lats_lons_train = Part_1_pre_processing_one_sort(t, lats_train, lons_train, resamp, length_days, wtype, norm)
w_test, X_lats_lons_test = Part_1_pre_processing_one_sort(t, lats_test, lons_test, resamp, length_days, wtype, norm)
w_valid, X_lats_lons_valid = Part_1_pre_processing_one_sort(t, lats_valid, lons_valid, resamp, length_days, wtype, norm)
# weights, for train it's applied in PCA - kernel
s = int(X_lats_lons_valid.shape[1]/2)
X_lats_lons_valid[:,s:] = X_lats_lons_valid[:,s:]*w_valid
s = int(X_lats_lons_test.shape[1]/2)
X_lats_lons_test[:,s:] = X_lats_lons_test[:,s:]*w_test
return X_lats_lons_valid, X_lats_lons_test, X_lats_lons_train, w_train, w_valid, w_test
def Part_2_PCA(path_save_PCA, name_PCA_config, X_lats_lons_valid, X_lats_lons_test, X_lats_lons_train, w_train, n_components, copy, whiten, svd_solver, kernel, degreek):
X_reduced_train, pca= PCA_Kernelized(X_lats_lons_train, n_components, copy, whiten, svd_solver, w_train, kernel, degreek)
X_reduced_valid = pca.transform(X_lats_lons_valid)
X_reduced_test = pca.transform(X_lats_lons_test)
a = pca.alphas_
l = pca.lambdas_
dc = pca.dual_coef_
Save_PCA(path_save_PCA, name_PCA_config,X_reduced_train, X_reduced_valid, X_reduced_test, a, l, dc )
return None
def k_means_X_cv(n_splits, X_reduced, n_clusters, init, nmb_initialisations, max_iter, tol, algorithm, verbose, sample_weight):
kf = KFold(n_splits=n_splits, shuffle=True)
avg_silouhette = 0
i = 0
for train_index, val_index in kf.split(X_reduced):
print('fold nmb ', i)
i+=1
X_train = X_reduced[train_index,:]
k_means = cluster.KMeans(n_clusters=n_clusters, init=init, n_init = nmb_initialisations, max_iter = max_iter, tol = tol, algorithm = algorithm, verbose = verbose)
k_means.fit(X_train, sample_weight = sample_weight)
X_centers = k_means.cluster_centers_
a_temp = k_means.inertia_
#a_temp = silhouette_score(X_val, labs_val)
if a_temp>avg_silouhette:
X_centered_memory = X_centers
k_means_memory = k_means
avg_silouhette = a_temp
return X_centered_memory, k_means_memory, a_temp
def get_number_centroids(X_centers_train, X_reduced_train):
N_clusters = X_centers_train.shape[0]
Liste_number= np.zeros(N_clusters)
for n in range(N_clusters):
RV = X_centers_train[n]-X_reduced_train[:,:]
N_RV = np.linalg.norm(RV, axis = 1)
Liste_number[n] = np.argmin(N_RV)
return Liste_number
def split_sets(lats_all, lons_all, temps_all, sals_all, perctest, perctrain):
s0, s1 = lats_all.shape
data = np.concatenate((lats_all,lons_all), axis=1)
random.seed(4)
random.shuffle(data)
random.seed(4)
random.shuffle(temps_all)
random.seed(4)
random.shuffle(sals_all)
lats_test = data[:int(perctest*s0), 0:s1]
lons_test = data[:int(perctest*s0), s1:]
lats_train = data[int(perctest*s0):int(perctest*s0)+int(perctrain*s0), 0:s1]
lons_train = data[int(perctest*s0):int(perctest*s0)+int(perctrain*s0), s1:]
lats_valid = data[int(perctest*s0)+int(perctrain*s0):, 0:s1]
lons_valid = data[int(perctest*s0)+int(perctrain*s0):, s1:]
temps_test = temps_all[:int(perctest*s0),:]
sals_test = sals_all[:int(perctest*s0),:]
temps_train =temps_all[int(perctest*s0):int(perctest*s0)+int(perctrain*s0),:]
sals_train = sals_all[int(perctest*s0):int(perctest*s0)+int(perctrain*s0),:]
temps_valid = temps_all[int(perctest*s0)+int(perctrain*s0):,:]
sals_valid = sals_all[int(perctest*s0)+int(perctrain*s0):,:]
return lats_test, lons_test, lats_train, lons_train, lats_valid, lons_valid, temps_train, temps_test, temps_valid, sals_train, sals_test, sals_valid
def predict(X_reduced_val, X_centers):
X_reduced_val2 = np.repeat(X_reduced_val[:,:,np.newaxis], X_centers.shape[0], axis = 2)
X_centers2 = np.repeat(np.transpose(X_centers)[np.newaxis,:,:], X_reduced_val.shape[0], axis = 0)
return np.argmin(np.linalg.norm(X_reduced_val2-X_centers2, axis=1), axis = 1)
def Save_PCA(path_save_PCA,name_PCA_config, X_reduced_train, X_reduced_valid, X_reduced_test, a, l, dc ):
np.savetxt(path_save_PCA+'/X_train_kernelpca_%s.csv'%name_PCA_config, X_reduced_train, delimiter=',')
np.savetxt(path_save_PCA+'/X_valid_kernelpca_%s.csv'%name_PCA_config, X_reduced_valid, delimiter=',')
np.savetxt(path_save_PCA+'/X_test_kernelpca_%s.csv'%name_PCA_config, X_reduced_test, delimiter=',')
np.savetxt(path_save_PCA+'/alphas_kernelpca_%s.csv'%name_PCA_config, a, delimiter=',')
np.savetxt(path_save_PCA+'/lambdas_kernelpca_%s.csv'%name_PCA_config, l, delimiter=',')
np.savetxt(path_save_PCA+'/dualcoef_kernelpca_%s.csv'%name_PCA_config, dc, delimiter=',')
def Part_2_Load_PCA(name_kernel_pca, path_kernelpca) :
X_reduced_train = np.genfromtxt(path_kernelpca+'X_train_kernelpca_'+name_kernel_pca+'.csv', delimiter=',')
X_reduced_valid = np.genfromtxt(path_kernelpca+'X_valid_kernelpca_'+name_kernel_pca+'.csv', delimiter=',')
X_reduced_test = np.genfromtxt(path_kernelpca+'X_test_kernelpca_'+name_kernel_pca+'.csv', delimiter=',')
return X_reduced_train, X_reduced_valid, X_reduced_test
def Part_3_kmeans_clustering(name_PCA_config, path_save_PCA, n_split, n_clusters, init, nmb_initialisations, max_iter, tol, algorithm, verbose, sample_weight, ntest, path_save_clustering):
X_reduced_train, X_reduced_valid, X_reduced_test = Part_2_Load_PCA(name_PCA_config, path_save_PCA)
# K-MEANS CLUSTERING
print('Kmeans')
X_centers_train, k_means_model, a_temp = k_means_X_cv(n_split, X_reduced_train, n_clusters, init, nmb_initialisations, max_iter, tol, algorithm, verbose, sample_weight)
labels_valid = predict(X_reduced_valid, X_centers_train)
labels_test = predict(X_reduced_test, X_centers_train)
print('Get Centroids')
centroids = get_number_centroids(X_centers_train, X_reduced_train)
Part_3_save_clustering(ntest, path_save_clustering, labels_valid, labels_test, X_reduced_valid, X_reduced_test, centroids, a_temp,X_centers_train)
return None
def Part_3_save_clustering(ntest, path_save_clustering, labels_valid, labels_test, X_reduced_valid, X_reduced_test, centroids, a_temp,X_centers_train):
os.makedirs(path_save_clustering)
np.save(path_save_clustering+'centroids'+ntest, centroids)
np.save(path_save_clustering+'X_centers_train'+ntest, X_centers_train)
np.save(path_save_clustering+'labels_test'+ntest, labels_test)
np.save(path_save_clustering+'X_reduced_test'+ntest, X_reduced_test)
np.save(path_save_clustering+'labels_valid'+ntest, labels_valid)
np.save(path_save_clustering+'X_reduced_valid'+ntest, X_reduced_valid)
return None
def Part_4_prediction(X_lats_lons, X_lats_lons_train, Alphas,lambdas, X_centers_train, kernel) :
if kernel == 'cosine':
Kernel_matrix = cosine_similarity(X_lats_lons, X_lats_lons_train)
elif kernel == 'linear':
Kernel_matrix = linear_kernel(X_lats_lons, X_lats_lons_train)
else:
print('Houston, issue here ! ')
Alphas_scaled = Alphas/np.sqrt(lambdas)
X_reduced = np.matmul(Kernel_matrix, Alphas_scaled)
labels = predict(X_reduced, X_centers_train)
return labels, X_reduced
def run_script_prediction(name, norm, t, resamp, length_days, wtype, lats, lons, lats_train, lons_train, path_save, name_kernel_pca, X_centers_train, path_kernelpca, kernel) :
w, X_lats_lons = Part_1_pre_processing_one_sort(t, lats, lons, resamp, length_days, wtype, norm)
w_train, X_lats_lons_train = Part_1_pre_processing_one_sort(t, lats_train, lons_train, resamp, length_days, wtype, norm)
s = int(X_lats_lons.shape[1]/2)
X_lats_lons[:,s:] = X_lats_lons[:,s:]*w
s = int(X_lats_lons_train.shape[1]/2)
X_lats_lons_train[:,s:] = X_lats_lons_train[:,s:]*w_train
Alphas = np.genfromtxt(path_kernelpca+'alphas_kernelpca_'+name_kernel_pca+'.csv', delimiter=',')
Lambdas = np.genfromtxt(path_kernelpca+'lambda_kernelpca_'+name_kernel_pca+'.csv', delimiter=',')
return Part_4_prediction(X_lats_lons, X_lats_lons_train, Alphas, Lambdas, X_centers_train, kernel)
def apply_to_all_data(path_save_clustering, ntest, init_year,final_year, length_days, files, start_lon, norm, t, resamp,wtype, name_PCA_config, path_save_PCA, Dataset_path, perctest, perctrain, kernel):
centroids, labels_test, labels_valid, lats_test, lats_valid, lons_test, lons_valid, lons_train, lats_train, \
X_reduced_test, X_Reduced_valid, temps_test, temps_train, temps_valid, sals_test, sals_train, sals_valid, X_centers_train = load_data_test_train_valid(path_save_clustering, ntest, Dataset_path, length_days, perctest, perctrain, start_lon)
for yr in range(init_year,final_year):
print('Year', yr)
lats_all,lons_all, temps_all, sals_all, date_all = extract_all_per_year(yr, length_days, files, start_lon)
labels_all = []
for sep in range(0,lats_all.shape[0],500) :
print(sep,'/',lats_all.shape[0])
lats_all_l = lats_all[sep:sep+500,:] ; lons_all_l = lons_all[sep:sep+500,:]
labels, X_reduced = run_script_prediction(ntest, norm, t, resamp, length_days, wtype, lats_all_l, lons_all_l, lats_train, lons_train, path_save_clustering,
name_PCA_config, X_centers_train, path_save_PCA, kernel)
labels_all.extend(labels)
np.save(path_save_clustering+'ClassifiedData/'+'labels_data_%i'%yr, labels_all)
return None
def load_data_test_train_valid(path_save_clustering, ntest, Dataset_path, length_days, perctest, perctrain, start_lon):
lats_all,lons_all, temps_all, sals_all, date_all = extract(Dataset_path, length_days, start_lon)
lats_test, lons_test, lats_train, lons_train, lats_valid, lons_valid, temps_train, temps_test, temps_valid, sals_train, sals_test, sals_valid = split_sets(lats_all, lons_all,temps_all, sals_all, perctest, perctrain)
CENTROID = np.load(path_save_clustering+'centroids'+ntest+'.npy', allow_pickle = True)
LABELS_TEST = np.load(path_save_clustering+'labels_test'+ntest+'.npy', allow_pickle = True)
X_REDUCED_TEST = np.load(path_save_clustering+'X_reduced_test'+ntest+'.npy', allow_pickle = True)
LABELS_VALID = np.load(path_save_clustering+'labels_valid'+ntest+'.npy', allow_pickle = True)
X_REDUCED_VALID = np.load(path_save_clustering+'X_reduced_valid'+ntest+'.npy', allow_pickle = True)
X_centers_train = np.load(path_save_clustering+'X_centers_train'+ntest+'.npy', allow_pickle = True)
return CENTROID, LABELS_TEST, LABELS_VALID, lats_test, lats_valid, lons_test, lons_valid, lons_train, lats_train, \
X_REDUCED_TEST, X_REDUCED_VALID, temps_test, temps_train, temps_valid, sals_test, sals_train, sals_valid, X_centers_train
def load_data_year(path_save_clustering, yr, length_days, files, start_lon):
labels = np.load(path_save_clustering+'ClassifiedData/'+'labels_data_%i'%yr +'.npy', allow_pickle = True)
lats_all,lons_all, temps_all, sals_all, date_all = extract_all_per_year(yr, length_days, files, start_lon)
return lats_all, lons_all, temps_all, sals_all, date_all, labels
def get_labels_time_series(path_save_clustering, init_year,final_year, n_clusters, length_days, files, start_lon):
Dates_all = []; Perc_labels_all = [];
for yr in range(init_year,final_year):
print('Year', yr)
lats_all, lons_all, temps_all, sals_all, time_data, labels_data = load_data_year(path_save_clustering, yr, length_days, files, start_lon)
Date_data = np.unique(time_data)
Dates_all.extend(Date_data)
Perc_labels = np.zeros((len(Date_data), n_clusters))
for i in range(len(Date_data)):
d0 = np.where(Date_data[i] ==time_data)[0]
for di in d0:
Perc_labels[i,labels_data[di]] +=1
Perc_labels[i,:] =100*Perc_labels[i,:]/len(d0)
Perc_labels_all.extend(Perc_labels)
Perc_labels_all = np.array(Perc_labels_all)
return Dates_all, Perc_labels_all
|
noemieplanat/Clustering_Lagrangian_particles
|
Scripts/All_functions_ML.py
|
All_functions_ML.py
|
py
| 18,619 |
python
|
en
|
code
| 0 |
github-code
|
50
|
25193341516
|
# Creating a dictionary of 20 countries
Countries = dict({'1': 'Argentina',
'2': 'Australia',
'3': 'Brazil',
'4': 'Colombia',
'5': 'Egypt',
'6': 'France',
'7': 'Germany',
'8': 'Greece',
'9': 'Hong Kong',
'10': 'Kiribati',
'11': 'Lesotho',
'12': 'Madagascar',
'13': 'Mexico',
'14': 'Nepal',
'15': 'New Zealand',
'16': 'Nigeria',
'17': 'Philippines',
'18': 'Portugal',
'19': 'United Arab Emirates',
'20': 'United Kingdom'})
# To manage the different possible output formats of the file
# serialization and deserialization options are defined
serialization_option = "XML"
serialization_option = "JSON"
serialization_option = "BINARY"
deserialization_option = "XML"
deserialization_option = "JSON"
deserialization_option = "BINARY"
# Server and port addresses are indicated
server_address = 'localhost'
port_number = 9999
# To generate the encryption token for encrypting and decrypting the operation
from cryptography.fernet import Fernet
key = Fernet.generate_key()
|
CT673/End-of-Module-Assignment
|
Config.py
|
Config.py
|
py
| 1,313 |
python
|
en
|
code
| 0 |
github-code
|
50
|
3120828974
|
from jupyter_client.manager import start_new_kernel
import thebe.core.file as File
import thebe.core.constants as Constant
import thebe.core.output as output
import thebe.core.logger as Logger
import thebe.core.database as Database
import thebe.core.html as Html
from pygments import highlight
from pygments.lexers import BashLexer, PythonLexer, MarkdownLexer
from pygments.formatters import HtmlFormatter
import pypandoc, time, sys, datetime, glob, re, sys, time, os, copy, logging, threading, queue, json
class jupyter_client_wrapper:
def __init__(self, fileName):
# Setting up self.loggers
self.lUpdate = Logger.getLogger('update.log', 'update')
self.logger = Logger.getLogger('main.log', 'main')
self.mess_logger = Logger.getLogger('mess.log', 'mess')
self.status_logger = Logger.getLogger('status.log', 'status')
self.execute_logger = Logger.getLogger('execute.log', 'execute')
self.kernel_manager, self.jupyter_client = start_new_kernel()
# Determine what kind of file working with
self.fileLocation, is_ipynb = File.setup(fileName)
# Initialize some variables
# self.isActive = False
self.executionThread = None
self.Cells = []
self.executions = 0
# Initialize local and global scope for old
# execution engine
self.LocalScope = {}
self.GlobalScope = {}
'''
-------------------------------
Setter functions
-------------------------------
'''
def setSocket(self, socketio):
self.socketio = socketio
'''
-------------------------------
Execution pre-preprocessing
-------------------------------
'''
def execute(self, update = 'changed'):
#self.Cells = Database.getCells(self.fileLocation)
if self._isActive():
self.socketio.emit('flash')
else:
if update == 'changed':
self._execute_changed()
elif update == 'all':
self._execute_all()
elif update == 'connected':
self._execute_connected()
elif type(update) == list:
self._execute_cell(update)
else:
pass
time.sleep(.5)
'''
-------------------------------
Execution pre-preprocessing - Helpers
-------------------------------
'''
def _execute_cell(self, index):
# self.isActive = True
self._execute(update = index)
# self.isActive = False
def _execute_changed(self):
if self._isModified():
self.status_logger.info('Execute changed...')
# self.isActive = True
self._execute(update = 'changed')
# self.isActive = False
self.status_logger.info('Finished...')
def _execute_all(self):
self.status_logger.info('Execute all...')
# self.isActive = True
self.Cells = []
self._execute(update = 'all')
# self.isActive = False
self.status_logger.info('Finished...')
def _execute_connected(self):
if not self.Cells:
self.status_logger.info('Execute connected...')
# self.isActive = True
self._execute(update = 'connected')
# self.isActive = False
time.sleep(2)
else:
self.socketio.emit('show all', self._convert())
def _restart_kernel(self):
self.status_logger.info('Restarting kernel...')
kernel_manager.restart_kernel()
while True:
try:
io_msg_content = self.jupyter_client.get_iopub_msg(timeout=3)['content']
time.sleep(.01)
except queue.Empty:
break
def _isModified(self, x=.3):
'''
Return true if the target file has been modified in the past x amount of time
'''
lastModified=os.path.getmtime(self.fileLocation)
timeSinceModified=int(time.time()-lastModified)
if timeSinceModified<=x:
return True
else:
return False
'''
-------------------------------
Execution - Main - Helpers
-------------------------------
'''
def _execute(self, update = 'changed'):
'''
Execute cells based on 'update' value
'''
self.status_logger.info('Updating...')
self._update(self._getFileContent(), update)
self.status_logger.info('Showing...')
self.socketio.emit('show all', self._convert())
'''
'''
self.status_logger.info('Executing...')
self.executionThread = threading.Thread(target = self._executeThread)
self.executionThread.daemon = True
self.executionThread.start()
def _update(self, fileContent, update):
'''
Update the 'Cells' variable with new data from
the Thebe file
'''
# 'cells' is for the new cells
cells = []
# Ignore code that comes before the first delimiter
ignoreFirst = self._ignoreFirst(fileContent)
self.lUpdate.info('---------------')
self.lUpdate.info('ignoreFirst: %s'%(ignoreFirst,))
# True cell count, used because sourceCount
# can be unreliable
cellCount = 0
for sourceCount, source in enumerate(fileContent.split(Constant.CellDelimiter)):
self.lUpdate.info('---------------')
self.lUpdate.info('Cell count: %s'%(cellCount,))
# Ignore the first source if a cell delimiter
# does not preceed it
if ignoreFirst:
ignoreFirst = False
continue
#Split source by line
source = source.splitlines(True)
self.lUpdate.info('Source length: %s'%(len(source),))
if self._validSource(source):
# Get copy of cell initially populated
cell = copy.deepcopy(Constant.Cell)
cell = self._setMarkdown(source, cell)
self.lUpdate.info('Changed: %s'%(cell['changed'],))
# Handle front end buttons
if update == 'all':
cell = self._setChanged(source, cell, force_change = True)
elif type(update) == list and cellCount in update:
cell = self._setChanged(source, cell, force_change = True)
else:
cell = self._setChanged(source, cell)
self.lUpdate.info('Changed: %s'%(cell['changed'],))
# Set execution counter if it exists previously
try:
cell['execution_count'] = self.Cells[cellCount]['execution_count']
except IndexError:
pass
cells.append(cell)
cellCount += 1
self.Cells = cells
self.status_logger.info('Changed cells: %s'%([x['changed'] for x in self.Cells],))
def _executeThread(self):
'''
Run the newly changed cells and return their output.
'''
self.status_logger.info('Inside execute thread...')
self.Cells = self._runNewCells()
self.executions += 1
'''
Update the database with the fresh code.
And outputs.
'''
# Database.update(self.fileLocation, self.Cells, GlobalScope, LocalScope, executions)
self._updateIpynb()
self.status_logger.info('Execution thread finished...')
'''
-------------------------------
Actual execution
-------------------------------
'''
def _runNewCells(self):
'''
Run each changed cell, returning the output.
'''
# Append cells containing updated output to this
newCells = []
# Toggle to true when the users code produces an
# error so code execution can stop
kill = False
for cellCount, cell in enumerate(self.Cells):
# Run changed code if it is not markdown
# and no prior cell has triggered an error
if cell['changed']:
self.socketio.emit('message', 'Running cell #%s...'%(cellCount))
self.socketio.emit('loading', cellCount)
cell['changed'] = False
if cell['cell_type'] != 'markdown' and not kill:
self.logger.info('\n------------------------\nRunning cell #%s\nIn directory: %s\nWith code:\n%s\n-------------------------------'%(cellCount, os.getcwd(), cell['source']))
# Execute the code from the cell, stream
# outputs using socketio, and return output
outputs = self._jExecute(cell['source'])
# Prevent subsequent execution of code
# if in error was found
if self._hasError(outputs):
kill = True
# Add output data to cell
cell['outputs'] = outputs
# How does ipython do this?
cell['execution_count'] = cell['execution_count'] + 1
# Append run cell the new cell list
newCells.append(cell)
# Stop the front end loading
self.socketio.emit('stop loading')
self.status_logger.info('End of runAllCells...')
return newCells
def _jExecute(self, code):
'''
'''
self.status_logger.info('Inside jExecute thread...')
code = ''.join(code)
# Execute the code
msg_id = self.jupyter_client.execute(code)
# Get the execution status
# When the execution state is "idle" it is complete
t = True
try:
io_msg_content = self.jupyter_client.get_iopub_msg(timeout=1)['content']
except queue.Empty:
t = False
self.status_logger.info('After first message in jExecute...')
# Initialize the temp variable
temp = {}
# Initialize outputs
outputs = []
# Continue polling for execution to complete
# which is indicated by having an execution state of "idle"
while t:
# Save the last message content. This will hold the solution.
# The next one has the idle execution state indicating the execution
# is complete, but not the stdout output
temp = io_msg_content
self.execute_logger.info(temp)
# Check the message for various possibilities
if 'data' in temp: # Indicates completed operation
if 'image/png' in temp['data']:
plotData = temp['data']['image/png']
output = self._getPlotOutput(plotData)
outputs.append(output)
self.socketio.emit('output', output)
if 'name' in temp and temp['name'] == "stdout": # indicates output
# Create output for server use
output = self._getStdOut(temp['text'])
outputs.append(output)
# Send HTML output for immediate front end use
htmlOutput = copy.deepcopy(output)
htmlOutput['data']['text/plain'] = [Html.convertText(text, ttype = 'bash') for text in htmlOutput['data']['text/plain']]
self.socketio.emit('output', htmlOutput)
if 'evalue' in temp: # Indicates error
# Create output for server use
output = self._getErr(temp['evalue'])
outputs.append(output)
# Send HTML output for immediate front end use
htmlOutput = copy.deepcopy(output)
htmlOutput['evalue'] = [Html.convertText(text, ttype = 'bash') for text in htmlOutput['evalue']]
self.socketio.emit('output', htmlOutput)
# If there is an error than it is pointless
# to keep on running code
break
# Poll the message
try:
io_msg_content = self.jupyter_client.get_iopub_msg(timeout=1)['content']
time.sleep(.1)
if 'execution_state' in io_msg_content and io_msg_content['execution_state'] == 'idle':
break
except queue.Empty:
break
self.status_logger.info('End of jExecute thread...')
return outputs
'''
-------------------------------
Execution helper functions
-------------------------------
'''
def _hasError(self, outputs):
'''
If an error cell exists in outputs
return true
'''
for output in outputs:
if 'evalue' in output:
return True
return False
def _fillPlot(cell, plot):
'''
If an image exists in the plot variable, create and return a plot cell.
'''
if plot:
output = Constant.getDisplayOutput()
output['data']['image/png'] = plot
cell['outputs'].append(output)
return cell
def _getPlotOutput(self, plot):
'''
'''
output = Constant.getDisplayOutput()
output['data']['image/png'] = plot
return output
def _getStdOut(self, stdOut):
output = Constant.getExecuteOutput()
output['data']['text/plain'] = stdOut.splitlines(True)
return output
def _getErr(self, err):
output = Constant.getErrorOutput()
output['evalue'] = err.splitlines(True)
return output
'''
-------------------------------
Preprocessing helper functions
-------------------------------
'''
def _getFileContent(self):
fileContent = ''
with open(self.fileLocation, 'r') as file_content:
fileContent = file_content.read()
return fileContent
def _update_all(self):
# 'cells' is for the new cells
cells = []
def _ignoreFirst(self, fileContent):
# Ignore code that comes before the first delimiter
if not fileContent.startswith(Constant.CellDelimiter):
self.logger.info('Ignoring first...')
return True
else:
return False
def _getSourceList(self):
'''
Form the hashes from the cell list into a list
'''
return [cell['source'] for cell in self.Cells]
def _toThebe(self, ipynb):
'''
Take in a ipynb dictionary, and returns a string in thebe format.
(Cell sources to delimited by our Constants.CellDelimiter)
'''
output = ''
for cell in ipynb['cells']:
if cell['cell_type'] == 'markdown':
output = ''. join(\
(output, \
(Constant.CellDelimiter + 'm\n' + \
''.join(cell['source']))\
))
else:
output = ''. join(\
(output, \
(Constant.CellDelimiter + '\n' + \
''.join(cell['source']))\
))
return output
def _setChanged(self, source, cell, force_change = False):
'''
Detect if a cell has been changed
'''
if force_change:
cell['changed'] = True
cell['last_changed'] = time.strftime("%x %X", time.gmtime())
cell['outputs'] = []
else:
try:
x = self._getSourceList().index(source)
cell = self.Cells[x]
except ValueError:
cell['changed'] = True
cell['last_changed'] = time.strftime("%x %X", time.gmtime())
return cell
def _setMarkdown(self, source, cell):
'''
Determine if a cell is marked down
'''
# Detect if cell is Markdown
if source[0] == 'm\n':
# Set cell as markdown
cell['cell_type'] = 'markdown'
# Remove the new line after the delimiter
source.pop(0)
#Set sourceCode
cell['source'] = source
return cell
def _validSource(self, source):
'''
Return false if source list is all Just new lines
'''
for s in source:
if s != '\n':
return True
return False
def _updateIpynb(self):
'''
Write the new changes to the ipynb file.
'''
self.status_logger.info('Updating .ipynb...')
cCells = copy.deepcopy(self.Cells)
# Remove extra attributes created by thebe.
self._sanitize(cCells)
# Save cells into a ".ipynb" file
with open(File.getPrefix(self.fileLocation)+'.ipynb', 'w') as f:
# Get the jupyter cell list wrapper
ipynb = Constant.getIpynb()
# Wrap cells
ipynb['cells'] = cCells
# Overwrite old ipynb file
json.dump(ipynb, f, indent=True)
def _sanitize(self, Cells):
'''
Remove the extra attributes that thebe uses,
that Jupyter does not
'''
for i, cell in enumerate(Cells):
del Cells[i]['execution_count']
del Cells[i]['changed']
'''
-------------------------------
HTML conversion
-------------------------------
'''
def _convert(self):
'''
Return a deep copy of cellList with code replaced with html-ized code
'''
# Deep copy cells so the original is not converted to HTML
tempCells = copy.deepcopy(self.Cells)
for cell in tempCells:
# Preprocessing a code cell
if cell['cell_type'] == 'code':
# Highlight the Python syntax
cell['source'] = \
[highlight(source, PythonLexer(), HtmlFormatter()) for source in cell['source']]
# Highlight standard output and error
for output in cell['outputs']:
# Highlight the standard output
if output['output_type'] == 'execute_result':
output['data']['text/plain'] = \
[highlight(text, BashLexer(), HtmlFormatter()) \
for text in output['data']['text/plain']]
# Highlight the error
if output['output_type'] == 'error':
output['traceback'] = \
[highlight(text, BashLexer(), HtmlFormatter()) \
for text in output['traceback']]
# Preprocessing a markdown cell
if cell['cell_type'] == 'markdown':
# Flatten the list so multi line latex delimiters
# are not separated by HTML elements as this would
# break MathJax.
cell['source'] = ''.join(cell['source'])
# Remove any html that could interupt
# markdown conversion
clean = re.compile('<.*>.*</.*>')
cell['source'] = re.sub(clean, '', cell['source'])
# Convert the markdown
# These arguments are used to let pypandoc
# know to ignore latex
pdoc_args = ['--standalone', '--mathjax']
# Convert from markdown to HTML
cell['source'] = \
pypandoc.convert_text(cell['source'], \
'html', format = 'md',\
extra_args = pdoc_args)
return tempCells
def _isActive(self):
if self.executionThread:
if self.executionThread.is_alive():
return True
else:
return False
else:
return False
|
hotsoupisgood/Thebe
|
thebe/core/jupyter_wrapper.py
|
jupyter_wrapper.py
|
py
| 19,967 |
python
|
en
|
code
| 0 |
github-code
|
50
|
27157479985
|
import pandas as pd
import numpy as np
import logging
import math
logging.basicConfig(format="%(asctime)s %(name)s:%(levelname)s:%(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.INFO)
def varStats(dataframe,round=2):
format_str = "{" + "0:,." + str(round) + "f}"
data=dataframe
list_role = []
list_dtype = []
list_level = []
list_use = []
list_sum = []
list_max = []
list_min = []
list_total_count = []
list_null = []
list_null_rate = []
list_unique = []
list_unique_rate = []
list_mean = []
list_median=[]
list_q1=[]
list_q3=[]
list_var = []
list_std=[]
list_skew = []
list_kurt=[]
list_notnull_count = []
list_mode = []
list_range = []
list_qrange = []
list_cov = []
list_sum_of_squares=[]
list_se = []
for i in data.columns:
if i.lower() in ['y', 'target']:
role = "目标"
elif i.lower() in ['id','userid','user_id','order_no','order_id']:
role = "ID"
else:
role = "输入"
list_dtype.append(str(data[i].dtypes))
list_role.append(role)
if data[i].nunique()==2:
list_level.append("二值型")
elif data[i].nunique()>2 and str(data[i].dtypes)=="object":
list_level.append("名义型")
elif data[i].nunique()==1:
list_level.append("单一值")
else:
list_level.append("区间型")
list_use.append("是")
list_total_count.append(len(data))
list_notnull_count.append(data[i].notnull().sum())
list_null.append(data[i].isnull().sum())
list_null_rate.append('{:,.2%}'.format(data[i].isnull().sum() / len(data)))
list_unique.append(data[i].nunique())
list_unique_rate.append('{:,.2%}'.format(data[i].nunique() / len(data)))
list_mode.append(data[i].mode()[0])
#数值变量计算
if str(data[i].dtypes)=="int64" or str(data[i].dtypes)=="float64":
list_min.append(data[i].min())
list_q1.append(format_str.format(data[i].quantile(0.25)))
list_q3.append(format_str.format(data[i].quantile(0.75)))
list_skew.append(format_str.format(data[i].skew()))
list_kurt.append(format_str.format(data[i].kurt()))
list_mean.append(format_str.format(data[i].mean()))
list_var.append(format_str.format(data[i].var()))
list_std.append(format_str.format(data[i].std()))
list_median.append(format_str.format(data[i].median()))
list_max.append(data[i].max())
list_range.append(format_str.format(data[i].max()-data[i].min()))
list_qrange.append(format_str.format(data[i].quantile(0.75) - data[i].quantile(0.25)))
list_cov.append(format_str.format(data[i].std()/data[i].mean()))
list_sum.append(format_str.format(data[i].sum()))
list_sum_of_squares.append(format_str.format(sum([num*num for num in data[i]])))
list_se.append(format_str.format(data[i].var()/math.sqrt(data[i].notnull().sum())))
else:
list_min.append("")
list_q1.append("")
list_q3.append("")
list_skew.append("")
list_kurt.append("")
list_mean.append("")
list_var.append("")
list_std.append("")
list_median.append("")
list_max.append("")
list_range.append("")
list_qrange.append("")
list_cov.append("")
list_sum.append("")
list_sum_of_squares.append("")
list_se.append("")
df = pd.DataFrame(
{"变量名": data.columns, '数据类型': list_dtype, '角色': list_role, '水平': list_level, '是否使用': list_use,'总体计数': list_total_count,'非缺失值计数': list_notnull_count,'均值':list_mean,'均值标准误':list_se,'方差': list_var,'标准差':list_std,'变异系数':list_cov,'总和':list_sum,'平方和':list_sum_of_squares,'众数':list_mode,'最小值': list_min,'Q1': list_q1,'中位数': list_median,'Q3':list_q3,'最大值': list_max,'极差': list_range,'四分位间距': list_qrange,'峰度':list_kurt,'偏度':list_skew,'缺失值': list_null, '缺失值占比': list_null_rate,'唯一值': list_unique, '唯一值占比': list_unique_rate})
df.to_csv("var_stats.csv")
logging.info('描述统计处理完成')
return df
|
leeoo/pyminer
|
pyminer2/extensions/packages/data_miner/data_miner/features/statistics/basic_stats.py
|
basic_stats.py
|
py
| 4,475 |
python
|
en
|
code
| null |
github-code
|
50
|
17009503445
|
# -*- coding: utf-8 -*-
import os
import argparse
from datetime import datetime, timedelta
from dataclasses import asdict
from typing import List
import uuid
import const
from logging import Logger
import logger
from mq import MQ, MQMsgData
import ysapi
def _send_msg(send_data: MQMsgData,
queue_name: str,
routing_key: str,
log: Logger):
try:
with MQ(**const.MQ_CONNECT,
queue=queue_name,
routing_key=routing_key) as queue:
msg = asdict(send_data)
queue.send_message(message=msg)
log.info('Send message queue=%(queue)s, data=%(data)s', {'queue': queue_name, 'data': msg})
except Exception:
log.exception('Failed to send mq message error')
raise
def _get_order_item_id_list(task_no: int, log: Logger) -> List[str]:
log.info('Start get order list')
end_time = datetime.now()
start_time = end_time - timedelta(days=const.ORDER_LIST_GET_LAST_DAYS)
if const.IS_PRODUCTION:
profile_dirname = f'yshop_producer_{task_no}'
else:
profile_dirname = f'yshop_producer_test_{task_no}'
profile_dir = os.path.join(const.CHROME_PROFILE_DIR, profile_dirname)
if const.IS_PRODUCTION:
auth_file = os.path.join(const.TMP_DIR, f'yshop_auth_producer_{task_no}.json')
else:
auth_file = os.path.join(const.TMP_DIR, f'yshop_auth_producer_test_{task_no}.json')
cert = (const.YSHOP_CERT_CRT_FILE, const.YSHOP_CERT_PKEY_FILE)
with ysapi.YahooAPI(profile_dir=profile_dir,
log=log,
application_id=const.YJDN_APP_ID_PRODUCER,
secret=const.YJDN_SECRET_PRODUCER,
auth_file=auth_file,
business_id=const.YSHOP_BUSINESS_ID,
business_password=const.YSHOP_BUSINESS_ID,
yahoo_id=const.YSHOP_YAHOO_ID,
yahoo_password=const.YSHOP_YAHOO_PASSWORD,
cert=cert) as api:
log.info('Request to get order list')
order_list = api.shopping.order.list.get(order_time_from=start_time, order_time_to=end_time)
item_ids = []
for order_list_data in order_list:
order_id = order_list_data.order_id
log.info('Request to get order info order_id=%s', order_id)
order_info_list = api.shopping.order.info.get(order_id=order_id)
for order_info in order_info_list:
order_status = order_info.order_status
# 受注ステータス(在庫連動対象)
# 1 : 予約中
# 2 : 処理中
# 3 : 保留
# 5 : 完了
if order_status not in [1, 2, 3, 5]:
# 受注ステータス(在庫連動対象外)
# 4 : キャンセル
continue
order_items = order_info.items
if order_items:
for order_item in order_items:
item_id = order_item.item_id
item_ids.append(item_id)
log.info('Get order list: order_list=%s', item_ids)
return item_ids
def _producer(task_no: int, log: Logger):
item_ids = _get_order_item_id_list(task_no=task_no, log=log)
if not item_ids:
return
send_data = MQMsgData(id=str(uuid.uuid4()),
item_ids=item_ids,
msg_send_time=datetime.now().isoformat())
log.info('Send MQ')
# 楽天
_send_msg(send_data=send_data,
queue_name=const.MQ_RAKUTEN_QUEUE,
routing_key=const.MQ_RAKUTEN_ROUTING_KEY,
log=log)
# AuPayマーケット
_send_msg(send_data=send_data,
queue_name=const.MQ_AU_QUEUE,
routing_key=const.MQ_AU_ROUTING_KEY,
log=log)
def main():
parser = argparse.ArgumentParser(description='stockout_yshop_producer')
parser.add_argument('--task_no',
required=True,
type=int,
help='input process No type integer')
arg_parser = parser.parse_args()
log = logger.get_logger(task_name='stockout-yshop-producer',
sub_name='main',
name_datetime=datetime.now(),
task_no=arg_parser.task_no,
**const.LOG_SETTING)
log.info('Start task')
log.info('Input args task_no=%s', arg_parser.task_no)
_producer(task_no=arg_parser.task_no, log=log)
log.info('End task')
if __name__ == '__main__':
main()
|
pro-top-star/python-stock-out
|
app/stockout_yshop_producer.py
|
stockout_yshop_producer.py
|
py
| 4,722 |
python
|
en
|
code
| 2 |
github-code
|
50
|
25290415553
|
from matplotlib import pyplot as plt
from matplotlib import cm
def plot_by_num_and_group(sequences_in, numcol, groupcols):
seq = sequences_in.copy()
g = seq.groupby(groupcols)
n_col = 4
n_row = len(g) // n_col + len(g) % n_col
f, axes = plt.subplots(n_row, n_col, figsize=[20, 15], sharex=True, sharey=True,
constrained_layout=True)
axes = axes.ravel()
for (n, df), (i, ax) in zip(g, enumerate(axes)):
s = ax.scatter(df[numcol], df['logit_best_xg'],
c=df['n_pass'],
cmap='viridis')
v = ax.vlines(df[numcol], df['logit_y_rep_low'],
df['logit_y_rep_high'], color='grey', zorder=0)
ax.set_title(n, y=0.77)
if i % n_col == 0:
ax.set_ylabel('Best xg (logit scale)')
if i >= n_row * n_col - n_col:
ax.set_xlabel(numcol)
f.colorbar(s, ax=axes, label='number of passes in sequence', shrink=0.35,
location='top')
f.suptitle(f'Max xg in long sequences\nfor different {numcol}s and {groupcols}s',
fontsize=20, x=0.01, y=0.99, ha='left', fontweight='bold')
f.legend([v], ['Model predictions: 10%-90% credible interval'], frameon=False,
loc='upper right', prop={'size': 14})
return f, axes
def plot_player_effect(sequences_in, numcol, player, team, ax):
team_seqs = sequences_in.query(f"team == '{team}'").copy()
player_seqs = team_seqs.loc[lambda df: df['players'].str.contains(player)]
cmap = cm.get_cmap('viridis')
ax.vlines(team_seqs[numcol], team_seqs['logit_y_rep_low'],
team_seqs['logit_y_rep_high'], color='grey', zorder=0,
label="Model predictions: 10%-90% credible interval")
ax.scatter(team_seqs[numcol], team_seqs['logit_best_xg'],
color=cmap(0.5), label=f'Sequences without {player}')
ax.scatter(player_seqs[numcol], player_seqs['logit_best_xg'], color='red',
label=f'Sequences with {player}')
ax.legend(frameon=False, loc='upper left')
ax.set_title(f'{team} with and without {player}')
ax.set_xlabel(numcol)
ax.set_ylabel("Best xg (logit scale)")
return ax
|
teddygroves/football_on_paper
|
plotting.py
|
plotting.py
|
py
| 2,214 |
python
|
en
|
code
| 0 |
github-code
|
50
|
8231560009
|
# Environment to play
#environment = 'LunarLanderContinuous-v2'
environment = 'Pendulum-v0'
#environment = 'CartPole-v1'
# environment = 'Acrobot-v1'
# environment = 'MountainCar-v0'
# Continuous Action if true
#continuous_action = False
continuous_action = True
# Number of Episodes
max_episodes = 100000
#Summaries log directory (/tmp/tf-rl/log)
log_dir = '/tmp/tf-rl/log'
# Model path for save (/tmp/tf-rl/model/)')
save_model_dir = '/tmp/tf-rl/model/'
#Interval to save model (500)
interval_to_save_model = 500
# Model path for restore
restore_model_path = None
#restore_model_path = '/tmp/tf-rl/model/model-500'
# Training mode
train = True
# Render mode
render = True
# Record mode
record = False
# Record path
record_path = 'record/'
|
KatayamaLab/tf-rl
|
config.py
|
config.py
|
py
| 754 |
python
|
en
|
code
| 0 |
github-code
|
50
|
43949326095
|
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 25 09:32:01 2019
@author: benja
"""
import pandas as pd
import re
import numpy as np
import os
from itertools import permutations
import multiprocessing as mp
import utils
import string
import json
import sys
from functools import partial
def fn_alias_matcher(name, name_list):
'''Return a name_listst of all uniq names that name could match
with that are in name_list.
e.g.: if name == 'Barbieri, Lindsay (Bar)',
returns 'Barbieri, Lindsay' and 'Barbieri, Bar' if both are in name_list
'''
try:
alias, full_non_alias = separate_alias(name)
if not alias:
return []
ln = full_non_alias.split(',')[0]
ln_matches = [s for s in name_list if ln+ ',' in s]
full_alias = ln +', ' + alias
full_non_alias = re.sub(f' \\({alias}\\)\s*', '', name)
#non_alias = full_non_alias.split(', ')[1]
#reverse_alias = f'{ln}, {alias} ({non_alias})'
matches = [s for s in ln_matches if any(
[s==name for name in (full_alias,
full_non_alias,
#reverse_alias
)]
)]
return list(set(matches))
except:
globals().update(locals())
print(name)
raise
def separate_alias(name):
alias_match = re.search(r'\([\w\s\.]+\)', name)
if alias_match:
alias = alias_match.group().strip(r'\(\)')
else:
return False, False
full_non_alias = re.sub(f' \\({alias}\\)\s*', '', name).strip()
return alias, full_non_alias
def ln_alias_matcher(name, name_list):
alias, full_non_alias = separate_alias(name)
alias = alias.replace('nee ', '')
full_non_alias = full_non_alias.strip('-')
if not alias:
return []
full_alias = alias + ',' + full_non_alias.split(',')[1]
out = []
matches = [s for s in name_list if any(
[s==name for name in (full_alias,
full_non_alias,
#reverse_alias
)]
)]
return list(set(matches))
def has_alias(name):
'''Return True if the name has a fn alias in it.'''
return bool(re.search(r'\([\w\s\.]+\)', name))
def extract_alias_authors(adf, fn= True):
'''Return a dataframe with one column: longer_name.
Having filtered down to only the longer_names that contain an alias.'''
return adf[adf['longer_name'].apply(has_alias)][['longer_name']]
def get_alias_type(name):
'Categorize and alias as being for a first or last name.'
parts = name.split(',')
if has_alias(parts[1]):
return 'first_name'
elif has_alias(re.split('[\s-]', parts[0])[1]) or re.search(r'\([\w\s\.]+\)-', parts[0]):
return 'last_name'
elif has_alias(parts[0].split(' ')[0]):
return 'first_name'
return None
def duplicate_alias_entries(adf):
'''Find all entries that have an author name with an alias:
e.g. 'Barbieri, Lindsay (Bar).'
Duplicate these entries, creating one for
each possible name. e.g. 'Barbieri, Lindsay' and Barbieri, Bar '''
alias_dict = {}
aliases = extract_alias_authors(adf)
aliases['type'] = aliases['longer_name'].apply(get_alias_type)
longer_names = adf['longer_name'].tolist()
for function, a_type in zip([fn_alias_matcher,
ln_alias_matcher],
['first_name',
'last_name']
):
alias_list = aliases[aliases['type']==a_type]
for alias in alias_list:
res = function(alias, longer_names)
if res:
alias_dict[alias] = res
for alias, li in alias_dict.items():
if li:
sel_rows = adf.loc[adf['longer_name']==alias]
#print(f'Duplicating {sel_rows.shape[0]} rows')
for name in li:
new_rows = sel_rows.copy()
new_rows['longer_name'] = name
new_rows['aut_tuple'] = new_rows['aut_tuple'].apply(
lambda li: [n.replace(alias, name) for n in li])
adf = adf.append(new_rows)
adf = adf[adf['longer_name']!=alias]
adf.index = range(0, adf.shape[0])
adf['aut_index'] = adf.index
return adf, alias_dict
def merge_from_aliases(adf, alias_dict):
vals = [v for v in alias_dict.values() if len(v)>1]
for li in vals:
for name in li[1:]:
adf.loc[adf['longer_name']==name, 'longer_name'] = li[0]
author_id = adf.loc[adf['longer_name'] == li[0], 'author_id'].iloc[0]
adf.loc[adf['longer_name']==name, 'author_id'] = author_id
#adf['indicies'] = adf['indicies'].apply(tuple)
return adf.drop_duplicates(subset=['longer_name', 'ID_num', 'indicies'])
#%%
def aut_cleaner(string):
'''CLean author names'''
string=re.sub(r'"|\[|', '', string)
string = re.sub(r"'|\]", '', string)
string = string.replace('()', '')
string = re.sub('\s+', ' ', string)
string = string.replace(' -', ' ')
return initials_list_to_initials(string)
def initials_list_to_initials(string):
'''Convert a name Doe, JF to Doe, J. F.'''
parts = name_spliter(string)
if len(parts)==2:
if parts[1].upper() == parts[1] and len(parts[1]) <= 3 and '.' not in parts[1]:
return string.replace(parts[1], '. '.join(parts[1])+'.')
return string
f_letter =re.compile(r'^.+?\,\s\w')
#load in postal codes data
postal_codes = json.loads(open(os.path.join('data', 'postal-codes.json')).read())
postal_codes = [item for item in postal_codes if item['Regex'] and item['ISO']]
pos_codes = [
{'country': item['Country'],
'iso': item['ISO'],
'regex': item['Regex'][1:-1].replace(r'\b', '')}
for item in postal_codes]
def uniq(li):
'''Return list of unique elements in a list.'''
return list(set(li))
def only_letters(stri):
'''Remove all non-letter characters from a string.'''
return ''.join([i for i in stri if i in string.ascii_letters])
def all_parts_match(name1, name2):
'''Checks for inconsistencies between two names.
Doe, John Edward will check true with Doe, J ; Doe, John, E; Doe, John -
But not with Doe, James; Doe, John F; Doe, John Ellis.'''
return all([
all([c1 == c2 for c1, c2 in
zip(only_letters(part1), only_letters(part2))])
for part1, part2 in zip(name1.split(), name2.split())])
def name_spliter(name):
'''Split name into its component parts.'''
name_spliter_re=re.compile(r'\,|\s')
try:
return [part.strip() for part in name_spliter_re.split(name) if part.strip()]
except:
print(name)
def name_num_dict(_string):
'''Turn an entry for ORCID IDs or Researcher IDs into a dict of
Name: id_num'''
pieces=[p for p in _string.split(';') if p.strip()]
try:
vals=[piece.split('/') for piece in pieces]
return {name.strip(): num.strip() for name, num in [v for v in vals if len(v)==2]}
except:
print(pieces)
raise
def consolidate_name_num_di(li_of_di):
'''Parse a list of dictionaries to make one name_num_dict'''
out={}
errors=[]
for di in li_of_di:
#if all values are either missing from dict or the same:
if all([out.get(key, value)==value for key, value in di.items()]):
out.update(di)
else:
errors+list(di.keys())
return out, errors
def name_num_dict_all(df, col):
'''Turn a column with ORCID or Researcher ID numbers into a dictionary of
Name: Id_num pairs.'''
valid=df.dropna(subset=[col])
return consolidate_name_num_di(
valid[col].apply(name_num_dict)
)
#%%
def parse_names1(string):
'''Name Parser for AU/AF columns.'''
return [aut_cleaner(name).strip() for name in string.split(';')]
def parse_names_idnum(string):
'''Name Parser for OI/RI columns.'''
pieces=[p.strip('-, ') for p in string.split(';')]
return [aut_cleaner(p.split('/')[0]).strip() for p in pieces]
name_cols=['AF', 'AU']
id_cols=['RI', 'OI']
def collect_all_names(row):
'''Get all versions of author name from a row of the dataframe.
Return all unique names, and a dictionary of id numbers.'''
names=[]
dis={}
for i, col in enumerate(name_cols):
if type(row[col])==str:
names+=parse_names1(row[col])
for col in id_cols:
if type(row[col])==str:
names+=parse_names_idnum(row[col])
dis[col]=name_num_dict(row[col])
else:
dis[col]={}
return names, dis
def make_name_dict(names, di, index):
'''From a list of names and a nested dictionary of
ID_nums, return a list of dics:
{names: list of associated names,
RI: Researcher ID if any.
OI: ORCID ID if any}'''
out=[]
fls=list(set([f_letter.search(n).group() for n in names if
f_letter.search(n)]))
#print(fls)
#collect all names that match a ln_fi group
try:
for fl in fls:
try:
fl_names=[n for n in names if re.search('^'+fl, n)]
except:
continue
if len (fl_names) >= 2:
au = fl_names[0]
af = fl_names[1]
else:
au = None
af = None
codes={}
for key, sub_dict in di.items():
for n in fl_names:
if n in sub_dict:
codes[key]=sub_dict[n]
break
elif len (n.split(', '))==2:
n=n.split(', ')[1]+', '+n.split(', ')[0]
if n in sub_dict:
fl_names.append(n)
codes[key]=sub_dict[n]
else:
codes[key]=None
if au:
#print(fl_names)
sub_out={**codes, **{'names': fl_names, 'indicies': index,
'AU': au, 'AF': af} }
out.append(sub_out)
return out
except:
globals().update(locals())
raise
def all_ids_row(row):
'''Collect all author identifiers for a given article.
Returns a list of dicts'''
try:
names, dis=collect_all_names(row)
return [{**{col: row[col] for col in row.index}, **row_dict}
for row_dict in make_name_dict(names, dis, row.name)]
except:
globals().update({'row': row})
raise
#%%
def flat_w_uniq(nested_li):
'''Flatten a list and remove redundant entries.'''
return list(set(utils.list_flattener(nested_li)))
#%%
def make_aut_df(df):
'''Get all name-forms associated with each numeric identifier for the two
identifier lists.'''
df['index'] = df.index
df['list_of_authors'] = df['AF'].str.lower().apply(lambda x: str(x).split(';'))
adf = pd.DataFrame(utils.list_flattener(
utils.parallelize_on_rows(
df, all_ids_row, num_of_processes=6).to_list()
)
)
#adf.drop(columns = ['ln_fi'], inplace = True )
adf.rename(columns= {'names': 'aut_tuple', 'index': 'ID_num'},
inplace = True)
return adf
def flat_uniq_nonnan(data):
'''Return a flat list of all non-Falsey, non-nan values.'''
return [i for i in flat_w_uniq(list(data)) if utils.is_valid(i)]
def ln_fi_from_group(li):
'''Get the lastname, first-initial pair for the longest name in a group of names.'''
return ln_fi_get(sorted(li, key=len)[-1])
def max_len(li):
'''Return the longest item in a list'''
return max(li, key=len)
def is_full_name(name):
'''Return whether the second part of a name has at least 2 letters in it.'''
if ',' in name:
return count_letters(name.split(',')[-1])>2
return False
def full_name_matches(li):
'''From a list of names, return a dictionary of possible matches. '''
matches = {}
for i in sorted(li, key= len, reverse = True):
res = []
for i2 in li:
if all_parts_match(i, i2) and (count_letters(i)>=count_letters(i2)) and i != i2:
res.append(i2)
matches[i] = res
return unpack_di_list(matches)
def sorted_dict_items(di, key):
'''Iterate through a dictionary sorted by key.'''
for k,v in sorted(di.items(), key=key):
yield k, v
def unpack_di_list(di):
'''Turn a dictionary where all values are lists into
a dictionary where each key is a value from those lists, and the value
is the key for that entry from the original dictionary.
Assign only if the entry is unique. '''
di = {k:v for k, v in di.items() if v}
di2 = {}
flat = utils.list_flattener(list(di.values()))
#iterate through dict
for k, li in sorted_dict_items(di, key = lambda x: len(x[0])):
if all_names_match_list(li) :
for name in li:
#Add to only if match is unique.
if name not in di.keys() or k not in flat:
#delete if item is already there to ensure unique dict
if di2.get(name):
di2[name]= 'Null'
else:
di2[name] = k
return {k:v for k,v in di2.items() if v != 'Null' }
#%%
def identifier_df(adf, ID, other_id):
'''Make a dataframe for the OId or RId column.
args : adf - author dataframe
ID : the identifier column name
other_id : the other Identifier column ID.
The resulting dataframe has the columns:
aut_tuple (list): all forms of the name associated with that ID number
inst, email, postal_code (lists): all institutions, email addresses and postal codes
associated with this ID number
indicies (list) : all indicies in the author dataframe where this author appears.
longer_name : longest version of the name that has been found.
last_name_first_init : last-name, first-initial. E.g Doe, J
longer_names : all forms of the name that are not just last-name, first intial,
would include Doe, John; Doe, J. E.; Doe John, E.; etc
'''
gb = adf.groupby(ID)
df = gb[['aut_tuple', 'inst', 'email', 'postal_code', 'indicies']].agg(flat_uniq_nonnan)
df[other_id]=gb[other_id].agg(set).apply(lambda x: x.pop() if len(x)==1 else None)
for column in ['inst', 'email', 'postal_code']:
#assign empty lists for null values
df.loc[df[column].isnull(), column] = [[]] * df[column].isnull().sum()
with mp.Pool(mp.cpu_count()) as pool:
df['longer_name'] = pool.map(max_len, df['aut_tuple'])
df['last_name_first_init'] = pool.map(ln_fi_get, df['longer_name'])
gb = df.reset_index().groupby('longer_name')
#df2 = gb[['aut_tuple', 'inst',
# 'email', 'postal_code', 'indicies']].agg('first')
df['longer_names'] = df['aut_tuple'].apply(
lambda x: [i for i in x if count_letters(i.split(',')[-1])>2])
'''
for column in ['inst', 'email', 'postal_code']:
df.loc[df[column].isnull(), column] = [[]] * df[column].isnull().sum()
cols = [ID, other_id, 'longer_name', 'last_name_first_init']
df[cols] = gb[cols].agg('first')
df.set_index(ID, inplace=True)
'''
return df
def count_letters(stri):
'''Return number of letters in a string.'''
return len(re.findall('|'.join(string.ascii_letters), stri))
def break_into_sub_cols(df, col):
'''Take a column that has a list of values in it, and exploded it such that each value
has its own column.
e.g. : df =
x
0 [1, 1, 1]
1 [ 2, 2]
break_into_sub_cols(df, 'x') yields:
x x_0 x_1 x_2
0 [1, 1, 1] 1 1 1
1 [2, 2] 2 2 NaN
'''
col_names=[f'{col}_{x}' for x in range(df[col].apply(len).max())]
df[col_names]=df[col].apply(pd.Series)
return df
def tuple_match(tup1, tup2):
'''Check if all items in tup1 are in tup2'''
return all([t in tup2 for t in tup1])
#def get_keys(tup_of_names, keys):
#
# return [k for k in keys if tuple_match(tup_of_names, k)]
f_letter_name=re.compile(r'^.+?\,\s\w$')
def authorfix(name):
'''Make three fixes to name '''
return list_of_initials_fix(
f_initial_no_dot_fix(
titlecase_fix(
name)
)
)
def titlecase_fix(name):
'''Ensure that last name is titlecase '''
pieces=name.split(',')
if len (pieces)==2:
return pieces[0].title()+',' +pieces[1]
else:
return name
def f_initial_no_dot_fix(name):
'''Turn name of form Doe, J to Doe, J.'''
if f_letter_name.search(name):
return name+'.'
return name
def list_of_initials_fix(string):
'''Turn a name of the form 'Johnson, LB' to
"Johnson, L. B. for consistency." '''
parts = name_spliter(string)
if len(parts)==2:
if parts[1].upper() == parts[1] and len(parts[1]) <= 3 and '.' not in parts[1]:
return string.replace(parts[1], '. '.join(parts[1])+'.')
return string
def aut_col_cleaner(names):
'''Clean author strings, then put them back together.'''
if type(names)==str:
return '; '.join([authorfix(name.strip()).lower() for name in names.split(';')])
else:
return names
#%%
def code_df_as_dict(df):
'''Convert the author-code df to a dictionary.'''
return {tuple(item): num for
item, num in zip(df['aut_tuple'].tolist(), df.index.tolist())}
def rebuild_df(series_list_dics):
'''Last step in converting a paralellized split operation back to a dataframe.'''
return pd.DataFrame(
utils.list_flattener(series_list_dics.tolist()))
def ln_fi_get(name):
'''Get the last-name first-initial form of the name.
e.g. ln_fi_get(Doe, John)
return Doe, J.'''
if f_letter.search(str(name)):
return f_letter.search(name).group()
def get_email(row):
'''If the EM column in the df has an email that matches
the author's first 5 letters of last name (or 3-4 if there are only 3-4) and first initial
separately.
return that email as a string.
'''
emails=row['EM']
if type(emails)!=str:
return None
emails=emails.split(';')
try:
string1 = re.search('\w{3,5}', row['longer_name'].split(',')[0].lower()).group()
string2 = row['last_name_first_init'][-1]
except:
return None
for em in emails:
if '@' not in em:
continue
n = em.split('@')[0]
if string1 in n and (string2 in n.replace(string1, '') or
only_letters(n) == string1):
return em.strip()
#%%
def make_matcher(adf, col_names):
'''Create a df for an alternate match field (or set off fields).
Return a dataframe with columns:
[col_names} +
indicies : all indicies associated with this
aut_tuple, longer name and an
id number based on those columns.'''
gb = adf.dropna(subset=col_names).groupby(
['last_name_first_init']+ col_names)
matches = pd.DataFrame(gb['aut_tuple'].agg(flat_uniq_nonnan))
matches['indicies'] = gb['indicies'].agg(list)
matches['longer_name'] = gb['longer_name'].agg(max_len)
#matches['last_name_first_init'] = gb['last_name_first_init'].agg('first')
matches=matches.reset_index()
matches['id_num'] = matches.index.map(lambda x: '_'.join(col_names)+str(x))
return matches
def split_by_first_letter(df, col):
'''Split a dataframe into a list of 26 dataframes.
Each one contains values for col where the first letter of that string is
that letter.'''
return [df[df[col].apply(lambda x: str(x)[0])==letter]
for letter in string.ascii_uppercase]
name_group=re.compile('\[.*?\]')
def string_to_list(_str, sep = '; '):
if _str[0] == '[':
return _str.strip('[]').split(sep)
def parse_multi_address(_string, name, row):
'''From a multi-address string :"[names] address [names] more address"
get the correct address for name. '''
if len(_string.split(';')) ==1 and '[' not in _string:
return _string
if '[' in _string and bool(re.search(f'{name}[;\]]', _string)):
names=re.findall(name_group, _string)
names=[parse_str_list(n) for n in names]
addresses=[i.strip() for i in re.split(name_group, _string) if i]
out={}
for name_list, address in zip(names, addresses):
for _name in name_list:
out[_name]=address
return out.get(name)
elif all([len(_string.split(';')) == len(row['list_of_authors']),
name in row['list_of_authors'],
'[' not in _string]):
return _string.split(';')[row['list_of_authors'].index(name)]
else:
return
def parse_address_2(string, name, row):
'''For parsing the corresponding author address in column "RP"
Split on the string 'corresponding author' Name appears before this string,
address appears after it.
'''
pieces = re.split('\(corresponding author\),', string)
for i, piece in enumerate(pieces):
if name in piece:
try:
return pieces[i+1].split(';')[0].strip()
except IndexError:
return None
def get_address(row):
'''Extract the author address from either column C1 (inst affiliation)
or from column RP (corresponding author).
Try these until a valid result is returned'''
for column, function in (('C1', parse_multi_address), ('RP', parse_address_2)):
res = use_address_function(row, column, function)
if res:
return res
def use_address_function(row, add_col, function):
'''Meta-function for managing the workflow of an address retrieving function.
Processes the string in row[add_col], and tries retreiving it using either of the
names in the name columns.
Stops when the function retreives a valid result.
'''
_string = row[add_col]
if type(_string)==str:
_string = _string.lower()
for col in ["AF", "AU"]:
name = row[col]
res = function(_string, name, row)
if res:
return res
#%%
def parse_str_list(string, sep=';'):
'''Return a string that encodes a list as a list.'''
string = string.replace('[', '').replace(']', '')
return [i.strip() for i in string.split(sep)]
def get_postal_code(string):
'''Get the postal code, if any encoded in the address.
Uses a list of postal code regexes. Returns:
a string of the format: "{ISO_country_code} {postal code}"
e.g. "US 01450"'''
if type(string) != str:
return None
string = string.upper()
if 'US' in string and re.search(r'\d{5}', string):
return 'US'+' ' + re.search(r'\d{5}', string).group()
else:
for item in pos_codes: #iterate through dict of postal codes
if check_postal_code_string(string, item):
return item['iso']+ ' ' + re.search(item['regex'], string).group()
return None
def check_postal_code_string(string, item):
'''Check whether a string matches a national postal code format.
Must have: right format and the country's name or iso abbrv '''
iso_re=re.compile(item['iso']+'?(,|$)')
if item['country'] in string or iso_re.search(string): #check for country name or ISO abbrv
return bool(re.search(item['regex'], string))
def extract_inst(string):
'''Extract institution from an address string.'''
if type(string)==str:
return string.split(',')[0].lower()
else:
return None
#%%
def get_uniq_items(df, column):
'''Get list of items that appear exactly once in a given column of a dataframe'''
val_counts = pd.DataFrame(df.value_counts(column)).reset_index()
uniq_names = val_counts[val_counts[0]==1][column]
return uniq_names
def add_to_list_df(row, col_name):
'''Concatenate the values for col_name from the left side of a merged dataframe
to those from the right side of a merged data.'''
try:
if not row[f'{col_name}_x']:
return row[f'{col_name}_y']
elif row[f'{col_name}_x'] in row[f'{col_name}_y']:
return row[f'{col_name}_y']
elif type(row[f'{col_name}_x'])==list:
return list(set(row[f'{col_name}_x']+row[f'{col_name}_y']))
else:
return list(set([row[f'{col_name}_x']]+row[f'{col_name}_y']))
except:
print(col_name)
raise
def nan_to_emptylist(data):
'''Convert nans to empty_lists.'''
data.loc[data.isnull()] = [[]] * data.isnull().sum()
return data
def match_by_columns(adf, ids, id_col, left_on, right_on):
'''Find addtional matches by matching on other columns.
Find any name entries that don't have an RI/OI,
but have an email/inst/postal_code (with last-name first-initial)
that matches a RI or OI entry.
Return the adf, updated with the id column filled in
and the ids updated with the new matches,
encoded as a list of indicies of matching entries.'''
m = adf[adf[id_col].isnull()].merge(
ids.dropna(subset=right_on).reset_index(),
left_on = left_on,
right_on = right_on,
how = 'inner')
if right_on[-1] =='email_0':
m.to_csv(os.path.join('data', f'{id_col}_emails.csv'))
try:
if not m.empty:
col_names =[c for c in ['email', 'inst', 'postal_code'] if c not in left_on]
#update the ids data_frame
for col_name in ['email', 'inst', 'postal_code', 'aut_tuple']:
ids.loc[m[f'{id_col}_y'], f'{col_name}'] = m.apply(
lambda row: add_to_list_df(row, col_name), axis=1).tolist()
for col in col_names:
ids[col] = nan_to_emptylist(ids[col])
print(f'{m.shape[0]} Matches Found')
#update author dataframe
adf.loc[m['aut_index'], id_col] = m[f'{id_col}_y'].tolist()
except:
print(m.columns, ids.columns, adf.columns)
raise
return adf, ids
def multi_val_matcher(adf, ids, id_col, col_name):
'''Add id numbers to the author dataframe by matching on another
column identifier: email, institution or postal code.
Because the ids df can have arbitrarily many values for the col name,
'''
ids=break_into_sub_cols(ids, col_name)
for sub_col in [c for c in ids.columns if f'{col_name}_' in c]:
adf, ids = match_by_columns(adf,
ids,
id_col,
left_on = ['last_name_first_init', col_name],
right_on = ['last_name_first_init', sub_col])
ids.drop(columns=[sub_col], inplace=True)
return adf, ids
def long_name_matcher(adf, ids, id_col):
'''Add IDs to the adf from an id_dataframe based
on exact matches of long-form names.'''
ids['longer_names'] = ids['longer_names'].apply(lambda li:
[i for i in li if is_full_name(i)])
ids=break_into_sub_cols(ids, 'longer_names')
print(f'Matching to {id_col} by longer name')
for sub_col in [c for c in ids.columns if 'longer_names_' in c]:
adf, ids = match_by_columns(adf, ids, id_col,
left_on = ['longer_name'],
right_on = [sub_col])
ids.drop(columns=[sub_col], inplace=True)
return adf, ids
def all_numeric_matchers(adf, ids, id_col):
'''Perform all matches to find pre-provided id numbers (RIs and OIs).
adf : author dataframe
ids : the identifier dataframe
id_col : the identifier column
each matching function collects additional data from other matching columns,
e.g. if the ids df has an id# for Doe, John and finds another Doe, John,
that whole entry becomes linked; the email address, institution and zip code
all are added to the adf.
'''
#Add to the
adf, ids = long_name_matcher(adf, ids, id_col)
for other_id in ['inst', 'email', 'postal_code']:
print(f'Matching to {id_col} by {other_id}')
adf, ids= multi_val_matcher(adf, ids, id_col, other_id)
return adf, ids
#%%
def extract_unique_vals(df, column):
'''Subset only those entries in the dataframe
with a unique value for column'''
indexer= df[column].value_counts()==1
return df[df[column].isin(indexer.index)]
def vals_of_at_least(df, column, thresh =2):
'''Subset the entries in a dataframe
that have a value for column that occurs at least thresh times.'''
indexer= df[column].value_counts()>=thresh
return df[df[column].isin(indexer.index)]
def alternate_matcher(adf, col_name):
'''Find matches based on other column values.
args - adf - author dataframe
col_name : column name
returns - adf with added ID numbers made for that column, and the matcher dataframe.
ID numbers are added for all matches of the combination of col_name and last_name_first_initial
So Doe, John and Doe, J. M. are matched if they both have the same value for col_name.
'''
print('Making new matcher dataframe. ')
matches = make_matcher(adf, [col_name])
print(matches.shape)
adf[f'{col_name}_id'] = None
m = try_merge(adf,
matches,
left_on = [col_name, 'last_name_first_init'],
right_on = [col_name, 'last_name_first_init'],
how = 'inner')
m = extract_unique_vals(m, 'aut_index')
m= vals_of_at_least(m, col_name)
if not m.empty:
print(f'{m.shape[0]} matches found')
print(m[col_name].head(5))
adf.loc[m['aut_index'], f'{col_name}_id'] = m['id_num'].tolist()
m2 = try_merge(adf,
matches[matches['longer_name'].apply(is_full_name)],
left_on = 'longer_name',
right_on = 'longer_name',
how = 'inner')
m2 = extract_unique_vals(m2, 'aut_index')
if not m2.empty:
adf.loc[m2['aut_index'], f'{col_name}_id'] = m2['id_num'].tolist()
return adf, matches
def try_merge(left, right, **kwargs):
'''Merge two dataframes together, using the standard pd.merge function.
If this results in a memory error, save the right-side dataframe
to a scratch csv and merge in chunks.'''
try:
return left.merge(right, **kwargs)
except MemoryError:
out = []
right.to_csv('scratch.csv')
reader = pd.read_csv('scratch.csv', chunksize = 1000)
for r in reader:
out.append(left.merge(r, **kwargs))
del r
os.remove('scratch.csv')
return pd.concat(out)
def row_names_match(row):
'''Check that the longer_names from a row created from a
df merge are matching.'''
return all_parts_match(row['longer_name_x'], row['longer_name_y'])
def match_to_codes_on_full_name(adf, match_cols, uniq_names):
'''Find any remaining full-name matches.
First between remaining names and '''
left= has_no_id(adf, match_cols, uniq_names)
codes = adf[(adf[match_cols].fillna(False).sum(axis =1) != 0)][['OI', "RI",
'email_id',
'inst_id',
'postal_code_id', 'longer_name', 'last_name_first_init']].copy()
codes = codes.groupby('longer_name').agg('first')
try:
#assign identifier info rows with full-name matches to the code df:
m = try_merge(left, codes,
left_on='last_name_first_init',
right_on = 'last_name_first_init', how = 'inner')
del codes
if m.empty:
print('No New Maches Found')
else:
m['matches'] = m.apply(row_names_match, axis=1)
for col in match_cols:
adf.loc[m[m['matches']]['aut_index'], col] = m[m['matches']][f'{col}_y'].tolist()
#adf['name_id'] = None
return adf
except:
globals().update(locals())
raise
def all_names_match_list(li):
return all([all_parts_match(x,y) for x,y in permutations(li,2)])
def all_ln_fi_match(left):
'''Search for First-name last-initial groups where all names are consistent.
Consistent names are defined as no clear contradictions between each other.
See all_parts_match for explanation
Assign these a 'name_ID' string.
'''
print(f'{left.shape[0]} remaining names to resolve.')
gb=left.dropna(subset=['last_name_first_init']).groupby('last_name_first_init')
indexer = pd.DataFrame(gb['longer_name'].agg(lambda x: list(set(x)))).dropna()
print('Finding all last-name, first initial groups with no inconsistencies.')
indexer = indexer.loc[indexer['longer_name'].apply(all_names_match_list)]
indexer['name_id'] = indexer.reset_index().reset_index()['index'].apply(
lambda x: f'name{str(x)}').tolist()
return indexer.merge(left, left_on = 'last_name_first_init',
right_on = 'last_name_first_init',
how = 'inner')
def li_o_di_to_di(li_o_di):
'''Convert a list of dicts to one dict.'''
out_dict={}
for di in li_o_di:
out_dict.update(di)
return out_dict
def has_no_id(adf, match_cols, uniq_names):
'''Return all entries that have no identifier in match_cols, and are not
a unique last-name, first-initial pair.'''
return adf[((adf[match_cols].fillna(False)!=False).sum(axis =1) == 0)
& (adf['last_name_first_init'].isin(uniq_names) ==False)].copy()
def assign_remaining_names(adf, match_cols):
'''Final Pass through names that do not yet have matches.
Assign all of them a unique identifier.
Then check to see if any of them
match with one another, purely based on name parts. '''
#Give a unique identifier to each unique value for longer-name
left = adf[(adf[match_cols].fillna(False)!=False).sum(axis =1) == 0].copy()
left_uniq = pd.DataFrame(
left['longer_name'].unique(), columns = ['longer_name']).reset_index()
left = try_merge(left, left_uniq, left_on = 'longer_name',
right_on ='longer_name', how ='left')
#assign a numeric string as a name identifier to each name
left['name_id'] = left['index'].apply(lambda x: f'name_{str(x + adf.shape[0])}')
#get all longer-name values for each lastname, first-initial value
names = left.groupby('last_name_first_init')['longer_name'].agg(list).apply(uniq)
#Dict of unique matches from a full-name matcher
out_dict = li_o_di_to_di(
names.apply(
full_name_matches).tolist())
left['match_name'] = left['longer_name'].apply(lambda x: out_dict.get(x,x))
#recombine data and retreive new name_ids:
keep_cols = ['match_name', 'longer_name', 'aut_index']
matcher = try_merge(left[keep_cols],
left[['name_id', 'longer_name']],
right_on = 'longer_name',
left_on = 'match_name', how ='inner')
#Collect names where new matches have been found.
matcher = matcher[matcher['longer_name_x'] != matcher['longer_name_y']]
#reattach these
left= try_merge(left, matcher, left_on ='aut_index',
right_on = 'aut_index', how = 'left')
#assign name_id to matches first, then to original if none exists.
left['name_id'] = left[['name_id_y', 'name_id_x']].apply(
utils.first_valid, axis = 1)
#assign name_ids numbers back to author dataframe
adf.loc[left['aut_index'], 'name_id'] = left['name_id'].tolist()
return adf
def assign_name_string(adf):
'''Assign the longest Name string available
to each unique author identifier.
Return the adf with that name in the column labelled "id_name"'''
gb = adf.groupby('author_id')['longer_name'].agg(lambda x: max(x, key=len))
adf = try_merge(adf, gb, left_on = 'author_id',
right_on = 'author_id', how = 'left')
return adf.rename(columns = {'longer_name_x' : 'longer_name',
'longer_name_y': 'id_name'})
def clean_data(df):
'''Format the dataframe for processing.
Apply author-cleaning to author columns and set other important columns to
lowercase.'''
df['AU'] = df['AU'].apply(aut_col_cleaner)
df['AF'] = df["AF"].apply(aut_col_cleaner)
for col in ["EM", "OI", "RI"]:
df[col] = df[col].apply(lambda x: str(x).lower())
return df.drop(columns = ['ln_fi'])
def prep_aut_df(adf):
'''Add columns to the author dataframe:
aut_index : an indexer number.
address : address if any
email : email address, if any
inst : institutional affiliation, if any
last_name_first_initial
postal_code : nation and number for postal code, if any'''
adf['address'] = utils.parallelize_on_rows(adf, get_address)
adf['longer_name'] = adf['aut_tuple'].apply(lambda x : sorted(x[1:], key = len)[-1])
with mp.Pool(mp.cpu_count()) as pool:
adf['last_name_first_init']=pool.map(ln_fi_get, adf['AF'])
adf['postal_code'] = pool.map(get_postal_code, adf['address'])
adf['aut_index'] = adf.index
assert adf['ID_num'].isnull().sum()== 0
adf['email']=utils.parallelize_on_rows(adf, get_email)
adf['inst']=adf['address'].apply(extract_inst)
return adf
def resolve_names(adf):
RIs = identifier_df(adf, 'RI', 'OI')
assert np.nan not in RIs['email'].tolist()
OIs = identifier_df(adf, 'OI', 'RI')
assert np.nan not in OIs['email'].tolist()
for ids, col in zip((RIs, OIs), ('RI', 'OI')):
adf[col].loc[adf[col].isin(ids.index) == False] = np.nan
print('Matching by RI')
adf, RIs = all_numeric_matchers(adf, RIs, 'RI')
print('Matching by OI')
adf, OIs = all_numeric_matchers(adf, OIs, 'OI')
assert adf['ID_num'].isnull().sum() == 0
#memory management
del OIs
del RIs
assert adf['ID_num'].isnull().sum()==0
matcher_dict={}
print("Matching by Email, Postal Code and Institution")
for col_name in ['email', 'postal_code', 'inst']:
print(f'Using {col_name} for matches')
adf, matcher_dict[col_name] = alternate_matcher(adf, col_name)
del matcher_dict[col_name]
assert f'{col_name}_id' in adf.columns
assert adf['ID_num'].isnull().sum()==0
match_cols= ['OI', "RI",
'email_id',
'inst_id',
'postal_code_id']
uniq_names=get_uniq_items(adf, 'last_name_first_init')
#to_solve = adf.loc[(adf['RI'].isnull()) & (adf['OI'].isnull()) & (adf['last_name_first_init'].isin(uniq_names) ==False )]
#RIs.to_csv(os.path.join('data', 'intermed_data', f'RIs{test_string}.csv')) #can
#OIs.to_csv(os.path.join('data', 'intermed_data', f'OIs{test_string}.csv'))
adf = match_to_codes_on_full_name(adf, match_cols, uniq_names)
adf['name_id'] = None
left = has_no_id(adf, match_cols, uniq_names)
name_matches = all_ln_fi_match(left)
adf.loc[name_matches['aut_index'], 'name_id'] = name_matches['name_id_x'].tolist()
match_cols.append('name_id')
assert adf['ID_num'].isnull().sum()==0
#adf.drop_duplicates(subset=['author_id']).to_csv(save_path)
print('Finding pure name-based matches.')
adf = assign_remaining_names(adf, match_cols)
adf['author_id'] = adf[match_cols].apply(utils.first_valid, axis = 1)
return adf
def main(df, test):
#assert df['ID_num'].isnull().sum()==0
df = clean_data(df)
columns_to_use = ['AF', "AU", "EM", "OI", "RI", "C1", "RP" ]
adf = make_aut_df(df.loc[:, columns_to_use])
print(f'Working with {adf.shape[0]} author-entries.')
assert adf['ID_num'].isnull().sum()==0
if not test:
del df
print('Formatting Author Data')
adf = prep_aut_df(adf)
adf, alias_dict = duplicate_alias_entries(adf)
adf = resolve_names(adf)
adf = merge_from_aliases(adf, alias_dict)
adf = assign_name_string(adf)
print('Making Identifier Dataframes')
assert adf['ID_num'].isnull().sum()==0
#del to_solve
#del ids
return adf
def save_results(adf, data_path,
save_path, article_data_save_path, nrows=None):
adf = adf[['ID_num', 'longer_name', 'author_id', 'OI', "RI",
'email_id',
'inst_id',
'postal_code_id']]
print('Saving Data')
adf.to_csv(save_path)
df = pd.read_csv(data_path, nrows = nrows)
adf=try_merge(adf, df, left_on = 'ID_num',
right_on= 'index', how = 'left')
adf.to_csv(article_data_save_path)
#%%
if __name__ == '__main__':
test = False
if test:
test_string = '_test'
else:
test_string = ''
if len (sys.argv) == 1:
save_dir = os.path.join('data', 'intermed_data')
data_path=os.path.join(save_dir, 'all_data_2.csv')
save_path=os.path.join(save_dir, f'all_author_data{test_string}.csv')
article_data_save_path = os.path.join(save_dir,
f'expanded_authors{test_string}.csv')
elif len(sys.argv) == 4:
data_path = sys.argv[1]
save_path = sys.argv[2]
article_data_save_path =sys.argv[3]
else:
raise ValueError(f'Script needs 3 arguments, data path and save path. {len(sys.argv)} args provided')
if test:
nrows = 2000*100
else:
nrows = None
df = pd.read_csv(data_path, nrows = nrows)
print(df.shape)
#assert df['ID_num'].isnull().sum()==0
#df = df.dropna(subset = ['AF'])[df['AF'].dropna().str.contains('Lal, R')]
adf = main(df,
test)
# =============================================================================
# adf = adf[['ID_num', 'longer_name', 'author_id']]
#
#
# save_results(adf, data_path,
# save_path, article_data_save_path, nrows)
#
# =============================================================================
|
bubalis/ae_sysreview
|
author_work.py
|
author_work.py
|
py
| 45,236 |
python
|
en
|
code
| 0 |
github-code
|
50
|
42931306467
|
#!/usr/bin/python3
def weight_average(my_list=[]):
if(len(my_list) == 0):
return 0
suma = 0
divisor = 0
for i in my_list:
suma += i[0] * i[1]
for i in my_list:
divisor += i[1]
return suma / divisor
|
valerepetto14/holbertonschool-higher_level_programming
|
0x04-python-more_data_structures/100-weight_average.py
|
100-weight_average.py
|
py
| 248 |
python
|
en
|
code
| 0 |
github-code
|
50
|
36348384155
|
import json
from .generalhandle import GeneralHandle
from .generalhandle import BaseHandle
from .converter import api2mc
from .converter import mc2api
import tornado.httpclient
import logging
logger = logging.getLogger('API')
APIVersion = 'V5.1.0.1.0.20170421'
CM_MAU_MQ = {
'ex': 'mau.cmmau.ex',
'key': 'mau.cmmau.k',
}
CM_MCU_MQ = {
'ex': 'mau.cmmcu.ex',
'key': 'mau.cmmcu.k',
}
class ConfListHandle(GeneralHandle):
"""
GET /confs
"""
_get = {
'action': 'redis',
'lua': 'v1/lua/getconflist.lua',
'converter': api2mc.conflist,
}
class MtHandle(GeneralHandle):
"""
GET /conf/{conf_id}/mt/{mt_id}
DELETE /conf/{conf_id}/mt/{mt_id}
"""
_get = {
'action': 'redis',
'lua': 'v1/lua/getmtinfo.lua',
'converter': api2mc.getmtinfo,
}
_delete = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_DELMT_REQ',
'converter': api2mc.delmt,
},
'ack': {
'msg': 'CMU_CM_DELMT_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_DELMT_NACK',
'converter': mc2api.defaultnack,
},
}
class CallMtHandle(GeneralHandle):
"""
PUT /conf/{conf_id}/mt/{mt_id}/online
"""
_put = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_CALLMT_REQ',
'converter': api2mc.callmt,
},
'ack': {
'msg': 'CMU_CM_CALLMT_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_CALLMT_NACK',
'converter': mc2api.defaultnack,
},
}
_delete = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_DROPMT_REQ',
'converter': api2mc.callmt,
},
'ack': {
'msg': 'CMU_CM_DROPMT_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_DROPMT_NACK',
'converter': mc2api.defaultnack,
},
}
class CancelInspectMtHandle(GeneralHandle):
"""
DELETE confs/{conf_id}/inspections/{mt_id}/{mode}
"""
_delete_mt = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_STOPSEEMT_REQ',
'converter': api2mc.newstopinspectmt,
},
'ack': {
'msg': 'CMU_CM_STOPSEEMT_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_STOPSEEMT_NACK',
'converter': mc2api.defaultnack,
},
}
_delete_vmp = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_STOPSEEVMP_REQ',
'converter': api2mc.newinspectvmp,
},
'ack': {
'msg': 'CMU_CM_STOPSEEVMP_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_STOPSEEVMP_NACK',
'converter': mc2api.defaultnack,
},
}
async def delete(self, *args, **kw):
key = 'conf/%s/selected/video/%s/1' % (self.path_args[0], self.path_args[1])
inspectinfo = self.db.hgetall(key)
if inspectinfo and inspectinfo[b'srctype'].decode() == '2':
await self.handle(self._delete_vmp, *args)
else:
await self.handle(self._delete_mt, *args)
class InspectMtHandle(GeneralHandle):
"""
GET confs/{conf_id}/inspections
POST confs/{conf_id}/inspections
DELETE confs/{conf_id}/inspections
"""
_get = {
'action': 'redis',
'lua': 'v1/lua/getinspectionlist.lua',
'converter': api2mc.getinspectionlist,
}
_post_mt = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_STARTSEEMT_REQ',
'converter': api2mc.inspectmt,
},
'ack': {
'msg': 'CMU_CM_STARTSEEMT_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_STARTSEEMT_NACK',
'converter': mc2api.defaultnack,
},
}
_post_vmp = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_STARTSEEVMP_REQ',
'converter': api2mc.inspectvmp,
},
'ack': {
'msg': 'CMU_CM_STARTSEEVMP_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_STARTSEEVMP_NACK',
'converter': mc2api.defaultnack,
},
}
_delete_mt = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_STOPSEEMT_REQ',
'converter': api2mc.stopinspectmt,
},
'ack': {
'msg': 'CMU_CM_STOPSEEMT_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_STOPSEEMT_NACK',
'converter': mc2api.defaultnack,
},
}
_delete_vmp = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_STOPSEEVMP_REQ',
'converter': api2mc.inspectvmp,
},
'ack': {
'msg': 'CMU_CM_STOPSEEVMP_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_STOPSEEVMP_NACK',
'converter': mc2api.defaultnack,
},
}
async def post(self, *args, **kw):
data = self.get_argument('params')
reqobj = json.loads(data)
if reqobj['src']['type'] == 2:
await self.handle(self._post_vmp, *args)
else:
await self.handle(self._post_mt, *args)
async def delete(self, *args, **kw):
data = self.get_argument('params')
reqobj = json.loads(data)
key = 'conf/%s/selected/video/%s/1' % (args[0], reqobj['dst']['mt_id'])
inspectinfo = self.db.hgetall(key)
if inspectinfo and inspectinfo[b'srctype'].decode() == '2':
await self.handle(self._delete_vmp, *args)
else:
await self.handle(self._delete_mt, *args)
class ChairManHandle(GeneralHandle):
"""
GET confs/{conf_id}/chairman
PUT confs/{conf_id}/chairman
"""
_get = {
'action': 'redis',
'lua': 'v1/lua/getchairman.lua',
'converter': api2mc.getchairman,
}
_put_set = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_SETCHAIRMAN_REQ',
'converter': api2mc.setchairman,
},
'ack': {
'msg': 'CMU_CM_SETCHAIRMAN_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_SETCHAIRMAN_NACK',
'converter': mc2api.defaultnack,
},
}
_put_cancel = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_CANCELCHAIRMAN_REQ',
'converter': api2mc.setchairman,
},
'ack': {
'msg': 'CMU_CM_CANCELCHAIRMAN_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_CANCELCHAIRMAN_NACK',
'converter': mc2api.defaultnack,
},
}
async def put(self, *args, **kw):
data = self.get_argument('params')
reqobj = json.loads(data)
if reqobj['mt_id'] != '':
await self.handle(self._put_set, *args)
else:
await self.handle(self._put_cancel, *args)
class UploadMtHandle(GeneralHandle):
"""
GET confs/{conf_id}/upload
PUT confs/{conf_id}/upload
"""
_get = {
'action': 'redis',
'lua': 'v1/lua/getupload.lua',
'converter': api2mc.getupload,
}
_put_start = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_SPECSRCOFMMCU_REQ',
'converter': api2mc.startupload,
},
'ack': {
'msg': 'CMU_CM_SPECSRCOFMMCU_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_SPECSRCOFMMCU_NACK',
'converter': mc2api.defaultnack,
},
}
_put_cancel = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_CANCELSRCOFMMCU_CMD',
'converter': api2mc.sete164,
}
}
async def put(self, *args, **kw):
data = self.get_argument('params')
reqobj = json.loads(data)
if reqobj['mt_id'] != '':
await self.handle(self._put_start, *args)
else:
await self.handle(self._put_cancel, *args)
class SpeakerHandle(GeneralHandle):
"""
GET conf/{conf_id}/speaker
PUT conf/{conf_id}/speaker
"""
_get = {
'action': 'redis',
'lua': 'v1/lua/getspeaker.lua',
'converter': api2mc.getspeaker,
}
_put_set = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_SETSPEAKER_REQ',
'converter': api2mc.setspeaker,
},
'ack': {
'msg': 'CMU_CM_SETSPEAKER_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_SETSPEAKER_NACK',
'converter': mc2api.defaultnack,
},
}
_put_cancel = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_CANCELSPEAKER_REQ',
'converter': api2mc.sete164,
},
'ack': {
'msg': 'CMU_CM_CANCELSPEAKER_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_CANCELSPEAKER_NACK',
'converter': mc2api.defaultnack,
},
}
async def put(self, *args, **kw):
params = self.get_argument('params')
reqobj = json.loads(params)
if reqobj['mt_id'] != '':
await self.handle(self._put_set, *args)
else:
await self.handle(self._put_cancel, *args)
class ConfSilenceHandle(GeneralHandle):
"""
PUT conf/{conf_id}/silence
"""
_put_set = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_CONFSILENCE_REQ',
'converter': api2mc.sete164,
},
'ack': {
'msg': 'CMU_CM_CONFSILENCE_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_CONFSILENCE_NACK',
'converter': mc2api.defaultnack,
},
}
_put_cancel = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_CANCELCONFSILENCE_REQ',
'converter': api2mc.sete164,
},
'ack': {
'msg': 'CMU_CM_CANCELCONFSILENCE_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_CANCELCONFSILENCE_NACK',
'converter': mc2api.defaultnack,
},
}
async def put(self, *args, **kw):
params = self.get_argument('params')
reqobj = json.loads(params)
if reqobj['value'] == 1:
await self.handle(self._put_set, *args)
else:
await self.handle(self._put_cancel, *args)
class ConfMuteHandle(GeneralHandle):
"""
PUT conf/{conf_id}/mute
"""
_put_set = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_CONFMUTE_REQ',
'converter': api2mc.sete164,
},
'ack': {
'msg': 'CMU_CM_CONFMUTE_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_CONFMUTE_NACK',
'converter': mc2api.defaultnack,
},
}
_put_cancel = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_CANCELCONFMUTE_REQ',
'converter': api2mc.sete164,
},
'ack': {
'msg': 'CMU_CM_CANCELCONFMUTE_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_CANCELCONFMUTE_NACK',
'converter': mc2api.defaultnack,
},
}
async def put(self, *args, **kw):
params = self.get_argument('params')
reqobj = json.loads(params)
if reqobj['value'] == 1:
await self.handle(self._put_set, *args)
else:
await self.handle(self._put_cancel, *args)
class ConfHandle(GeneralHandle):
"""
GET conf/{conf_id}
"""
_get = {
'action': 'redis',
'converter': api2mc.conf,
'lua': 'v1/lua/getconf.lua'
}
class ConfState(GeneralHandle):
"""
GET confs/{conf_id}/state
"""
_get = {
'action': 'redis',
'converter': api2mc.confstate,
'lua': 'v1/lua/getconfstate.lua'
}
class CascadesConfHandle(GeneralHandle):
"""
GET conf/{conf_id}/cascades
"""
_get = {
'action': 'redis',
'converter': api2mc.getcascadeconf,
'lua': 'v1/lua/getcascades.lua'
}
class CascadesMtHandle(GeneralHandle):
"""
GET conf/{conf_id}/cascades/{cascade_id}/mts
POST confs/{conf_id}/cascades/{cascade_id}/mts
"""
_get = {
'action': 'redis',
'converter': api2mc.getcascademts,
'lua': 'v1/lua/getcascademts.lua'
}
_post = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_ADDMT_REQ',
'converter': api2mc.addcascadesmt,
},
'ack': {
'msg': 'CMU_CM_ADDMT_ACK',
'converter': mc2api.cascadesaddmtack,
},
'nack': {
'msg': 'CMU_CM_ADDMT_NACK',
'converter': mc2api.defaultnack,
},
}
class DelayConfHandle(GeneralHandle):
"""
POST conf/{conf_id}/delay
"""
_post = {
'action': 'mqrpc',
'mq': CM_MAU_MQ,
'req': {
'msg': 'CM_MAU_DELAYCONF_REQ',
'converter': api2mc.delayconf,
},
'ack': {
'msg': 'MAU_CM_DELAYCONF_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'MAU_CM_DELAYCONF_NACK',
'converter': mc2api.defaultnack,
},
}
class MtSlienceHandle(GeneralHandle):
"""
PUT conf/{conf_id}/mt/{mt_id}/silence
"""
_put_set = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_MTSILENCE_REQ',
'converter': api2mc.setmtchnl,
},
'ack': {
'msg': 'CMU_CM_MTSILENCE_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_MTSILENCE_NACK',
'converter': mc2api.defaultnack,
},
}
_put_cancel = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_CANCELMTSILENCE_REQ',
'converter': api2mc.setmtchnl,
},
'ack': {
'msg': 'CMU_CM_CANCELMTSILENCE_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_CANCELMTSILENCE_NACK',
'converter': mc2api.defaultnack,
},
}
async def put(self, *args, **kw):
params = self.get_argument('params')
reqobj = json.loads(params)
if reqobj['value'] == 1:
await self.handle(self._put_set, *args)
else:
await self.handle(self._put_cancel, *args)
class MtMuteHandle(GeneralHandle):
"""
PUT conf/{conf_id}/mt/{mt_id}/mute
"""
_put_set = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_MTMUTE_REQ',
'converter': api2mc.setmtchnl,
},
'ack': {
'msg': 'CMU_CM_MTMUTE_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_MTMUTE_NACK',
'converter': mc2api.defaultnack,
},
}
_put_cancel = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_CANCELMTMUTE_REQ',
'converter': api2mc.setmtchnl,
},
'ack': {
'msg': 'CMU_CM_CANCELMTMUTE_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_CANCELMTMUTE_NACK',
'converter': mc2api.defaultnack,
},
}
async def put(self, *args, **kw):
params = self.get_argument('params')
reqobj = json.loads(params)
if reqobj['value'] == 1:
await self.handle(self._put_set, *args)
else:
await self.handle(self._put_cancel, *args)
class ConfMonitorHandle(GeneralHandle):
"""
GET conf/{conf_id}/monitors
POST conf/{conf_id}/monitors
"""
_get = {
'action': 'redis',
'lua': 'v1/lua/getmonitorlist.lua',
'converter': api2mc.getmonitorlist,
}
_post_start = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_STARTMONITORING_REQ',
'converter': api2mc.startmonitor,
},
'ack': {
'msg': 'CMU_CM_STARTMONITORING_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_STARTMONITORING_NACK',
'converter': mc2api.defaultnack,
},
}
_post_startvmp = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_STARTMONITORING_VMP_REQ',
'converter': api2mc.startmonitorvmp,
},
'ack': {
'msg': 'CMU_CM_STARTMONITORING_VMP_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_STARTMONITORING_VMP_NACK',
'converter': mc2api.defaultnack,
},
}
_post_startmix = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_STARTMONITORING_MIXER_REQ',
'converter': api2mc.startmonitormix,
},
'ack': {
'msg': 'CMU_CM_STARTMONITORING_MIXER_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_STARTMONITORING_MIXER_NACK',
'converter': mc2api.defaultnack,
},
}
# _delete = {
# 'action': 'mqpush',
# 'mq': CM_MCU_MQ,
# 'cmd': {
# 'msg': 'CM_CMU_STOPMONITORING_CMD',
# 'converter': api2mc.stopmonitor,
# },
# }
async def post(self, *args, **kw):
params = self.get_argument('params')
reqobj = json.loads(params)
if reqobj['mode'] == 0 and reqobj['src']['type'] == 2:
await self.handle(self._post_startvmp, *args)
elif reqobj['mode'] == 1 and reqobj['src']['type'] == 3:
await self.handle(self._post_startmix, *args)
else:
await self.handle(self._post_start, *args)
class ConfSigleMonitorHandle(GeneralHandle):
"""
GET confs/{conf_id}/monitors/{dst_ip}/{dst_port}
DELETE confs/{conf_id}/monitors/{dst_ip}/{dst_port}
"""
_get = {
'action': 'redis',
'lua': 'v1/lua/getmonitorinfo.lua',
'converter': api2mc.getmonitorinfo,
}
_delete = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_STOPMONITORING_CMD',
'converter': api2mc.stopmonitor,
},
}
class NeedIFrameHandle(GeneralHandle):
"""
POST /api/v1/vc/confs/{conf_id}/neediframe/monitors
"""
_post = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_NEEDIFRAME_CMD',
'converter': api2mc.neediframe,
}
}
class MonitorAliveHandle(GeneralHandle):
"""
POST conf/{conf_id}/monitor/keepalive
"""
_post = {
'action': 'mqpush',
'mq': CM_MAU_MQ,
'cmd': {
'msg': 'CM_MAU_MONITORKEEPALIVE_NTF',
'converter': api2mc.monitorkeepalive,
}
}
class ConfSaftyHandle(GeneralHandle):
"""
POST conf/{conf_id}/safety
"""
_put = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_SETCONFSAFE_REQ',
'converter': api2mc.setconfsafty,
},
'ack': {
'msg': 'CMU_CM_SETCONFSAFE_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_SETCONFSAFE_NACK',
'converter': mc2api.defaultnack,
},
}
class VmpStartHandle(GeneralHandle):
"""
POST conf/{conf_id}/vmp
"""
_post = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_STARTVMP_REQ',
'converter': api2mc.startvmp,
},
'ack': {
'msg': 'CMU_CM_STARTVMP_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_STARTVMP_NACK',
'converter': mc2api.defaultnack,
},
}
class VmpHandle(GeneralHandle):
"""
GET conf/{conf_id}/vmp/{vmp_id}
POST conf/{conf_id}/vmp/{vmp_id}
DELETE conf/{conf_id}/vmp/{vmp_id}
"""
_get = {
'action': 'redis',
'converter': api2mc.getvmpinfo,
'lua': 'v1/lua/getvmpinfo.lua'
}
_post = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_CHANGEVMPPARAM_REQ',
'converter': api2mc.changevmp,
},
'ack': {
'msg': 'CMU_CM_CHANGEVMPPARAM_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_CHANGEVMPPARAM_NACK',
'converter': mc2api.defaultnack,
}
}
_delete = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_STOPVMP_REQ',
'converter': api2mc.stopvmp,
},
'ack': {
'msg': 'CMU_CM_STOPVMP_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_STOPVMP_NACK',
'converter': mc2api.defaultnack,
},
}
class StartMixerHandle(GeneralHandle):
"""
POST conf/{conf_id}/mix
"""
_post = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_STARTMIX_REQ',
'converter': api2mc.startmixer,
},
'ack': {
'msg': 'CMU_CM_STARTMIX_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_STARTMIX_NACK',
'converter': mc2api.defaultnack,
},
}
class MixerHandle(GeneralHandle):
"""
GET conf/{conf_id}/mix/{mix_id}
DELETE conf/{conf_id}/mix/{mix_id}
"""
_get = {
'action': 'redis',
'converter': api2mc.getmixer,
'lua': 'v1/lua/getmixer.lua'
}
_delete = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_STOPMIX_REQ',
'converter': api2mc.stopmix,
},
'ack': {
'msg': 'CMU_CM_STOPMIX_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_STOPMIX_NACK',
'converter': mc2api.defaultnack,
},
}
class MixerMembersHandle(GeneralHandle):
"""
POST conf/{conf_id}/mix/{mix_id}/members
DELETE conf/{conf_id}/mix/{mix_id}/members
"""
_post = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_ADDMIXMEMBER_CMD',
'converter': api2mc.setmixmembers,
},
}
_delete = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_REMOVEMIXMEMBER_CMD',
'converter': api2mc.setmixmembers,
},
}
class ConfPollStateHandle(GeneralHandle):
"""
PUT conf/{conf_id}/poll/state
"""
_put_pause = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_PAUSEPOLL_CMD',
'converter': api2mc.handlepollstate,
},
}
_put_resume = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_RESUMEPOLL_CMD',
'converter': api2mc.handlepollstate,
},
}
_put_stop = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_STOPPOLL_CMD',
'converter': api2mc.handlepollstate,
},
}
async def put(self, *args, **kw):
params = self.get_argument('params')
reqobj = json.loads(params)
funcdict = {
0: self._put_stop,
1: self._put_pause,
2: self._put_resume,
}
await self.handle(funcdict[reqobj['value']], *args)
class ConfPollHandle(GeneralHandle):
"""
GET conf/{conf_id}/poll
PUT conf/{conf_id}/poll/
"""
_get = {
'action': 'redis',
'converter': api2mc.getpollinfo,
'lua': 'v1/lua/getpollinfo.lua'
}
_put = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_STARTPOLL_CMD',
'converter': api2mc.startpoll,
},
}
class ConfVadHandle(GeneralHandle):
"""
GET /confs/([0-9]+)/vad
PUT confs/([0-9]+)/vad
"""
_get = {
'action': 'redis',
'converter': api2mc.getvadinfo,
'lua': 'v1/lua/getvadinfo.lua'
}
_put_start = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_STARTMIX_REQ',
'converter': api2mc.startvad,
},
'ack': {
'msg': 'CM_CMU_STARTMIX_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CM_CMU_STARTMIX_NACK',
'converter': mc2api.defaultnack,
},
}
_put_stop = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_STOPMIX_REQ',
'converter': api2mc.stopvad,
},
'ack': {
'msg': 'CMU_CM_STOPMIX_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_STOPMIX_NACK',
'converter': mc2api.defaultnack,
},
}
async def put(self, *args, **kw):
params = self.get_argument('params')
reqobj = json.loads(params)
funcdict = {
0: self._put_stop,
1: self._put_start,
}
await self.handle(funcdict[reqobj['state']], *args)
class ShortMsgHandle(GeneralHandle):
"""
POST conf/{conf_id}/msg
"""
_post = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_SENDMSG_CMD',
'converter': api2mc.sendmsg,
}
}
class MtRecHandle(GeneralHandle):
"""
POST confs/{conf_id}/mt_recoder/{mt_id}
"""
_post_pause = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_PAUSEPLAY_REQ',
# 'converter': api2mc.rechandle,
},
'ack': {
'msg': 'CMU_CM_PAUSEPLAY_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_PAUSEPLAY_NACK',
'converter': mc2api.defaultnack,
},
}
_post_resume = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_RESUMEPLAY_REQ',
# 'converter': api2mc.rechandle,
},
'ack': {
'msg': 'CMU_CM_RESUMEPLAY_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_RESUMEPLAY_NACK',
'converter': mc2api.defaultnack,
},
}
_post_stop = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_STOPPLAY_REQ',
# 'converter': api2mc.rechandle,
},
'ack': {
'msg': 'CMU_CM_STOPPLAY_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_STOPPLAY_NACK',
'converter': mc2api.defaultnack,
},
}
async def post(self, *args, **kw):
params = self.get_argument('params')
reqobj = json.loads(params)
funcdict = {
0: self._post_pause,
1: self._post_resume,
2: self._post_stop,
}
await self.handle(funcdict[reqobj['state']], *args)
class MtListVmpsHandle(GeneralHandle):
"""
GET confs/{conf_id}/mtvmps
POST confs/{conf_id}/mtvmps
"""
_get = {
'action': 'redis',
'converter': api2mc.getmtlistvmps,
'lua': 'v1/lua/getmtlistvmps.lua'
}
_post = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_STARTMTVMP_REQ',
'converter': api2mc.startmtvmp,
},
'ack': {
'msg': 'CMU_CM_STARTMTVMP_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_STARTMTVMP_NACK',
'converter': mc2api.defaultnack,
}
}
class MtVmpsHandle(GeneralHandle):
"""
GET confs/{conf_id}/mtvmps/{mt_id}
PUT confs/{conf_id}/mtvmps/{mt_id}
DELETE confs/{conf_id}/mtvmps/{mt_id}
"""
_get = {
'action': 'redis',
'converter': api2mc.getmtvmps,
'lua': 'v1/lua/getmtvmps.lua'
}
_put = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_CHANGEMTVMPPARAM_REQ',
'converter': api2mc.changemtvmps,
},
'ack': {
'msg': 'CMU_CM_CHANGEMTVMPPARAM_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_CHANGEMTVMPPARAM_NACK',
'converter': mc2api.defaultnack,
}
}
_delete = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_STOPMTVMP_REQ',
'converter': api2mc.stopmtvmps,
},
'ack': {
'msg': 'CMU_CM_STOPMTVMP_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_STOPMTVMP_NACK',
'converter': mc2api.defaultnack,
}
}
class HduListVmpsHandle(GeneralHandle):
"""
GET confs/{conf_id}/hduvmps
POST confs/{conf_id}/hduvmps
"""
_get = {
'action': 'redis',
'lua': 'v1/lua/gethduvmpslist.lua',
'converter': api2mc.gethduvmpslist,
}
_post = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_STARTHDUVMP_REQ',
'converter': api2mc.starthduvmps,
},
'ack': {
'msg': 'CMU_CM_STARTHDUVMP_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_STARTHDUVMP_NACK',
'converter': mc2api.defaultnack,
}
}
class HduVmpsHandle(GeneralHandle):
"""
GET confs/{conf_id}/hduvmps/{hdu_id}
PUT confs/{conf_id}/hduvmps/{hdu_id}
DELETE confs/{conf_id}/hduvmps/{hdu_id}
"""
_get = {
'action': 'redis',
'lua': 'v1/lua/gethduvmps.lua',
'converter': api2mc.gethduvmps,
}
_put = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_CHANGEHDUVMP_REQ',
'converter': api2mc.changehduvmps,
},
'ack': {
'msg': 'CMU_CM_CHANGEHDUVMP_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_CHANGEHDUVMP_NACK',
'converter': mc2api.defaultnack,
}
}
_delete = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_STOPHDUVMP_REQ',
'converter': api2mc.stophduvmps,
},
'ack': {
'msg': 'CMU_CM_STOPHDUVMP_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_STOPHDUVMP_NACK',
'converter': mc2api.defaultnack,
}
}
class SpecDualkSrcHandle(GeneralHandle):
"""
GET confs/{conf_id}/dualstream
PUT confs/{conf_id}/dualstream
DELETE confs/{conf_id}/dualstream
"""
_get = {
'action': 'redis',
'lua': 'v1/lua/getdualstream.lua',
'converter': api2mc.getdualstream,
}
_put_start = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_SPECDUALSRC_CMD',
'converter': api2mc.specdualsrc,
}
}
_put_stop = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_CANCELDUALSRC_CMD',
'converter': api2mc.stopspecdualsrc,
}
}
_delete = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_CANCELDUALSRC_CMD',
'converter': api2mc.specdualsrc,
}
}
async def put(self, *args, **kw):
params = self.get_argument('params')
reqobj = json.loads(params)
if reqobj['mt_id'] != '':
await self.handle(self._put_start, *args)
else:
key = "conf/%s/dualstream" % self.path_args[0]
dualinfo = self.db.hgetall(key)
if dualinfo:
await self.handle(self._put_stop, *args, dualinfo[b'mtcascade'].decode(), dualinfo[b'mtid'].decode())
else:
msg = {
'success': 0,
'error_code': 22014,
}
self.write(msg)
class MtCameraRCHandle(GeneralHandle):
"""
POST conf/{conf_id}/mt/{mt_id}/camera/state
"""
_post_start = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_MTCAMERA_MOV_CMD',
'converter': api2mc.camerarc,
}
}
_post_stop = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_MTCAMERA_STOP_CMD',
'converter': api2mc.camerarc,
}
}
async def post(self, *args, **kw):
params = self.get_argument('params')
reqobj = json.loads(params)
if reqobj['state'] == 0:
await self.handle(self._post_start, *args)
else:
await self.handle(self._post_stop, *args)
class MtVolumHandle(GeneralHandle):
"""
POST conf/{conf_id}/mt/{mt_id}/volum
"""
_put = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_MODMTVOLUME_CMD',
'converter': api2mc.mtvolum,
}
}
class ConfHduListHandle(GeneralHandle):
"""
GET confs/{conf_id}/hdus
POST confs/{conf_id}/hdus
"""
_get = {
'action': 'redis',
'lua': 'v1/lua/getconfhdulist.lua',
'converter': api2mc.getconfhdulist,
}
_post = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_STARTHDUSWITCH_REQ',
'converter': api2mc.newstarthdu,
},
'ack': {
'msg': 'CMU_CM_STARTHDUSWITCH_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_STARTHDUSWITCH_NACK',
'converter': mc2api.defaultnack,
}
}
_post_startpoll = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_STARTHDUPOLL_CMD',
'converter': api2mc.newstarthdupoll,
},
}
_post_change = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_CHANGEHDUVMPMODE_CMD',
'converter': api2mc.newstophdu,
},
}
async def post(self, *args, **kw):
params = self.get_argument('params')
reqobj = json.loads(params)
if reqobj['mode'] == 2:
await self.handle(self._post_change, *args)
self.clear()
if reqobj['mode'] != 3:
funcdict = self._post
elif reqobj['mode'] == 3:
funcdict = self._post_startpoll
await self.handle(funcdict, *args)
class PlatformHduListHandle(GeneralHandle):
"""
GET hdus
"""
_get = {
'action': 'mqrpc',
'mq': CM_MAU_MQ,
'req': {
'msg': 'CM_MAU_GETHDUINFOBYMOID_REQ',
'converter': api2mc.hdulist,
},
'ack': {
'msg': 'MAU_CM_GETHDUINFOBYMOID_ACK',
'converter': mc2api.hdulist,
},
'nack': {
'msg': 'MAU_CM_GETHDUINFOBYMOID_NACK',
'converter': mc2api.defaultnack,
}
}
class HduHandle(GeneralHandle):
"""
GET conf/{conf_id}/hdu/{hdu_id}
POST conf/{conf_id}/hdu/{hdu_id}
DELETE conf/{conf_id}/hdu/{hdu_id}
"""
_get = {
'action': 'redis',
'lua': 'v1/lua/gethduchninfo.lua',
'converter': api2mc.gethduchninfo,
}
_post_start = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_STARTHDUSWITCH_REQ',
'converter': api2mc.starthdu,
},
'ack': {
'msg': 'CMU_CM_STARTHDUSWITCH_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_STARTHDUSWITCH_NACK',
'converter': mc2api.defaultnack,
}
}
_post_stop = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_STOPHDUSWITCH_REQ',
'converter': api2mc.stophdu,
},
'ack': {
'msg': 'CMU_CM_STOPHDUSWITCH_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_STOPHDUSWITCH_NACK',
'converter': mc2api.defaultnack,
}
}
_post_startpoll = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_STARTHDUPOLL_CMD',
'converter': api2mc.starthdupoll,
},
}
_post_stoppoll = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_STOPHDUPOLL_CMD',
'converter': api2mc.stophdupoll,
},
}
_delete_hdu = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_STOPHDUSWITCH_REQ',
'converter': api2mc.deletehdu,
},
'ack': {
'msg': 'CMU_CM_STOPHDUSWITCH_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_STOPHDUSWITCH_NACK',
'converter': mc2api.defaultnack,
}
}
_delete_poll = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_STOPHDUPOLL_CMD',
'converter': api2mc.stophdupoll,
},
}
_post_change = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_CHANGEHDUVMPMODE_CMD',
'converter': api2mc.stophdu,
},
}
async def delete(self, *args, **kw):
hdu_id = self.path_args[1].replace('_', '/')
key = 'conf/%s/tvwall/%s' % (self.path_args[0], hdu_id)
hduinfo = self.db.hgetall(key)
if hduinfo:
if hduinfo[b'style'].decode() == '0' and hduinfo[b'hdutype'].decode() == '1':
await self.handle(self._delete_poll, *args)
else:
await self.handle(self._delete_hdu, *args, hduinfo[b'style'].decode())
else:
msg = {
'success': 0,
'error_code': 20052,
}
self.write(msg)
async def post(self, *args, **kw):
params = self.get_argument('params')
reqobj = json.loads(params)
if reqobj['occupy'] == 1 and reqobj['mode'] == 2:
await self.handle(self._post_change, *args)
self.clear()
if reqobj['mode'] != 3:
funcdict = {
0: self._post_stop,
1: self._post_start,
}
elif reqobj['mode'] == 3:
funcdict = {
0: self._post_stoppoll,
1: self._post_startpoll,
}
await self.handle(funcdict[reqobj['occupy']], *args)
class MtListHandle(GeneralHandle):
"""
POST conf/{conf_id}/mtlist
DELETE conf/{conf_id}/mtlist
GET /conf/{conf_id}/mts'
"""
_get = {
'action': 'redis',
'lua': 'v1/lua/getconfmtlist.lua',
'converter': api2mc.getconfmtlist,
}
_post = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_ADDMT_REQ',
'converter': api2mc.addmts,
},
'ack': {
'msg': 'CMU_CM_ADDMT_ACK',
'converter': mc2api.addmtack,
},
'nack': {
'msg': 'CMU_CM_ADDMT_NACK',
'converter': mc2api.defaultnack,
}
}
_delete = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_DELMT_REQ',
'converter': api2mc.delmts,
},
'ack': {
'msg': 'CMU_CM_DELMT_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_DELMT_NACK',
'converter': mc2api.defaultnack,
}
}
class MtsStateHandle(GeneralHandle):
"""
POST conf/{conf_id}/mts/state
"""
_post = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_CALLMT_REQ',
'converter': api2mc.setmts,
},
'ack': {
'msg': 'CMU_CM_CALLMT_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_CALLMT_NACK',
'converter': mc2api.defaultnack,
}
}
_delete = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_DROPMT_REQ',
'converter': api2mc.setmts,
},
'ack': {
'msg': 'CMU_CM_DROPMT_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_DROPMT_NACK',
'converter': mc2api.defaultnack,
}
}
async def recorderHandle(self, method_action, *args, **kw):
try:
account_info = await self.valid_token()
if account_info is not None:
if method_action is not None:
method = self.request.method
if method == 'POST':
params = self.get_argument('params')
reqobj = json.loads(params)
if method == 'GET' or account_info['enableVRS'] and \
(reqobj['recorder_mode'] == 1 or account_info['enableLive']):
action = getattr(self, method_action['action'])
await action(method_action, account_info, *args, **kw)
else:
msg = {
'success': 0,
'error_code': 20005,
}
logger.error(msg)
self.write(msg)
else:
logger.debug('method_action is none')
handle = getattr(BaseHandle, self.request.method.lower())
handle(self, *args, **kw)
except tornado.httpclient.HTTPError as e:
print(e)
msg = {
'success': 0,
'error_code': 10102,
}
logger.error(msg)
self.write(msg)
class RecordersHandle(GeneralHandle):
"""
GET confs/{conf_id}/recorders
POST confs/{conf_id}/recorders
"""
handle = recorderHandle
_get = {
'action': 'redis',
'lua': 'v1/lua/getrecorderlist.lua',
'converter': api2mc.getrecorderlist,
}
_post = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_STARTREC_REQ',
'converter': api2mc.startrecorder,
},
'ack': {
'msg': 'CMU_CM_STARTREC_ACK',
'converter': mc2api.startrecack,
},
'nack': {
'msg': 'CMU_CM_STARTREC_NACK',
'converter': mc2api.defaultnack,
}
}
class RecorderInsHandle(GeneralHandle):
"""
GET confs/{conf_id}/recorders/{rec_id}
DELETE confs/{conf_id}/recorders/{rec_id}
"""
_get = {
'action': 'redis',
'lua': 'v1/lua/getrecorderstate.lua',
'converter': api2mc.getrecorderstate,
}
_delete = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_STOPREC_REQ',
'converter': api2mc.recorderoperator,
},
'ack': {
'msg': 'CMU_CM_STOPREC_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_STOPREC_NACK',
'converter': mc2api.defaultnack,
}
}
class RecorderStateHandle(GeneralHandle):
""""
PUT confs/{conf_id}/recorders/{rec_id}/state
"""
_put_pause = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_PAUSEREC_REQ',
'converter': api2mc.recorderoperator,
},
'ack': {
'msg': 'CMU_CM_PAUSEREC_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_PAUSEREC_NACK',
'converter': mc2api.defaultnack,
}
}
_put_resume = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_RESUMEREC_REQ',
'converter': api2mc.recorderoperator,
},
'ack': {
'msg': 'CMU_CM_RESUMEREC_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_RESUMEREC_NACK',
'converter': mc2api.defaultnack,
}
}
async def put(self, *args, **kw):
params = self.get_argument('params')
reqobj = json.loads(params)
if reqobj['value'] == 1:
await self.handle(self._put_pause, *args)
else:
await self.handle(self._put_resume, *args)
class PlayHandle(GeneralHandle):
"""
PUT /api/v1/vc/confs/{conf_id}/playback
GET /api/v1/vc/confs/{conf_id}/playback
"""
_get = {
'action': 'redis',
'lua': 'v1/lua/getplaystate.lua',
'converter': api2mc.getplaystate,
}
_put = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_STARTPLAY_REQ',
'converter': api2mc.startplay,
},
'ack': {
'msg': 'CMU_CM_STARTPLAY_ACK',
'converter': mc2api.startplayack,
},
'nack': {
'msg': 'CMU_CM_STARTPLAY_NACK',
'converter': mc2api.defaultnack,
}
}
class PlayStateHandle(GeneralHandle):
"""
PUT /api/v1/vc/confs/{conf_id}/playback/state
"""
_put_pause = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_PAUSEPLAY_REQ',
'converter': api2mc.playoperator,
},
'ack': {
'msg': 'CMU_CM_PAUSEPLAY_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_PAUSEPLAY_NACK',
'converter': mc2api.defaultnack,
}
}
_put_resume = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_RESUMEPLAY_REQ',
'converter': api2mc.playoperator,
},
'ack': {
'msg': 'CMU_CM_RESUMEPLAY_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_RESUMEPLAY_NACK',
'converter': mc2api.defaultnack,
}
}
_put_stop = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_STOPPLAY_REQ',
'converter': api2mc.playoperator,
},
'ack': {
'msg': 'CMU_CM_STOPPLAY_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_STOPPLAY_NACK',
'converter': mc2api.defaultnack,
}
}
async def put(self, *args, **kw):
params = self.get_argument('params')
reqobj = json.loads(params)
if reqobj['value'] == 1:
await self.handle(self._put_pause, *args)
elif reqobj['value'] == 2:
await self.handle(self._put_resume, *args)
else:
await self.handle(self._put_stop, *args)
class PlayProgHandle(GeneralHandle):
"""
PUT /api/v1/vc/confs/{conf_id}/playback/current_progress
"""
_put = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_SEEK_REQ',
'converter': api2mc.playprog,
},
'ack': {
'msg': 'CMU_CM_SEEK_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_SEEK_NACK',
'converter': mc2api.defaultnack,
}
}
class ViplistHandle(GeneralHandle):
"""
PUT /api/v1/vc/confs/{conf_id}/viplist
GET /api/v1/vc/confs/{conf_id}/viplist
"""
_get = {
'action': 'redis',
'lua': 'v1/lua/getviplist.lua',
'converter': api2mc.getviplist,
}
_put = {
'action': 'mqrpc',
'mq': CM_MCU_MQ,
'req': {
'msg': 'CM_CMU_SETVIPLIST_REQ',
'converter': api2mc.setviplist,
},
'ack': {
'msg': 'CMU_CM_SETVIPLIST_ACK',
'converter': mc2api.defaultack,
},
'nack': {
'msg': 'CMU_CM_SETVIPLIST_NACK',
'converter': mc2api.defaultnack,
}
}
class ForceBrdHandle(GeneralHandle):
"""
PUT /api/v1/vc/confs/{conf_id}/forcebroadcast
"""
_put = {
'action': 'mqpush',
'mq': CM_MCU_MQ,
'cmd': {
'msg': 'CM_CMU_FORCEBRD_CMD',
'converter': api2mc.forcebroadcast,
},
}
class APIVersionHandle(GeneralHandle):
"""
GET version
"""
async def get(self, *args, **kw):
msg = {
'version': APIVersion,
'success': 1,
}
self.write(msg)
class APILogLevelHandle(GeneralHandle):
"""
GET loglevel
"""
async def get(self, *args, **kw):
reqobj = int(self.path_args[0])
loglvl = (logging.NOTSET, logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR)
if logging.DEBUG <= loglvl[reqobj] <= logging.FATAL:
logger = logging.getLogger('API')
logger.setLevel(loglvl[reqobj])
msg = {
'success': 1,
}
else:
msg = {
'success': 0,
'error_code': 112230
}
self.write(msg)
pre_url = '/api/v1/vc/'
url = [
(pre_url + 'confs', ConfListHandle),
(pre_url + 'confs/([0-9]+)', ConfHandle),
# (pre_url + 'confs/([0-9]+)/state', ConfState),
(pre_url + 'confs/([0-9]+)/cascades', CascadesConfHandle),
(pre_url + 'confs/([0-9]+)/cascades/([0-9\.]+)/mts', CascadesMtHandle),
(pre_url + 'confs/([0-9]+)/mts', MtListHandle),
(pre_url + 'confs/([0-9]+)/silence', ConfSilenceHandle),
(pre_url + 'confs/([0-9]+)/mute', ConfMuteHandle),
(pre_url + 'confs/([0-9]+)/delay', DelayConfHandle),
(pre_url + 'confs/([0-9]+)/monitors', ConfMonitorHandle),
(pre_url + 'confs/([0-9]+)/monitors/([0-9.]+)/([0-9]+)', ConfSigleMonitorHandle),
(pre_url + 'confs/([0-9]+)/monitors_heartbeat', MonitorAliveHandle),
(pre_url + 'confs/([0-9]+)/neediframe/monitors', NeedIFrameHandle),
(pre_url + 'confs/([0-9]+)/safty', ConfSaftyHandle),
(pre_url + 'confs/([0-9]+)/speaker', SpeakerHandle),
(pre_url + 'confs/([0-9]+)/chairman', ChairManHandle),
(pre_url + 'confs/([0-9]+)/upload', UploadMtHandle),
(pre_url + 'confs/([0-9]+)/online_mts', MtsStateHandle),
(pre_url + 'confs/([0-9]+)/inspections', InspectMtHandle),
(pre_url + 'confs/([0-9]+)/inspections/([0-9]+)/([0-9]+)', CancelInspectMtHandle),
(pre_url + 'confs/([0-9]+)/(?:cascades/(?:[0-9]+)/)?mts/([0-9\.]+)', MtHandle),
(pre_url + 'confs/([0-9]+)/mts/([0-9\.]+)/silence', MtSlienceHandle),
(pre_url + 'confs/([0-9]+)/mts/([0-9\.]+)/mute', MtMuteHandle),
(pre_url + 'confs/([0-9]+)/mts/([0-9\.]+)/camera', MtCameraRCHandle),
(pre_url + 'confs/([0-9]+)/mts/([0-9\.]+)/volume', MtVolumHandle),
(pre_url + 'confs/([0-9]+)/vmps', VmpStartHandle),
(pre_url + 'confs/([0-9]+)/vmps/([0-9]+)', VmpHandle),
(pre_url + 'confs/([0-9]+)/mixs', StartMixerHandle),
(pre_url + 'confs/([0-9]+)/mixs/([0-9]+)', MixerHandle),
(pre_url + 'confs/([0-9]+)/mixs/([0-9]+)/members', MixerMembersHandle),
(pre_url + 'confs/([0-9]+)/sms', ShortMsgHandle),
(pre_url + 'confs/([0-9]+)/vad', ConfVadHandle),
(pre_url + 'confs/([0-9]+)/dualstream', SpecDualkSrcHandle),
(pre_url + 'confs/([0-9]+)/poll', ConfPollHandle),
(pre_url + 'confs/([0-9]+)/poll/state', ConfPollStateHandle),
(pre_url + 'hdus', PlatformHduListHandle),
(pre_url + 'confs/([0-9]+)/hdus', ConfHduListHandle),
(pre_url + 'confs/([0-9]+)/hdus/([0-9_]+)', HduHandle),
(pre_url + 'confs/([0-9]+)/mtvmps', MtListVmpsHandle),
(pre_url + 'confs/([0-9]+)/mtvmps/([0-9\.]+)', MtVmpsHandle),
(pre_url + 'confs/([0-9]+)/hduvmps', HduListVmpsHandle),
(pre_url + 'confs/([0-9]+)/hduvmps/([0-9_]+)', HduVmpsHandle),
(pre_url + 'confs/([0-9]+)/recorders', RecordersHandle),
(pre_url + 'confs/([0-9]+)/recorders/([0-9]+)', RecorderInsHandle),
(pre_url + 'confs/([0-9]+)/recorders/([0-9]+)/state', RecorderStateHandle),
(pre_url + 'confs/([0-9]+)/playback', PlayHandle),
(pre_url + 'confs/([0-9]+)/playback/state', PlayStateHandle),
(pre_url + 'confs/([0-9]+)/playback/current_progress', PlayProgHandle),
(pre_url + 'confs/([0-9]+)/viplist', ViplistHandle),
(pre_url + 'confs/([0-9]+)/forcebroadcast', ForceBrdHandle),
(pre_url + 'version', APIVersionHandle),
(pre_url + 'loglevel/([0-9])', APILogLevelHandle),
]
|
github188/dest
|
80-moservice/vcapi/src/v1/vchandle.py
|
vchandle.py
|
py
| 54,755 |
python
|
en
|
code
| 0 |
github-code
|
50
|
23240011506
|
import pandas as pd
import talib as ta
import tushare as ts
from tqdm import tqdm
pd.set_option('display.max_columns', None)
# set token
ts.set_token('303f0dbbabfad0fd3f9465368bdc62fc775bde6711d6b59c2ca10109')
# initialize pro api
pro = ts.pro_api()
def get_transform_data(path):
df = pd.read_csv(path, index_col=0)
df['date'] = pd.to_datetime(df['trade_date'], format='%Y%m%d')
df.set_index('date', inplace=True)
df = df.iloc[::-1]
return df
def append_return(df, start=1, end=10, step=1, max_entry_delay=1):
for i in range(1, max_entry_delay + 1):
df['t{}open'.format(str(i))] = df.open.shift(-i)
for n in range(start, end, step):
df['t{}_ret_on_t{}open'.format(str(n), str(i))] = (df.close.shift(-n) /
df['t{}open'.format(str(i))] - 1) * 100
return df
def calculate_signal(df, window):
closed = df['close'].values
df['ema' + str(window)] = ta.MA(closed, timeperiod=window, matype=1)
# Condition
df['ema_low<=ma' + str(window)] = df.low <= df['ema' + str(window)]
df['ema_close>=ma' + str(window)] = df.close >= df['ema' + str(window)]
# Combined Conditions
df['ema_score_ma' + str(window)] = (df['ema_low<=ma' + str(window)] &
df['ema_close>=ma' + str(window)]).astype(int)
return df
if __name__ == "__main__":
# 中国平安 601318
ts_codes = ['601318.SH']
for ts_code in tqdm(ts_codes):
file_path = f'../week1/solution_daily_price/{ts_code}.csv'
data = get_transform_data(file_path)
# append signal
win = 100
data_w_signal = calculate_signal(data, window=win)
# append returns
data_panel = append_return(data_w_signal)
data_panel.to_csv(f'panel_EMA/PANEL_{ts_code}.csv')
|
HuifengJin/Quant_project
|
solutions/week2/solution_panel.py
|
solution_panel.py
|
py
| 1,862 |
python
|
en
|
code
| 0 |
github-code
|
50
|
70969694234
|
# geeksforgeeks-practice
def gcd(a, b):
if a<b:
small=a
else:
small=b
for x in range(1,small+1):
if ((a%x==0) and (b%x==0)):
g=x
return g
|
ArunimaGupta1/geeksforgeeks-practice
|
GCD.py
|
GCD.py
|
py
| 187 |
python
|
en
|
code
| 0 |
github-code
|
50
|
21540899903
|
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 13 14:46:27 2019
@author: emili
"""
##Importing Keras Libraries
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
##Initializing the CNN
classifier = Sequential()
##Step 1: Convolution
classifier.add(Convolution2D(32,3,3, input_shape = (64, 64 ,3), activation = "relu"))
##Param 1: nb_filter= number of featura detectors and dimensions rowsXcolumns
##Param 2: input_shape=(3,256,256) número de canales y tamaño de las imágenes de input
##Param 3: Activation Function para obtener non-linearity
##Step 2: Max Pooling
classifier.add(MaxPooling2D(pool_size = (2,2)))
##Param 1: Tamaño del pool Map (2X2)
##Al aplicar los dos pasos anteriores conseguimos información de la imágen no solamente sobre sus features
## si no también sobre sus relaciones espaciales.
##Podemos agregar una segunda convolutional layer para mejorar el procesamiento de la imágen
classifier.add(Convolution2D(32,3,3, activation = "relu"))
classifier.add(MaxPooling2D(pool_size = (2,2)))
##Step 3: Flattening
classifier.add(Flatten())
##Usaremos el vector del Flatten para el input de nuestra ANN que tendrá fully connected layers
##ANN son geniales clasificadores para problemas no lineales y la clasificación de imágenes es un problema
## NO LINEAL (afortunadamente)
##Step 4: Full Connection
##Utilizamos Dense para crear una fully connected layer
classifier.add(Dense(output_dim = 128, activation = "relu"))
##Param 1: Número de nodos en nuestra fully connected hidden layer
classifier.add(Dense(output_dim = 1, activation = "sigmoid"))
##Output Layer
## Compiling CNN
classifier.compile(optimizer = "adam", loss = "binary_crossentropy", metrics = ["accuracy"])
##Part 2: Fitting CNN to the images
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
##Esta parte es posible gracias a la manera en que organizamos nuestro folders de manera manual.
training_set = train_datagen.flow_from_directory(
'dataset/training_set',
target_size=(64, 64),
batch_size=32,
class_mode='binary')
test_set = test_datagen.flow_from_directory(
'dataset/test_set',
target_size=(64, 64),
batch_size=32,
class_mode='binary')
classifier.fit_generator(
training_set,
steps_per_epoch=8000,
epochs=25,
validation_data=test_set,
validation_steps=2000)
|
tresstogo/Deep_Learning
|
cnn_M.py
|
cnn_M.py
|
py
| 2,830 |
python
|
es
|
code
| 0 |
github-code
|
50
|
70307591194
|
# Databricks notebook source
# MAGIC %md # Population vs. Median Home Prices
# MAGIC #### *Linear Regression with Single Variable*
# COMMAND ----------
# MAGIC %md ### Load and parse the data
# COMMAND ----------
# Use the Spark CSV datasource with options specifying:
# - First line of file is a header
# - Automatically infer the schema of the data
data = spark.read.csv("/databricks-datasets/samples/population-vs-price/data_geo.csv", header="true", inferSchema="true")
data.cache() # Cache data for faster reuse
data.count()
# COMMAND ----------
display(data)
# COMMAND ----------
data = data.dropna() # drop rows with missing values
data.count()
# COMMAND ----------
from pyspark.sql.functions import col
exprs = [col(column).alias(column.replace(' ', '_')) for column in data.columns]
vdata = data.select(*exprs).selectExpr("2014_Population_estimate as population", "2015_median_sales_price as label")
display(vdata)
# COMMAND ----------
from pyspark.ml import Pipeline
from pyspark.ml.feature import VectorAssembler
stages = []
assembler = VectorAssembler(inputCols=["population"], outputCol="features")
stages += [assembler]
pipeline = Pipeline(stages=stages)
pipelineModel = pipeline.fit(vdata)
dataset = pipelineModel.transform(vdata)
# Keep relevant columns
selectedcols = ["features", "label"]
display(dataset.select(selectedcols))
# COMMAND ----------
# MAGIC %md ## Scatterplot of the data
# COMMAND ----------
import numpy as np
import matplotlib.pyplot as plt
x = dataset.rdd.map(lambda p: (p.features[0])).collect()
y = dataset.rdd.map(lambda p: (p.label)).collect()
plt.style.use('classic')
plt.rcParams['lines.linewidth'] = 0
fig, ax = plt.subplots()
ax.loglog(x,y)
plt.xlim(1.0e5, 1.0e7)
plt.ylim(5.0e1, 1.0e3)
ax.scatter(x, y, c="blue")
display(fig)
# COMMAND ----------
# MAGIC %md ## Linear Regression
# MAGIC
# MAGIC **Goal**
# MAGIC * Predict y = 2015 Median Housing Price
# MAGIC * Using feature x = 2014 Population Estimate
# MAGIC
# MAGIC **References**
# MAGIC * [MLlib LinearRegression user guide](http://spark.apache.org/docs/latest/ml-classification-regression.html#linear-regression)
# MAGIC * [PySpark LinearRegression API](http://spark.apache.org/docs/latest/api/python/pyspark.ml.html#pyspark.ml.regression.LinearRegression)
# COMMAND ----------
# Import LinearRegression class
from pyspark.ml.regression import LinearRegression
# Define LinearRegression algorithm
lr = LinearRegression()
# COMMAND ----------
# Fit 2 models, using different regularization parameters
modelA = lr.fit(dataset, {lr.regParam:0.0})
modelB = lr.fit(dataset, {lr.regParam:100.0})
print(">>>> ModelA intercept: %r, coefficient: %r" % (modelA.intercept, modelA.coefficients[0]))
print(">>>> ModelB intercept: %r, coefficient: %r" % (modelB.intercept, modelB.coefficients[0]))
# COMMAND ----------
# MAGIC %md ## Make predictions
# MAGIC
# MAGIC Calling `transform()` on data adds a new column of predictions.
# COMMAND ----------
# Make predictions
predictionsA = modelA.transform(dataset)
display(predictionsA)
# COMMAND ----------
predictionsB = modelB.transform(dataset)
display(predictionsB)
# COMMAND ----------
# MAGIC %md ## Evaluate the Model
# MAGIC #### Predicted vs. True label
# COMMAND ----------
from pyspark.ml.evaluation import RegressionEvaluator
evaluator = RegressionEvaluator(metricName="rmse")
RMSE = evaluator.evaluate(predictionsA)
print("ModelA: Root Mean Squared Error = " + str(RMSE))
# COMMAND ----------
predictionsB = modelB.transform(dataset)
RMSE = evaluator.evaluate(predictionsB)
print("ModelB: Root Mean Squared Error = " + str(RMSE))
# COMMAND ----------
# MAGIC %md ## Plot residuals versus fitted values
# COMMAND ----------
display(modelA,dataset)
# COMMAND ----------
# MAGIC %md # Linear Regression Plots
# COMMAND ----------
import numpy as np
from pandas import *
pop = dataset.rdd.map(lambda p: (p.features[0])).collect()
price = dataset.rdd.map(lambda p: (p.label)).collect()
predA = predictionsA.select("prediction").rdd.map(lambda r: r[0]).collect()
predB = predictionsB.select("prediction").rdd.map(lambda r: r[0]).collect()
pydf = DataFrame({'pop':pop,'price':price,'predA':predA, 'predB':predB})
# COMMAND ----------
# MAGIC %md ## View the pandas DataFrame (pydf)
# COMMAND ----------
pydf
# COMMAND ----------
# MAGIC %md ## Display the scatterplot and the two regression models
# COMMAND ----------
fig, ax = plt.subplots()
ax.loglog(x,y)
ax.scatter(x, y)
plt.xlim(1.0e5, 1.0e7)
plt.ylim(5.0e1, 1.0e3)
ax.plot(pop, predA, '.r-')
ax.plot(pop, predB, '.g-')
display(fig)
|
AdamPaternostro/Azure-Databricks-Dev-Ops
|
notebooks/MyProject/Pop. vs. Price LR.py
|
Pop. vs. Price LR.py
|
py
| 4,598 |
python
|
en
|
code
| 61 |
github-code
|
50
|
15660309619
|
import json
import shutil
from tempfile import mkdtemp
class ExperimentalEnvironment(object):
UNREL_GRAPH = "unrelated_graph"
UNREL_RULE_GRAPH = "thermometer"
UNREL_RULE_RULE = "temperature_rule"
NOT_FEASIBLE_RULE = "light2_rule"
MAIN_GRAPHS = ["facts.n3"]
MAIN_RULE = ["light3_rule.n3"]
QUERY_RULE = "light_goal.n3"
def __init__(self):
self.output_folder = mkdtemp( dir = "/tmp" )
self.copy_normal_knowledge()
self.create_unrelated_graphs(1000)
self.create_unrelated_rules(1000)
self.create_not_feasible_rules(1000)
self.create_scenario()
self.create_scenario( unrelated_facts = 100 )
self.create_scenario( unrelated_rules = 100 )
self.create_scenario( not_feasible_rules = 100 )
self.create_scenario( unrelated_facts = 1000 )
self.create_scenario( unrelated_rules = 1000 )
self.create_scenario( not_feasible_rules = 1000 )
def _get_new_filename(self, filename):
return self.output_folder + "/" + filename
def _copy_file(self, filename):
shutil.copyfile( filename, self._get_new_filename( filename ) )
def copy_normal_knowledge(self):
self._copy_file( ExperimentalEnvironment.QUERY_RULE )
for normal_graphs in ExperimentalEnvironment.MAIN_GRAPHS:
self._copy_file( normal_graphs )
for normal_rule in ExperimentalEnvironment.MAIN_RULE:
self._copy_file( normal_rule )
def get_template_filepath(self, filename):
return "%s.n3.tpl" % (filename)
def get_output_filepath(self, filename, num):
return "%s/%s_%d.n3" % (self.output_folder, filename, num)
def create_files_from_template(self, template_filename, n):
with open ( self.get_template_filepath(template_filename), "r") as input_file:
content = input_file.read()
for i in range(n):
with open ( self.get_output_filepath(template_filename, i), "w" ) as output_file:
output_file.write( content.replace(r"(?id)", str(i)) )
def create_unrelated_graphs(self, n):
self.create_files_from_template( ExperimentalEnvironment.UNREL_RULE_GRAPH, n )
def create_unrelated_rules(self, n):
self.create_files_from_template( ExperimentalEnvironment.UNREL_RULE_RULE, n )
self.create_files_from_template( ExperimentalEnvironment.UNREL_RULE_GRAPH, n )
def create_not_feasible_rules(self, n):
self.create_files_from_template( ExperimentalEnvironment.NOT_FEASIBLE_RULE, n )
def create_scenario(self,
unrelated_facts = 1,
unrelated_rules = 1,
not_feasible_rules = 1 ):
config = {}
config["query_goal"] = self._get_new_filename( ExperimentalEnvironment.QUERY_RULE )
config["virtual_nodes"] = []
one_node = {} # in one node all the content, nothing special since that part is not being evaluated
one_node["facts"] = []
one_node["rules"] = []
for i in range(unrelated_facts):
one_node["facts"].append ( self.get_output_filepath(ExperimentalEnvironment.UNREL_GRAPH, i) )
one_node["rules"] = []
for i in range(unrelated_rules):
one_node["facts"].append ( self.get_output_filepath(ExperimentalEnvironment.UNREL_RULE_GRAPH, i) )
one_node["rules"].append ( self.get_output_filepath(ExperimentalEnvironment.UNREL_RULE_RULE, i) )
for i in range(not_feasible_rules):
one_node["facts"] = []
one_node["rules"].append ( self.get_output_filepath(ExperimentalEnvironment.NOT_FEASIBLE_RULE, i) )
config["virtual_nodes"].append( one_node )
actuator_node = {}
actuator_node["facts"] = [ self._get_new_filename(el) for el in ExperimentalEnvironment.MAIN_GRAPHS ]
actuator_node["rules"] = [ self._get_new_filename(el) for el in ExperimentalEnvironment.MAIN_RULE ]
config["virtual_nodes"].append( actuator_node )
with open ( "%s/scenario_%d_%d_%d.config" % (self.output_folder, unrelated_facts, unrelated_rules, not_feasible_rules), "w" ) as output_file:
output_file.write( json.dumps(config) )
if __name__ == '__main__':
ExperimentalEnvironment()
|
gomezgoiri/actuationInSpaceThroughRESTdesc
|
ScnImpl/wot2013/evaluation/environment.py
|
environment.py
|
py
| 4,472 |
python
|
en
|
code
| 0 |
github-code
|
50
|
35116740678
|
from collections import namedtuple
def coll_namedtuple():
City = namedtuple('City', 'name country population coordinates')
tokyo = City('Tokyo', 'JP', population=36.99, coordinates=(35.66, 139.69))
print(tokyo)
print(City._fields)
LatLong = namedtuple('LatLong', 'lat long')
delhi_data =('Delhi NCR', 'IN', 21.935, LatLong(28.61, 77.20))
delhi = City._make(delhi_data)
print(delhi._asdict())
def list_of_lists():
a = [['a', 'b']]
b = a * 5
print(b)
a[0][0] = 'c'
print(b)
b[0][1] = 'd'
print('\n')
print(a)
print(b)
if __name__ == '__main__':
# coll_namedtuple()
list_of_lists()
|
alexIGit/practics
|
py_luchano/tuple.py
|
tuple.py
|
py
| 626 |
python
|
en
|
code
| 0 |
github-code
|
50
|
17538298267
|
import pandas as pd
import numpy as np
# pandas分组
# -聚合 计算汇总统计
# -转换 执行一些特定于组的操作
# -过滤 再某些情况下丢弃数据
d = {
'Name': pd.Series(['Tom', 'James', 'Ricky', 'Vin', 'Steve', 'Minsu', 'Jack'
'Lee', 'David', 'Gasper', 'Betina', 'Andres']),
'Year' : pd.Series([2015, 2016, 2013, 2015, 2019, 2016, 2019, 2013, 2015, 2016, 2015]),
'Points': pd.Series([4.23, 3.24, 3.98, 2.56, 3.20, 4.6, 3.8, 3.78, 2.98, 4.80, 4.10])
}
df = pd.DataFrame(d)
print(df, '->df')
dfed = df.groupby('Year').groups
print(dfed)
# 通过循环打印
for year, group in df.groupby('Year'):
print(year)
print(group)
print('-' * 45)
# 获得一个分组细节(拿到2015年的所有数据)
grouped = df.groupby('Year')
print(grouped.get_group(2015))
print('-' * 45)
# 分组聚合
# 聚合函数为每个组返回聚合值.当创建了分组(groupby)对象, 就可以
# 对每个分组数据执行求和, 求标准差等操作
# 聚合每一年的评分
grouped = df.groupby('Year')
print(grouped['Points'].agg(np.mean))
print(grouped['Points'].agg([np.mean, np.max, np.min]))
# pandas数据表关联
# 默认通过相同的class_name进行合并
left = pd.DataFrame({
'student_id': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'student_name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung', 'Billy',
'Brian', 'Bran', 'Bryce', 'Betty'],
'class_id': [1, 1, 1, 2, 2, 2, 3, 3, 3, 4]
})
right = pd.DataFrame({
'class_id': [1, 2, 3, 4],
'class_name': ['ClassA', 'ClassB', 'ClassC', 'ClassD']
})
print('-' * 45)
print(left, '->left\n')
print(right, '->right\n')
# 合并两个DataFrame how参数, right,left右左连接, outer全连接, inner内连接, on确定以那个数据作为连接
# rs = pd.merge(left, right, on='subject_id', how='right')
rs = pd.merge(left, right, how='inner')
print(rs)
# pandas透视表与交叉表
|
yruns/Machine_Learning
|
DataAnalysis/Pandas/groupBy.py
|
groupBy.py
|
py
| 1,931 |
python
|
zh
|
code
| 0 |
github-code
|
50
|
68087887
|
import operator
W= input('Please enter a string ')
d=dict()
def most_frequent(string):
for key in string:
if key not in d:
d[key] = 1
else:
d[key] += 1
return d
print (most_frequent(W))
sorted_d = dict( sorted(d.items(), key=operator.itemgetter(1),reverse=True))
print('Dictionary in descending order by value : ',sorted_d)
|
Divyanaik74/Xyz.py
|
Most_frequent.py
|
Most_frequent.py
|
py
| 373 |
python
|
en
|
code
| 0 |
github-code
|
50
|
71122609754
|
import http.server
import socketserver
PORT = 8000
MAX_OPEN_REQUESTS = 5
class TestHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
print("GET received")
print("Request line:" + self.requestline)
print(" Cmd: " + self.command)
print(" Path: " + self.path)
contents = ""
if self.path == '/':
with open('index.html', 'r') as f:
for i in f:
contents += i
contents = str(contents)
elif self.path == '/blue':
with open('blue.html', 'r') as f:
for i in f:
contents += i
contents = str(contents)
elif self.path == '/pink':
with open('pink.html', 'r') as f:
for i in f:
contents += i
contents = str(contents)
else:
with open('error.html', 'r') as f:
for i in f:
contents += i
contents = str(contents)
self.send_response(200)
self.send_header('Content-Type', 'text/plain')
self.send_header("Content-Length", len(str.encode(contents)))
self.end_headers()
self.wfile.write(str.encode(contents))
return
Handler = TestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("Serving at PORT", PORT)
httpd.serve_forever()
|
baasi/2018-19-PNE-practices
|
P5/webserver.py
|
webserver.py
|
py
| 1,460 |
python
|
en
|
code
| 0 |
github-code
|
50
|
39435831697
|
from PyQt6.QtCore import Qt, QSortFilterProxyModel, QModelIndex
from PyQt6.QtWidgets import QHeaderView
import Fandom
from AbstractModel import AbstractModel
class ItemModel(AbstractModel):
def __init__(self):
self.what = 'ALL'
super().__init__([
AbstractModel.Column('ID', lambda x: x['ID'],
QHeaderView.ResizeMode.ResizeToContents,
Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter),
AbstractModel.Column('Name', lambda x: x['Name'],
QHeaderView.ResizeMode.ResizeToContents,
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter),
AbstractModel.Column('Description', lambda x: x['desc'],
QHeaderView.ResizeMode.ResizeToContents,
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter),
])
self.select()
def select(self):
self.beginResetModel()
self._rows = [x for x in Fandom.all_by_name.values()]
self.endResetModel()
def id(self, idx: int):
return self._rows[idx]['ID']
def typ(self, idx: int):
return self._rows[idx]['Type']
def name(self, idx: int):
return self._rows[idx]['Name']
def value(self, idx: int):
return self._rows[idx]
def get_tooltip(self, index: QModelIndex):
return self._rows[index.row()]['desc']
class ItemProxy(QSortFilterProxyModel):
def __init__(self, parent=None):
super().__init__(parent)
self._type = 'ALL'
self._head = ''
self._vocation = ''
def set_type(self, typ='ALL'):
self._type = typ
self.invalidateFilter()
def set_filter(self, head=''):
self._head = head.lower()
self.invalidateFilter()
def set_vocation(self, vocation: str):
if vocation != self._vocation:
self.beginResetModel()
self._vocation = vocation
self.endResetModel()
def filterAcceptsRow(self, source_row, source_parent):
mod: ItemModel = self.sourceModel()
row = mod.value(source_row)
if self._head and not row['Name'].lower().startswith(self._head):
return False
if self._type != 'ALL' and self._type != row['Type']:
return False
if self._vocation:
usable = row.get('usable', None)
if usable and not usable.get(self._vocation, True):
return False
return True
|
mcondarelli/DDDAedit
|
ItemModel.py
|
ItemModel.py
|
py
| 2,591 |
python
|
en
|
code
| 0 |
github-code
|
50
|
13004426895
|
"""According to the question we need to maintain count of likes and dislikes such that from a set of numbers(Second line of input) if a particluar number exist in set A(Third line of input) then the happiness count will be 1, if it exist in (Forth line of input)B the happiness count will be -1 and if neither of the sets then the happiness count will remain unchanged.
Here the First line of input dictates the number of entries in the COMPARING set(from which we will compare) and A and B (they both wil have same length).To keep the count of happiness we have created a variable count intialised to 0.
"""
x, y = map(int, input().split()) # x is length of storage and y is length of A, B
storage = list()
count = 0
storage = list(map(int, input().strip().split())) # map function converts all string input values into int
A = set(map(int, input().strip().split()))
B = set(map(int, input().strip().split()))
for i in storage:
if i in A: # if A then increment in count value
count = count+1
if i in B: # if B then decrement in count value
count = count-1
print(count)
|
TLE-MEC/Hack-CP-DSA
|
Hackerrank/No Idea!/Solution.py
|
Solution.py
|
py
| 1,246 |
python
|
en
|
code
| 180 |
github-code
|
50
|
13287888443
|
from fastapi import FastAPI, File, UploadFile
import uvicorn
import numpy as np
from io import BytesIO
from PIL import Image
import tensorflow
import cv2
from tensorflow.keras.applications.inception_v3 import preprocess_input
app = FastAPI()
model = tensorflow.keras.models.load_model("gender_model.h5")
@app.get("/ping")
async def ping():
return "Hello, I am alive"
def preprocess_image(data) -> np.ndarray:
img = np.array(Image.open(BytesIO(data)))
gray = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
faces = cascade.detectMultiScale(gray,1.1,7)
buffer = 30
ymin = max(0, faces[0][1]-buffer)
ymax = min(img.shape[1], faces[0][1]+faces[0][3]+buffer)
xmin = max(0, faces[0][0]-buffer)
xmax = min(img.shape[0], faces[0][0]+faces[0][2]+buffer)
face = img[ymin:ymax,xmin:xmax]
face = cv2.resize(face,(224,224))
img_scaled = preprocess_input(face)
reshape = np.reshape(img_scaled,(1,224,224,3))
image = np.vstack([reshape])
return image
@app.post("/predict")
async def predict(file: UploadFile = File(...)):
img = preprocess_image(await file.read())
predictions = model.predict(img)
classes = ['female', 'male']
result = classes[predictions[0].argmax()]
return {
"pred ": result
}
if __name__ == "__main__":
uvicorn.run(app, host="localhost", port=8080)
|
raghuadloid/character_creation
|
gender.py
|
gender.py
|
py
| 1,422 |
python
|
en
|
code
| 0 |
github-code
|
50
|
23447294801
|
import unittest
from city_functions import city_country
from city_functions import city_country_people
class CityFunctionsTestCase(unittest.TestCase):
"""Тесты для city_functions.py"""
def test_city_country(self):
"""Работает ли связка Santiago Chile"""
formatted_name = city_country("santiago", "chile")
self.assertEqual(formatted_name, "Santiago, Chile")
def test_city_country_people(self):
"""Работает ли связка Santiago Chile при обязательном параметре количества людей"""
formatted_name = city_country_people("santiago", "chile")
self.assertEqual(formatted_name, "Santiago, Chile")
def test_city_country_people_full(self):
"""Работает ли связка Santiago Chile 5000000"""
formatted_name = city_country_people("santiago", "chile", 5000000)
self.assertEqual(formatted_name, "Santiago, Chile - population: 5000000")
if __name__ == "__main__":
unittest.main()
|
91nickel/python
|
tests.py/test_cities.py
|
test_cities.py
|
py
| 1,054 |
python
|
en
|
code
| 0 |
github-code
|
50
|
19935741898
|
#Problem 10
def is_prime(n):
if n == 1:
return False
for i in range(2,int(n**(0.5))+1):
if n%i==0:
return False
count = 0
total = 0
n = 1
while n < 2000000:
n += 1
if is_prime(n) != False:
count += 1
total += n
print(total)
|
jasmineseah-17/euler
|
10_Summation_of_primes.py
|
10_Summation_of_primes.py
|
py
| 286 |
python
|
en
|
code
| 0 |
github-code
|
50
|
73324525275
|
import argparse
from attrdict import AttrDict
from deriva.core import ErmrestCatalog, get_credential, DerivaPathError
from deriva.utils.catalog.manage.update_catalog import CatalogUpdater, parse_args
from deriva.core.ermrest_config import tag as chaise_tags
import deriva.core.ermrest_model as em
groups = {
'pbcconsortium-reader': 'https://auth.globus.org/aa5a2f6e-53e8-11e8-b60b-0a7c735d220a',
'pbcconsortium-curator': 'https://auth.globus.org/da80b96c-edab-11e8-80e2-0a7c1eab007a',
'pbcconsortium-writer': 'https://auth.globus.org/6a96ec62-7032-11e8-9132-0a043b872764',
'pbcconsortium-admin': 'https://auth.globus.org/80df6c56-a0e8-11e8-b9dc-0ada61684422'
}
display = {'name_style': {'underline_space': True}}
bulk_upload = {
'asset_mappings': [
{
'asset_type': 'table',
'ext_pattern': '^.*[.](?P<file_ext>json|csv)$',
'file_pattern': '^((?!/assets/).)*/records/(?P<schema>.+?)/(?P<table>.+?)[.]',
'default_columns': ['RID', 'RCB', 'RMB', 'RCT', 'RMT']
},
{
'column_map': {
'md5': '{md5}',
'url': '{URI}',
'dataset': '{dataset_rid}',
'filename': '{file_name}',
'biosample': '{biosample_rid}',
'byte_count': '{file_size}'
},
'dir_pattern': '^.*/DS-(?P<dataset>[0-9A-Z-]+)/EXP-(?P<experiment>[0-9A-Z-]+/tomography)',
'ext_pattern': '.mrc$',
'file_pattern': '.*_(?P<capillary>[0-9]+)_(?P<position>[0-9]+)_pre_rec',
'target_table': ['Beta_Cell', 'XRay_tomography_data'],
'checksum_types': ['md5'],
'hatrac_options': {
'versioned_uris': 'True'
},
'hatrac_templates': {
'hatrac_uri': '/hatrac/commons/data/{dataset_rid}/{biosample_rid}/{file_name}'
},
'record_query_template': '/entity/{target_table}/Dataset={dataset_rid}/Biosample={biosample_rid}/md5={md5}/url={URI_urlencoded}',
'metadata_query_templates': [
'/attribute/D:=Beta_Cell:Dataset/E:=Beta_Cell:Experiment/RID={experiment}/B:=Beta_Cell:Biosample/Capillary_Number={capillary}/Sample_Position={position}/dataset_rid:=D:RID,experiment_rid:=E:RID,biosample_rid:=B:RID'
],
'create_record_before_upload': 'False'
},
{
'column_map': {
'md5': '{md5}',
'url': '{URI}',
'dataset': '{dataset_rid}',
'filename': '{file_name}',
'biosample': '{biosample_rid}',
'byte_count': '{file_size}'
},
'dir_pattern': '^.*/DS-(?P<dataset>[0-9A-Z-]+)/EXP-(?P<experiment>[0-9A-Z-]+/proteomics)',
'ext_pattern': '.csv$',
'file_pattern': '.*_(?P<capillary>[0-9]+)_(?P<position>[0-9]+)_pre_rec',
'target_table': ['Beta_Cell', 'XRay_tomography_data'],
'checksum_types': ['md5'],
'hatrac_options': {
'versioned_uris': 'True'
},
'hatrac_templates': {
'hatrac_uri': '/hatrac/commons/data/{dataset_rid}/{biosample_rid}/{file_name}'
},
'record_query_template': '/entity/{target_table}/Dataset={dataset_rid}/Biosample={biosample_rid}/md5={md5}/url={URI_urlencoded}',
'metadata_query_templates': [
'/attribute/D:=Beta_Cell:Dataset/E:=Beta_Cell:Experiment/RID={experiment}/B:=Beta_Cell:Biosample/Capillary_Number={capillary}/Sample_Position={position}/dataset_rid:=D:RID,experiment_rid:=E:RID,biosample_rid:=B:RID'
],
'create_record_before_upload': 'False'
},
{
'asset_type': 'table',
'ext_pattern': '^.*[.](?P<file_ext>json|csv)$',
'file_pattern': '^((?!/assets/).)*/records/(?P<schema>WWW?)/(?P<table>Page)[.]',
'target_table': ['WWW', 'Page'],
'default_columns': ['RID', 'RCB', 'RMB', 'RCT', 'RMT']
},
{
'column_map': {
'MD5': '{md5}',
'URL': '{URI}',
'Length': '{file_size}',
'Filename': '{file_name}',
'Page_RID': '{table_rid}'
},
'dir_pattern': '^.*/(?P<schema>WWW)/(?P<table>Page)/(?P<key_column>.*)/',
'ext_pattern': '^.*[.](?P<file_ext>.*)$',
'file_pattern': '.*',
'target_table': ['WWW', 'Page_Asset'],
'checksum_types': ['md5'],
'hatrac_options': {
'versioned_uris': True
},
'hatrac_templates': {
'hatrac_uri': '/hatrac/{schema}/{table}/{md5}.{file_name}'
},
'record_query_template': '/entity/{schema}:{table}_Asset/{table}_RID={table_rid}/MD5={md5}/URL={URI_urlencoded}',
'metadata_query_templates': [
'/attribute/D:={schema}:{table}/RID={key_column}/table_rid:=D:RID'
]
}
],
'version_update_url': 'https://github.com/informatics-isi-edu/deriva-qt/releases',
'version_compatibility': [['>=0.4.3', '<1.0.0']]
}
annotations = {
chaise_tags.display: display,
chaise_tags.bulk_upload: bulk_upload,
'tag:isrd.isi.edu,2019:catalog-config': {
'name': 'pbcconsortium',
'groups': {
'admin': 'https://auth.globus.org/80df6c56-a0e8-11e8-b9dc-0ada61684422',
'reader': 'https://auth.globus.org/aa5a2f6e-53e8-11e8-b60b-0a7c735d220a',
'writer': 'https://auth.globus.org/6a96ec62-7032-11e8-9132-0a043b872764',
'curator': 'https://auth.globus.org/da80b96c-edab-11e8-80e2-0a7c1eab007a'
}
},
}
acls = {
'insert': [groups['pbcconsortium-curator'], groups['pbcconsortium-writer']],
'delete': [groups['pbcconsortium-curator']],
'enumerate': ['*'],
'create': [],
'select': [groups['pbcconsortium-writer'], groups['pbcconsortium-reader']],
'owner': [groups['pbcconsortium-admin']],
'write': [],
'update': [groups['pbcconsortium-curator']]
}
def main(catalog, mode, replace=False):
updater = CatalogUpdater(catalog)
updater.update_catalog(mode, annotations, acls, replace=replace)
if __name__ == "__main__":
host = 'pbcconsortium.isrd.isi.edu'
catalog_id = 1
mode, replace, host, catalog_id = parse_args(host, catalog_id, is_catalog=True)
credential = get_credential(host)
catalog = ErmrestCatalog('https', host, catalog_id, credentials=credential)
main(catalog, mode, replace)
|
informatics-isi-edu/betacell-consortium
|
catalog-configs/pbcconsortium.isrd.isi.edu_1.py
|
pbcconsortium.isrd.isi.edu_1.py
|
py
| 6,612 |
python
|
en
|
code
| 2 |
github-code
|
50
|
25533080487
|
import re
import time
def text_del():
srcFiles = open('test.txt', 'r')
begin_flag = False
ip_flag = False
llc_flag = False
l = []
show_list = []
dst = ""
src = ""
protocol = ""
for file_path in srcFiles:
file_path = file_path.rstrip()
if file_path == "Ethernet(":
begin_flag = True
l.append(str(file_path))
if begin_flag:
l.append(str(file_path))
if "dst=" in file_path:
strlist = file_path.split('#')
dst = strlist[1]
#print(dst)
if "src=" in file_path:
strlist = file_path.split('#')
src = strlist[1]
#print(src)
if "data=ARP" in file_path:
protocol = "ARP"
if "data=LLC" in file_path:
protocol = "LLC"
llc_flag = True
if llc_flag:
if "data=STP" in file_path:
protocol = protocol + "-STP"
if "v=4" in file_path:
protocol = "IPv4"
ip_flag = True
if "v=6" in file_path:
protocol = "IPv6"
ip_flag = True
if ip_flag:
if "src=" in file_path:
strlist = file_path.split('#')
src = strlist[1]
if "dst=" in file_path:
strlist = file_path.split('#')
dst = strlist[1]
if "data=UDP" in file_path:
protocol = protocol + "-UDP"
if "data=TCP" in file_path:
protocol = protocol + "-TCP"
if "data=ICMP6" in file_path:
protocol = protocol + "-ICMP6"
if file_path == ") # Ethernet":
l.append(str(file_path))
begin_flag = False
ip_flag = False
llc_flag = False
break
for i in range(len(l)):
print(l[i])
print("dst is ", dst)
print("src is ", src)
print("protocol is", protocol)
if __name__ == '__main__':
#text_del()
s = str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
print(s)
# line = "this hdr-biz 123 model server 456"
# pattern = "model"
# if pattern in line:
# print("matchObj")
|
egoistor/sniff
|
test.py
|
test.py
|
py
| 2,375 |
python
|
en
|
code
| 0 |
github-code
|
50
|
21830967871
|
from flask_wtf import FlaskForm
from wtforms import HiddenField, DecimalField, SubmitField, SelectField, FloatField
from wtforms.validators import DataRequired, NumberRange
from wtforms.widgets.html5 import NumberInput
from wtforms_html5 import AutoAttrMeta
from app.constants import MINIMUM_CONSUMPTION, MAXIMUM_CONSUMPTION, VEHICLE_TYPES, FUEL_TYPES
from app.utils import get_fuel_prices
consumption_validator = NumberRange(min=MINIMUM_CONSUMPTION,
max=MAXIMUM_CONSUMPTION)
class RouteForm(FlaskForm):
class Meta(AutoAttrMeta):
pass
start_lon = HiddenField('start_lon',
validators=[DataRequired()])
start_lat = HiddenField('start_lat',
validators=[DataRequired()])
end_lon = HiddenField('end_lon',
validators=[DataRequired()])
end_lat = HiddenField('end_lat',
validators=[DataRequired()])
vehicle_type = SelectField('Type de véhicule',
default=VEHICLE_TYPES[2],
choices=VEHICLE_TYPES,
validators=[DataRequired()])
fuel_type = SelectField('Type de carburant',
default=FUEL_TYPES[0],
choices=FUEL_TYPES,
validators=[DataRequired()])
fuel_price = DecimalField('Prix du carburant',
widget=NumberInput(),
validators=[DataRequired()])
non_motorway_consumption = DecimalField('Consommation hors autoroute',
widget=NumberInput(),
validators=[DataRequired(),
consumption_validator])
motorway_consumption_130 = DecimalField('Consommation à 130 km/h',
widget=NumberInput(),
validators=[DataRequired(),
consumption_validator])
motorway_consumption_110 = DecimalField('Consommation à 110 km/h',
widget=NumberInput(),
validators=[DataRequired(),
consumption_validator])
submit = SubmitField('Calculer')
|
GustaveCoste/110surautoroute
|
app/forms.py
|
forms.py
|
py
| 2,468 |
python
|
en
|
code
| 0 |
github-code
|
50
|
41390829547
|
import json
import pickle
import nmslib
import requests
import numpy as np
questions_stored = r'D:\Archive\Voibot\qabot\data\question.pickle'
answers_stored = r'D:\Archive\Voibot\qabot\data\answer.pickle'
features_stored = r'D:\Archive\Voibot\qabot\data\feature.npy'
index_stored = r'D:\Archive\Voibot\qabot\data\feature_index'
# 加载问题和答案
with open(questions_stored, 'rb') as question_file:
questions = pickle.load(question_file)
with open(answers_stored, 'rb') as answer_file:
answers = pickle.load(answer_file)
features = np.load(features_stored)
# 加载索引
index = nmslib.init(method='hnsw', space='cosinesimil')
index.loadIndex(index_stored, load_data=True)
def get_ques_vec(question):
url = 'http://10.1.163.22:5000/encode'
headers = {'Content-Type': 'application/json'}
qas = [question]
data = {
'id': 123,
'texts': qas
}
r = requests.post(url=url, headers=headers, data=json.dumps(data))
result = json.loads(r.text)
qvector = result['result']
return qvector
def match(question):
qvector = get_ques_vec(question)
ids, distance = index.knnQuery(qvector, k=3)
return [questions[ids[0]], answers[ids[0]], distance[0]] # 返回最匹配的问题、答案及距离
if __name__ == "__main__":
while True:
question = input('Question: ')
answer = match(question)
print(answer)
# qvector = get_ques_vec(question)
# ids, distance = index.knnQuery(qvector, k=3)
# print(questions[ids[0]], distance[0])
# print(questions[ids[1]], distance[1])
# print(questions[ids[2]], distance[2])
|
yaohsinyu/voibot
|
qabot/search.py
|
search.py
|
py
| 1,650 |
python
|
en
|
code
| 0 |
github-code
|
50
|
37632079064
|
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
p,q=0,0
while q<len(nums):
if nums[q]==0:
q=q+1
else:
nums[p],nums[q]=nums[q],nums[p]
p=p+1
q=q+1
|
amanueldemirew/Competitive-Programming
|
0283-move-zeroes/0283-move-zeroes.py
|
0283-move-zeroes.py
|
py
| 280 |
python
|
en
|
code
| 0 |
github-code
|
50
|
9960952936
|
import logging
from collections import Collection
from math import isclose
from multipledispatch import dispatch
from bn.b_network import BNetwork
from bn.values.value import Value
from datastructs.assignment import Assignment
from inference.approximate.sampling_algorithm import SamplingAlgorithm
from inference.exact.naive_inference import NaiveInference
from inference.exact.variable_elimination import VariableElimination
from inference.query import ProbQuery, UtilQuery
from utils.py_utils import current_time_millis
class InferenceChecks:
exact_threshold = 0.01
sampling_threshold = 0.1
# logger
log = logging.getLogger('PyOpenDial')
def __init__(self):
self._variable_elimination = VariableElimination()
self._sampling_algorithm_1 = SamplingAlgorithm(2000, 200)
self._sampling_algorithm_2 = SamplingAlgorithm(15000, 1500)
self._naive_inference = NaiveInference()
self._timings = dict()
self._numbers = dict()
self._timings[self._variable_elimination] = 0
self._numbers[self._variable_elimination] = 0
self._timings[self._sampling_algorithm_1] = 0
self._numbers[self._sampling_algorithm_1] = 0
self._timings[self._sampling_algorithm_2] = 0
self._numbers[self._sampling_algorithm_2] = 0
self._timings[self._naive_inference] = 0
self._numbers[self._naive_inference] = 0
self._include_naive = False
def include_naive(self, include_naive):
self._include_naive = include_naive
@dispatch(BNetwork, Collection, Assignment)
def check_prob(self, network, query_vars, evidence):
query = ProbQuery(network, query_vars, Assignment())
distrib_1 = self._compute_prob(query, self._variable_elimination)
distrib_2 = self._compute_prob(query, self._sampling_algorithm_1)
try:
self._compare_distributions(distrib_1, distrib_2, 0.1)
except AssertionError as e:
distrib_2 = self._compute_prob(query, self._sampling_algorithm_2)
self.log.debug('resampling for query %s' % (str(ProbQuery(network, query_vars, evidence))))
self._compare_distributions(distrib_1, distrib_2, 0.1)
if self._include_naive:
distrib_3 = self._compute_prob(query, self._naive_inference)
self._compare_distributions(distrib_1, distrib_3, 0.01)
@dispatch(BNetwork, str, str, float)
def check_prob(self, network, query_var, a, expected):
self.check_prob(network, [query_var], Assignment(query_var, a), expected)
@dispatch(BNetwork, str, Value, float)
def check_prob(self, network, query_var, a, expected):
self.check_prob(network, [query_var], Assignment(query_var, a), expected)
@dispatch(BNetwork, Collection, Assignment, float)
def check_prob(self, network, query_vars, a, expected):
query = ProbQuery(network, query_vars, Assignment())
distrib_1 = self._compute_prob(query, self._variable_elimination)
distrib_2 = self._compute_prob(query, self._sampling_algorithm_1)
assert isclose(expected, distrib_1.get_prob(a), abs_tol=InferenceChecks.exact_threshold)
try:
assert isclose(expected, distrib_2.get_prob(a), abs_tol=InferenceChecks.sampling_threshold)
except AssertionError as e:
distrib_2 = self._compute_prob(query, self._sampling_algorithm_2)
assert isclose(expected, distrib_2.get_prob(a), abs_tol=InferenceChecks.sampling_threshold)
if self._include_naive:
distrib_3 = self._compute_prob(query, self._naive_inference)
assert isclose(expected, distrib_3.get_prob(a), abs_tol=InferenceChecks.exact_threshold)
@dispatch(BNetwork, str, float, float)
def check_cdf(self, network, variable, value, expected):
query = ProbQuery(network, [variable], Assignment())
distrib_1 = self._compute_prob(query, self._variable_elimination).get_marginal(variable).to_continuous()
distrib_2 = self._compute_prob(query, self._sampling_algorithm_1).get_marginal(variable).to_continuous()
assert isclose(expected, distrib_1.get_cumulative_prob(value), abs_tol=InferenceChecks.exact_threshold)
try:
assert isclose(expected, distrib_2.get_cumulative_prob(value), abs_tol=InferenceChecks.sampling_threshold)
except AssertionError as e:
distrib_2 = self._compute_prob(query, self._sampling_algorithm_2).get_marginal(variable).to_continuous()
assert isclose(expected, distrib_2.get_cumulative_prob(value), abs_tol=InferenceChecks.sampling_threshold)
if self._include_naive:
distrib_3 = self._compute_prob(query, self._naive_inference).get_marginal(variable).to_continuous()
assert isclose(expected, distrib_3.to_discrete().get_prob(value), abs_tol=InferenceChecks.exact_threshold)
@dispatch(BNetwork, str, str, float)
def check_util(self, network, query_var, a, expected):
self.check_util(network, [query_var], Assignment(query_var, a), expected)
@dispatch(BNetwork, Collection, Assignment, float)
def check_util(self, network, query_vars, a, expected):
query = UtilQuery(network, query_vars, Assignment())
distrib_1 = self._compute_util(query, self._variable_elimination)
distrib_2 = self._compute_util(query, self._sampling_algorithm_1)
assert isclose(expected, distrib_1.get_util(a), abs_tol=InferenceChecks.exact_threshold)
try:
assert isclose(expected, distrib_2.get_util(a), abs_tol=InferenceChecks.sampling_threshold * 5)
except AssertionError as e:
distrib_2 = self._compute_util(query, self._sampling_algorithm_2)
assert isclose(expected, distrib_2.get_util(a), abs_tol=InferenceChecks.sampling_threshold * 5)
if self._include_naive:
distrib_3 = self._compute_util(query, self._naive_inference)
assert isclose(expected, distrib_3.get_util(a), abs_tol=InferenceChecks.exact_threshold)
def _compute_prob(self, query, inference_algorithm):
start_time = current_time_millis()
distrib = inference_algorithm.query_prob(query)
inference_time = current_time_millis() - start_time
self._numbers[inference_algorithm] = self._numbers[inference_algorithm] + 1
self._timings[inference_algorithm] = self._timings[inference_algorithm] + inference_time
return distrib
def _compute_util(self, query, inference_algorithm):
start_time = current_time_millis()
distrib = inference_algorithm.query_util(query)
inference_time = current_time_millis() - start_time
self._numbers[inference_algorithm] = self._numbers[inference_algorithm] + 1
self._timings[inference_algorithm] = self._timings[inference_algorithm] + inference_time
return distrib
def _compare_distributions(self, distrib_1, distrib_2, margin):
rows = distrib_1.get_values()
for row in rows:
assert isclose(distrib_1.get_prob(row), distrib_2.get_prob(row), abs_tol=margin)
def show_performance(self):
if self._include_naive:
print('Average time for naive inference: %f (ms)' % (self._timings[self._naive_inference] / 1000000.0 / self._numbers[self._naive_inference]))
print('Average time for variable elimination: %f (ms)' % (self._timings[self._variable_elimination] / 1000000.0 / self._numbers[self._variable_elimination]))
importance_sampling_time = (self._timings[self._sampling_algorithm_1] + self._timings[self._sampling_algorithm_2]) / 1000000.0 / self._numbers[self._sampling_algorithm_1]
repeats = self._numbers[self._sampling_algorithm_2] * 100. / self._numbers[self._sampling_algorithm_1]
print('Average time for importance sampling: %f (ms) with %f %% of repeats.' % (importance_sampling_time, repeats))
|
KAIST-AILab/PyOpenDial
|
test/common/inference_checks.py
|
inference_checks.py
|
py
| 7,930 |
python
|
en
|
code
| 9 |
github-code
|
50
|
42572707827
|
import math
from typing import Tuple
from PIL import Image
def resize_crop(image: Image, size: Tuple[int, int]) -> Image:
"""Crop the image with a centered rectangle of the specified size"""
img_format = image.format
image = image.copy()
old_size = image.size
left = (old_size[0] - size[0]) / 2
top = (old_size[1] - size[1]) / 2
right = old_size[0] - left
bottom = old_size[1] - top
rect = [int(math.ceil(x)) for x in (left, top, right, bottom)]
left, top, right, bottom = rect
crop = image.crop((left, top, right, bottom))
crop.format = img_format
return crop
def resize_cover(image: Image, size: Tuple[int, int]) -> Image:
"""Resize image by resizing and keeping aspect ratio, then center cropping."""
img_format = image.format
img = image.copy()
img_size = img.size
ratio = max(size[0] / img_size[0], size[1] / img_size[1])
new_size = [int(math.ceil(img_size[0] * ratio)), int(math.ceil(img_size[1] * ratio))]
img = img.resize((new_size[0], new_size[1]), Image.LANCZOS)
img = resize_crop(img, size)
img.format = img_format
return img
|
apockill/portrayt
|
portrayt/renderers/crop_utils.py
|
crop_utils.py
|
py
| 1,134 |
python
|
en
|
code
| 53 |
github-code
|
50
|
71449673754
|
#!/usr/bin/env python3
'''
FSMScorer - A class to assign scores to FSMs based on how well they classify strings through their output.
Classes:
FSMScorer - scores
'''
import logging
import automata
class FSMScorer(object):
'''A class to score FSMs based on their outputs against a reference set of strings.'''
def __init__(self) -> None:
self.reference_dict = dict()
# initialise the cache
self.cache = dict()
@classmethod
def from_reference_dict(cls, rd):
r = cls()
r.reference_dict = rd
return r
@classmethod
def from_function(cls, f, reference_strings):
'''Constructor from a function and reference strings.'''
r = cls()
for s in reference_strings:
r.reference_dict[s] = f(s)
return r
def table_size(self):
'''Returns the number of reference strings.'''
return len(self.reference_dict)
def ref_and_output(self, n):
'''Return the n-th reference string and its output.'''
k = list(self.reference_dict.keys())[n]
return (k, self.reference_dict[k])
def set_output(self, s, out):
'''Set the expected output for string s to out.'''
self.reference_dict[s] = out
# This has modified at least one string/output pair, therefore reset the cache
self.reset()
def reset(self):
self.cache = dict()
def score(self, automaton):
'''Returns the number of correct results.'''
#First, check if the automaton's score is cached
h = str(automaton)
if h in self.cache:
logging.debug("CACHED score" + str(self.cache[h]))
return self.cache[h]
else:
# not cached, compute value, cache it and return it
count = 0
run = automata.MooreMachineRun(automaton)
for w in self.reference_dict.keys():
run.reset()
run.multistep(w)
output = run.output()
logging.debug("For input " + str(w) + " the output is " + str(output))
if output == self.reference_dict[w]:
count += 1
# cache before returning
self.cache[h] = count
logging.debug("Score is " + str(count))
if count == len(self.reference_dict):
logging.info("Maximal score reached.")
return count
# Unit testing code.
import unittest as ut
class TestCSA(ut.TestCase):
def test_creation(self):
f = FSMScorer()
f.reference_dict[()] = []
self.assertEqual(f.table_size(),1)
self.assertEqual(len(f.cache), 0)
a = automata.CanonicalMooreMachine.from_string(
"0 0 1 2\n"
"0 0 1 2\n"
"1 8 1 2")
s = f.score(a)
self.assertEqual(s, 0)
self.assertTrue(str(a) in f.cache)
self.assertFalse("" in f.cache)
def test_from_reference_dict(self):
f = FSMScorer.from_reference_dict({():0, (2,):1})
a = automata.CanonicalMooreMachine.from_string(
"0 0 1 2\n"
"0 0 1 2\n"
"1 8 1 2")
s = f.score(a)
self.assertEqual(f.table_size(), 2)
self.assertEqual(s, 2)
a = automata.CanonicalMooreMachine.from_string(
"0 1 1 2\n"
"0 0 1 2\n"
"1 8 1 2")
s = f.score(a)
self.assertEqual(len(f.cache), 2)
def test_direct_access(self):
f = FSMScorer.from_reference_dict({():0, (2,):1})
p = f.ref_and_output(1)
self.assertEqual(p, ((2,),1))
f.set_output(p[0],2)
_,s = f.ref_and_output(1)
self.assertEqual(s, 2)
def test_from_function(self):
def Kleene_of(repeated, s):
if len(s) == 0:
return True
elif s[0:len(repeated)] == repeated:
return Kleene_of(repeated, s[len(repeated):])
else:
return False
def recognise_ab_star(w):
'''Return 1 if the input is a member of the language (ab)*, else 0.'''
return 1 if Kleene_of((0, 1), w) else 0
f = FSMScorer.from_function(recognise_ab_star,((), (0, 1), (0, 1, 1) ))
a = automata.CanonicalMooreMachine.from_string(
"1 2 1\n"
"0 0 2\n"
"0 2 2")
s = f.score(a)
self.assertEqual(len(f.reference_dict), 3)
self.assertEqual(s, 2)
self.assertEqual(len(f.cache), 1)
self.assertTrue(str(a) in f.cache)
if __name__ == '__main__':
ut.main()
|
tonyzoltai/FSM-Evolution
|
FSMScorer.py
|
FSMScorer.py
|
py
| 4,639 |
python
|
en
|
code
| 0 |
github-code
|
50
|
38260145636
|
#!/usr/bin/env python
import time
import rospy
import RPi.GPIO as GPIO
from system_state.msg import WorkerState
from remote_command.msg import DualshockInputs
STATE_NAME_MAP= {
0: 'CHARGING/INACTIVE',
1: 'MANUAL CONTROL',
2: 'AUTONOMOUS CONTROL'
}
STATE_PINS = {
0: 22, ## Red
1: 18, ## Yellow
2: 17 ## Green
}
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(STATE_PINS.values(), GPIO.OUT, initial=GPIO.LOW)
class WorkerStateMachine():
def __init__(self, state= 0):
self.state = 0
self.pub = None
self.sub = None
self.triangle = None
## Set initial state
self.change_state(state)
def triangle_pressed(self, triangle_state):
return not self.triangle and triangle_state
def display_state(self):
for pin in STATE_PINS.values():
GPIO.output(pin, 0)
GPIO.output(STATE_PINS[self.state], 1)
def change_state(self, new_state):
state_change_msg = ' Lilboi transitioned from state %i (%s) to state %i (%s)'%(self.state, STATE_NAME_MAP[self.state], new_state, STATE_NAME_MAP[new_state])
rospy.loginfo(rospy.get_caller_id() + state_change_msg)
self.state = new_state
self.display_state()
def user_input_transitions(self, data):
## Charging
if self.state == 0:
if self.triangle_pressed(data.triangle): self.change_state(1)
## Manual Control
elif self.state == 1:
if self.triangle_pressed(data.triangle): self.change_state(2)
## Autonomous Control
elif self.state == 2:
if self.triangle_pressed(data.triangle): self.change_state(1)
## Update local values for next iteration
self.triangle = data.triangle
def shutdown(self):
## Return to state 0
self.change_state(0)
self.pub.publish(self.state)
def run_state_machine(self):
## Initialize state machine and publish the current state of this worker
## TODO: Name node based on worker ID
rospy.init_node('lilboi_state_machine', anonymous=True)
self.pub = rospy.Publisher('lilboi_state', WorkerState, queue_size=10)
self.sub = rospy.Subscriber('remote_commands', DualshockInputs, self.user_input_transitions)
## TODO: Charging auto-transitions
rate = rospy.Rate(10)
while not rospy.is_shutdown():
self.pub.publish(self.state)
rate.sleep()
self.shutdown()
if __name__ == '__main__':
try:
n = WorkerStateMachine()
n.run_state_machine()
except rospy.ROSInterruptException:
GPIO.cleanup()
pass
|
grodriguez78/amr_redux
|
src/system_state/src/worker_state_machine.py
|
worker_state_machine.py
|
py
| 2,374 |
python
|
en
|
code
| 0 |
github-code
|
50
|
28569533617
|
from typing import List
# Solution
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
# Initialise an empty set
hashset = set()
for number in nums:
# Duplicate found
if number in hashset:
return True
# add the unique number to hashset
else:
hashset.add(number)
# No duplicates found
return False
|
aakashmanjrekar11/leetcode
|
1. Array and Hashing/217. Contains Duplicate.py
|
217. Contains Duplicate.py
|
py
| 371 |
python
|
en
|
code
| 0 |
github-code
|
50
|
22539325683
|
#Course: CS2302 - Spring 2019
#Author: Solomon Davis
#Lab Number: 4
#Instructor: Olac Fuentes
#Last Modified: March 24, 2019
#Due Date: March 15, 2019
#Description: This code will use b-trees to carry out specific tasks. These
#tasks include commputing the height of the tree,extracting items from a b-tree
#into a sorted list, returning the minimum and maximum value, returning the
#number of nodes at a specific depth, printing the values at a specific depth,
#returning the of full nodes and full trees, and lastly given the depth of a
#specific key in the b-tree.
import time
import matplotlib.pyplot as plt
class BTree(object):
# Constructor
def __init__(self,item=[],child=[],isLeaf=True,max_items=5):
self.item = item
self.child = child
self.isLeaf = isLeaf
if max_items <3: #max_items must be odd and greater or equal to 3
max_items = 3
if max_items%2 == 0: #max_items must be odd and greater or equal to 3
max_items +=1
self.max_items = max_items
def FindChild(T,k):
# Determines value of c, such that k must be in subtree T.child[c], if k is in the BTree
for i in range(len(T.item)):
if k < T.item[i]:
return i
return len(T.item)
def InsertInternal(T,i):
# T cannot be Full
if T.isLeaf:
InsertLeaf(T,i)
else:
k = FindChild(T,i)
if IsFull(T.child[k]):
m, l, r = Split(T.child[k])
T.item.insert(k,m)
T.child[k] = l
T.child.insert(k+1,r)
k = FindChild(T,i)
InsertInternal(T.child[k],i)
def Split(T):
#print('Splitting')
#PrintNode(T)
mid = T.max_items//2
if T.isLeaf:
leftChild = BTree(T.item[:mid])
rightChild = BTree(T.item[mid+1:])
else:
leftChild = BTree(T.item[:mid],T.child[:mid+1],T.isLeaf)
rightChild = BTree(T.item[mid+1:],T.child[mid+1:],T.isLeaf)
return T.item[mid], leftChild, rightChild
def InsertLeaf(T,i):
T.item.append(i)
T.item.sort()
def IsFull(T):
return len(T.item) >= T.max_items
def Insert(T,i):
if not IsFull(T):
InsertInternal(T,i)
else:
m, l, r = Split(T)
T.item =[m]
T.child = [l,r]
T.isLeaf = False
k = FindChild(T,i)
InsertInternal(T.child[k],i)
def height(T):
#Retutns the height of the B-tree
if T.isLeaf:
return 0
return 1 + height(T.child[0])
def Search(T,k):
# Returns node where k is, or None if k is not in the tree
if k in T.item:
return T
if T.isLeaf:
return None
return Search(T.child[FindChild(T,k)],k)
def Print(T):
# Prints items in tree in ascending order
if T.isLeaf:
for t in T.item:
print(t,end=' ')
else:
for i in range(len(T.item)):
Print(T.child[i])
print(T.item[i],end=' ')
Print(T.child[len(T.item)])
def PrintD(T,space):
# Prints items and structure of B-tree
if T.isLeaf:
for i in range(len(T.item)-1,-1,-1):
print(space,T.item[i])
else:
PrintD(T.child[len(T.item)],space+' ')
for i in range(len(T.item)-1,-1,-1):
print(space,T.item[i])
PrintD(T.child[i],space+' ')
def SearchAndPrint(T,k):
node = Search(T,k)
if node is None:
print(k,'not found')
else:
print(k,'found',end=' ')
print('node contents:',node.item)
def Smallest(T):
if T.isLeaf:
return T.item[0]
return Smallest(T.child[0])
def Largest(T):
if T.isLeaf:
return T.item[-1]
return Largest(T.child[len(T.item)])
def SmallestAtDepth(T,d):
#Returns the smallest value at the given depth d
if T.isLeaf: #If at depth d is the Btree is a leaf it returns the item with the smallest value
return T.item[0]
if d==0: #If the depth is 0 the smallest value is then returned from the given values
return T.item[0]
return SmallestAtDepth(T.child[0],d-1) #return the left most child in the Btree until the function is in the correct depth
def LargestAtDepth(T,d):
#Returns the largest value at the given depth d
if T.isLeaf: #If at depth d is the Btree is a leaf it returns the item with the largest value
return T.item[-1]
if d==0: #If the depth is 0 the largest value is then returned from the given values
return T.item[-1]
return LargestAtDepth(T.child[len(T.item)],d-1) #return the right most child in the Btree until the function is in the correct depth
def NumItems(T):
#count = 0
if T.isLeaf:
return len(T.item)
for i in range(len(T.child)):
NumItems(T.child[i])
#count +=1
#print(count)
return NumItems(T.child[i]) + len(T.item)
def FindDepth(T,k):
if k != T.item:
return FindDepth(T.item,k) + 1
if k == T.item:
return 0
#for i in range(len(T.item)-1,-1,-1)
if k>T.item:
return FindDepth(T.item,k) + 1
if k<T.item:
return FindDepth(T.item,k) + 1
def PrintDescending(T):
if T.isLeaf:
for i in range(len(T.item)-1,-1,-1):
print(T.item[i],end=' ')
else:
PrintDescending(T.child[len(T.item)])
for i in range(len(T.item)-1,-1,-1):
print(T.item[i],end=' ')
PrintDescending(T.child[i])
def PrintItemsInNode(T,k):
if T.child.item[i] == k:
return -1
if T.child.item[i] < k:
return PrintItemsInNode(T,k)
return PrintItemsInNode(T,k)
#def Height(T):
# if T.isLeaf:
# return 1
# else:
# for i in range(len(T.item)):
# return 1 + Height(T.child[i])
def PrintAtDepth(T,d):
#Prints all the values at the given depth in the b-tree
if d == 0:
for i in range(len(T.item)):
print(T.item[i],end=' ') #Print the item in the tree
for i in range(len(T.child)): #Loop that traverses through entire the Btree
PrintAtDepth(T.child[i],d-1) #Calls back to the function until the funtion is in the correct depth
def NumberOfNodesAtDepth(T,d):
#Count the number of nodes at a given a depth d
global count
if d == 0:
count +=1 #Count that adds one when there is a value at a depth
for i in range(len(T.child)): #Loop that traverses through entire the Btree
NumberOfNodesAtDepth(T.child[i],d-1) #Calls back to the function until the funtion is in the correct depth
return count
def SortedList(T,L2):
#Takes the values in the b-tree and puts it into a sorted list
if T.isLeaf:
for t in T.item:
L2.append(t) #Appends value from tree to list
else:
for i in range(len(T.item)): #Loop that traverses through entire the Btree
SortedList(T.child[i],L2)
L2.append(T.item[i]) #Appends value from tree to list
SortedList(T.child[len(T.item)],L2)
def SearchDepth(T,k,count):
# Returns Depth where k is, or -1 if k is not in the tree
if k in T.item: #If the value k is equal to the item in the Btree the count is returned
return count
if T.isLeaf: #If the value k is not found in the Btree then -1 is returned
return -1
#count +=1
return SearchDepth(T.child[FindChild(T,k)],k,count+1)
def FullNodes(T):
#Returns the number of full nodes in the b-tree
global nodecount
if T.isLeaf:
if len(T.item) == 3:
nodecount +=1
if len(T.child) == 3:
nodecount +=1
for i in range(len(T.child)): #Loop that traverses through entire the Btree
FullNodes(T.child[i])
return nodecount #Returns the count of full nodes
def FullLeaves(T):
#Returns the number of full leaves in the b-tree
global leafcount
if T.isLeaf:
if len(T.item) == 3: #If the length of the leaf is 3 the count adds 1 to the counter
leafcount +=1
else:
for i in range(len(T.child)): #Loop that traverses through entire the Btree
FullLeaves(T.child[i])
return leafcount #Returns the count of full leaves
L = [30, 50, 10, 20, 60, 70, 100, 40, 90, 80, 110, 120, 1, 11 , 3, 4, 5,105, 115, 200, 2, 45, 6]
T = BTree()
for i in L:
print('Inserting',i)
Insert(T,i)
PrintD(T,'')
Print(T)
print('\n####################################')
PrintD(T,'')
L2 = []
#start_time = time.time()
SortedList(T,L2)
#end_time = time.time()
#running_time = start_time-end_time
#plt.plot(0,running_time,'o',color='k')
print(L2)
count = 0
leafcount = 0
nodecount = 0
#start_time1 = time.time()
print(SearchDepth(T,30,count))
#end_time1 = time.time()
#running_time1 = start_time1-end_time1
#ax.plot(x,y,color='k')
#plt.plot(1,running_time1,'o',color='k')
#start_time2 = time.time()
print(NumberOfNodesAtDepth(T,2))
#end_time2 = time.time()
#running_time2 = start_time2-end_time2
#plt.plot(2,running_time2,'o',color='k')
#start_time3 = time.time()
print(FullLeaves(T))
#end_time3 = time.time()
#running_time3 = start_time3-end_time3
#plt.plot(3,running_time3,'o',color='k')
#start_time4 = time.time()
print(FullNodes(T))
#end_time4 = time.time()
#running_time4 = start_time4-end_time4
#plt.plot(4,running_time4,'o',color='k')
#Print(T)
#SearchAndPrint(T,60)
#SearchAndPrint(T,200)
#SearchAndPrint(T,25)
#SearchAndPrint(T,20)
#start_time5 = time.time()
PrintAtDepth(T,2)
#end_time5 = time.time()
#running_time5 = start_time5-end_time5
#plt.plot(5,running_time5,'o',color='k')
#print(FindDepth(T,60))
#start_time6 = time.time()
print(height(T))
#end_time6 = time.time()
#running_time6 = start_time6-end_time6
#plt.plot(6,running_time6,'o',color='k')
#seconds = range(0,1000)
#print(running_time)
#plt.plot(6,running_time,'o',color='k')
#plt.show()
#start_time7 = time.time()
print(SmallestAtDepth(T,1))
#end_time7 = time.time()
#running_time7 = start_time7-end_time7
#plt.plot(7,running_time7,'o',color='k')
#start_time8 = time.time()
print(LargestAtDepth(T,2))
#end_time8 = time.time()
#running_time8 = start_time8-end_time8
#plt.plot(8,running_time8,'o',color='k')
#PrintDescending(T)
#print(FindDepth(T,1))
#print PrintItemsInNode(T,30)
#plt.show()
|
Solomond10/CS2302
|
LAB4/Lab 4.py
|
Lab 4.py
|
py
| 10,519 |
python
|
en
|
code
| 0 |
github-code
|
50
|
21753251086
|
from bunch import Bunch
import datetime
import numpy as np
model_params = {"alpha_default": 0.3, # default alpha for all items
"alpha_min": 0.1, # minimum possible alpha
"alpha_max": 0.5, # maximum possible alpha
"decay_scale": 0.21, # decay scaling factor
"threshold": -0.8, # activation threshold
"rec_prob_noise_reduction": 0.255, # recall probability noise reduction factor
"intersesh_time_scale": 0.025} # factor to scale down intersession time
# A list of all items, which the user has NOT yet encountered, BUT NEED to be learned
items_new = [item_form]
# A dictionary of all items, which the user HAS encountered, BUT still NEED to be learned
items_seen = {item_form: item_info}
# An ITEM'S FORM is represented simply by a string
item_form_sample = ""
# An ITEM'S INFORMATION is represented by the following values:
item_info_sample = Bunch(cur_alpha=0.0,
encounters=[])
# An ENCOUNTER is represented by the following information:
encounter_sample = Bunch(time=datetime.datetime,
alpha=0.0,
result="")
# Execution DEPENDS on values of arguments
#
# N = len(items seen this session)
# B = 4 = [get current time, assign session start, +, assign session end] // BASIC instructions, always executed by the FUNCTION
# SL // The session LENGTH
# AEL = sum(all encounter lengths) / N // AVERAGE encounter LENGTH (same unit as session length)
# NI // Instructions, when finding NEXT ITEM
# ENC = 1 // Instructions, when ENCOUNTERING an item
# RP = 5 // Instructions, when calculating RECALL PROBABILITY
# NA = 4 | 5 | 8 // Instructions, when calculating NEW ALPHA
# W = 9 + NI + ENC + RP + NA = [get current time, assign current time, // BASIC instructions, ALWAYS executed in the WHILE loop
# if, assign new item, store encounter result,
# store current alpha, create new encounter,
# add new encounter, assign new alpha] +
# NI + ENC + RP + NA
#
# INSTR_COUNT = B + (SL / AEL) * W + [get cur time, store cur time, if, break] =
# =
#
def learn(items_seen, items_new, session_length):
"""
Goes through a single learning session.
Arguments:
items_seen -- a dictionary of items, which the user HAS encountered before, but still hasn't learned
items_new -- a list of items, which the user HASN'T encountered before, but still needs to learn
session_length -- the length of the study session (in seconds)
Returns:
updated lists of new and seen items
"""
# store the session's START time
session_start = datetime.datetime.now()
# store the session's END time
session_end = session_start + datetime.timedelta(seconds=session_length)
# while there is still time in the session
while True:
cur_time = datetime.datetime.now()
if cur_time >= session_end:
break
# get the next item to be presented
cur_item, cur_item_act, items_new = get_next_item(items_seen, items_new, cur_time)
# Encounter the item and store the encounter's result
cur_enc_result = encounter_item(cur_item)
# Store the current item's alpha
cur_item_alpha = items_seen[cur_item].cur_alpha
# Add the current encounter to the item's encounter list
items_seen[cur_item].encounters.append(Bunch(time=cur_time,
alpha=cur_item_alpha,
result=cur_enc_result))
# Adjust the alpha value depending on the result of the current encounter
items_seen[cur_item].cur_alpha = calc_new_alpha(cur_item_alpha, calc_recall_prob(cur_item_act), cur_enc_result)
# TODO: expand ACT(N) functions to get final instruction count
# Execution DEPENDS on values of arguments
#
# N = len(items seen)
# AEC = sum(len(encounters) for each item) / N // Average encounter count
# ACT(AEC) = // Instructions, when calculating an item's activation
# F = N * (3 + ACT(AEC)) // Instructions, in the FOR loop
# = N * ([get cur item, store cur item, store item act] + ACT(AEC))
# B = 5 + F = [declare dictionary, calc future time // BASIC instructions, always executed by the FUNCTION
# store future time, assign min_item,
# declare next_item, assign next_item,
# declare next_item_act, return values] + F
#
# |========================================================================================================================|
# | CONDITIONS | INSTR COUNT | CUR INSTR LIST | TOTAL INSTR COUNT |
# |========================================================================================================================|
# | N == 0 | B + 7 + ACT(0) | [if, if, if, remove, | ... |
# | | | create new enc list, | |
# | | | assign new enc list, | |
# | | | assign next_item_act] | |
# | | | + ACT(0) | |
# |========================================================================================================================|
# | N != 0 & | B + 11 + ACT(0) | [if, min, if, elif, | ... |
# | len(items_new) != 0 & | | >, !=, if, remove, | |
# | min_item.act > threshold | | create new enc list, | |
# | | | assign new enc list, | |
# | | | assign next_item_act] | |
# | | | + ACT(0) | |
# |========================================================================================================================|
# | N != 0 & | B + 7 | [if, min, if, elif, | ... |
# | min_item.act < threshold | | >, !=, if, | |
# | | | assign next_item_act] | |
# |========================================================================================================================|
#
def get_next_item(items_seen, items_new, cur_time):
"""
Finds the next item to be presented based on their activation.
Arguments:
items_seen -- a dictionary of items, which the user HAS encountered before, but still hasn't learned
items_new -- a list of items, which the user HASN'T encountered before, but still needs to learn
cur_time -- the time at which the next item will be presented
Returns:
the next item to be presented, its activation and the possible updated list of new items
"""
# Maps an item to its activation
item_to_act = {}
# Add 15 seconds to the time in order to catch items before they fall below the retrieval threshold
future_time = cur_time + datetime.timedelta(seconds=15)
# Recalculate each SEEN item's activation at future time with their updated alphas
for item in items_seen:
item_to_act[item] = calc_activation(item, items_seen[item].cur_alpha, [enc for enc in items_seen[item].encounters if enc.time < future_time], [], future_time)
# Get the item with the lowest activation
min_item = "" if len(seen_items) == 0 else min(items_seen, key=item_to_act.get)
# Stores the next item to be presented
next_item = ""
# If ALL items are NEW
if min_item == "":
# Select the next NEW item to be presented
next_item = items_new[0]
# If the lowest activation is ABOVE the retrieval threshold
# AND
# There ARE NEW items available
elif item_to_act[next_item] > model_params["threshold"] and len(items_new) != 0:
# select the next new item to be presented
next_item = items_new[0]
# In ALL other cases, the item with the lowest activation is selected
# (regardless of whether it is below the retrieval threshold)
else:
next_item = min_item
# Stores the next item's activation
next_item_act = 0.0
# If the next item is NOT NEW
if next_item in item_to_act:
next_item_act = item_to_act[next_item]
# If the next item IS NEW
else:
# Remove the selected item from the new item list
items_new.remove(next_item)
# Initialize the item in the 'seen' list
items_seen[next_item] = Bunch(cur_alpha=model_params["alpha_default"], encounters=[])
# Calculate the item's activation
next_item_act = calc_activation(next_item, items_seen[next_item].cur_alpha, [], [], future_time)
return next_item, next_item_act, items_new
# Execution DEPENDS on values of arguments
#
# NOTE: WITHOUT caching, the function is recursively called a total of 2 ^ N times
# NOTE: WITH caching, the function is recursively called a total of 1 + N times = base case + N
# NOTE: triang_num = factorial, but using ADDITION
#
# N = len(encounters)
# T = 5 // Instructions, when calculating the TIME DIFFERENCE
# D = 4 | 5 // Instructions, when calculating the DECAY
# A = 1 // Instructions, when APPENDING an encounter's activation to CACHE
# S = 1 // Instructions, when SLICING off previous encounters
#
# B = 2 = [declare activation, return activation] // BASIC instructions, ALWAYS executed by the function
# BC = 4 = B + 2 = B + [if, assign activation] // BASIC instructions, ALWAYS executed when the BASE CASE is reached
# E_1 = 5 = [if, elif, declare sum, log, assign activation] // BASIC instructions, ALWAYS executed in the FIRST ELSE statement
# F = 18|19 = 9 + 5 + 4|5 = [assign enc_idx, assign enc_bunch, // BASIC instructions, ALWAYS executed in the FOR loop
# assign enc_time, declare enc_act,
# assign time_diff, assign decay,
# pow, +, assign sum] + T + D
# I_2 = 2 = [if, assign enc_act] // BASIC instructions, ALWAYS executed in the SECOND IF statement
# E_2 = 2 = [if, S, assign enc_act, A] // BASIC instructions, ALWAYS executed in the SECOND IF statement
#
# |=======================================================================================================================|
# | CONDITIONS | INSTR COUNT | CUR INSTR LIST | TOTAL INSTR COUNT |
# |=======================================================================================================================|
# | N != 0 & | B + 3 | [if, elif, | 5 |
# | last_enc.time > cur_time | | raise error] | |
# |--------------------------|---------------------------------------|----------------------|-----------------------------|
# | else | BC + | [] | ((20|21) * triang_num(N)) + |
# | | triang_num(N) * (F + I_2) + | | 9*N + 4 |
# | | (N * (B + E_1 + S + A)) | | |
# |=======================================================================================================================|
#
def calc_activation(item, cur_alpha, encounters, activations, cur_time):
"""
Calculates the activation for a given item at a given timestamp.
Takes into account all previous encounters of the item through the calculation of decay.
Arguments:
item -- the item whose activation should be calculated
cur_alpha -- the alpha value of the item which should be used in the calculation
encounters -- the list of all of the item's encounters
activations -- the list of activations corresponding to each encounter (used for caching activation values)
cur_time -- the timestamp at which the activation should be calculated
Returns:
the activation of the item at the given timestamp
"""
# Stores the item's activation
activation = 0.0
# If there are NO previous encounters
if len(encounters) == 0:
activation = np.NINF
# ASSUMING that the encounters are sorted according to their timestamps
# If the last encounter happens later than the time of calculation
elif encounters[len(encounters)-1].time > cur_time:
raise ValueError("Encounters must happen BEFORE the time of activation calculation!")
else:
# Stores the sum of time differences
sum = 0.0
# For each encounter
for enc_idx, enc_bunch in enumerate(encounters):
# Store the encounter's time
enc_time = enc_bunch.time
# Stores the item's activation at that encounter
enc_act = 0.0
# If the encounter's activation has ALREADY been calculated
if enc_idx < len(activations):
enc_act = activations[enc_idx]
# If the encounter's activation has NOT been calculated yet
else:
# Calculate the activation of the item at the time of the encounter
enc_act = calc_activation(item, cur_alpha, encounters[:enc_idx], activations, enc_time)
# Add the current encounter's activation to the list
activations.append(enc_act)
# Calculate the time difference between the current time and the previous encounter
# AND convert it to seconds
time_diff = calc_time_diff(cur_time, enc_time)
# calculate the item's decay at the encounter
enc_decay = calc_decay(enc_act, alpha)
# SCALE the difference by the decay and ADD it to the sum
sum = sum + np.power(time_diff, -enc_decay)
# calculate the activation given the sum of scaled time differences
activation = np.log(sum)
return activation
# Execution DEPENDS on values of arguments
#
# B = 2 = [declare decay, return decay] // BASIC instructions, ALWAYS executed by the function
#
# |=========================================================================================|
# | CONDITIONS | INSTR COUNT | CUR INSTR LIST | TOTAL INSTR COUNT |
# |=========================================================================================|
# | is_neg_inf | B + 2 | [if, assign decay] | 4 |
# |-------------------------|------------------|----------------------|---------------------|
# | else | B + 4 | [if, *, +, | 6 |
# | | | assign decay] | |
# |=========================================================================================|
#
def calc_decay(activation, cur_alpha):
"""
Calculate the activation decay of an item given its activation at the time of an encounter and its alpha.
Arguments:
activation -- the activation of the item at the given encounter
cur_alpha -- the current alpha of the item
Returns:
the decay value of the item
"""
decay = 0.0
# if the activation is -infinity (the item hasn't been encountered before)
if np.isneginf(activation):
# the decay is the default alpha value
decay = model_params["alpha_default"]
else:
# calculate the decay
decay = model_params["decay_scale"] * np.exp(activation) + cur_alpha
return decay
# Executes in CONSTANT time
#
# B = 5 = [-, /, exp, +, /] // BASIC instructions, ALWAYS executed by the function
#
def calc_recall_prob(activation):
"""
Calculates an item's probability of recall given its activation.
Arguments:
activation -- the activation of the item
Returns:
the item's probability of recall based on activation
"""
return 1 / (1 + np.exp(((model_params["threshold"] - activation) / model_params["rec_prob_noise_reduction"])))
# Execution DEPENDS on values of arguments
#
# B = 3 = [assign time_diff, calc_total_seconds, return time_diff] // BASIC instructions, ALWAYS executed by the function
#
# |=========================================================================================|
# | CONDITIONS | INSTR COUNT | CUR INSTR LIST | TOTAL INSTR COUNT |
# |=========================================================================================|
# | time_a > time_b | B + 2 | [if, -] | 5 |
# |-------------------------|------------------|----------------------|---------------------|
# | else | B + 2 | [if, -] | 5 |
# |=========================================================================================|
# NOTE: This calculation gets more complicated once sessions come into play
def calc_time_diff(time_a, time_b):
"""
Calculates the difference between two timestamp.
The time difference is represented in total seconds.
Arguments:
time_a -- the first timestamp to be considered
time_b -- the second timestamp to be considered
Returns:
the time difference in seconds
"""
time_diff = (time_a - time_b) if time_a > time_b else (time_b - time_a)
return (time_diff).total_seconds()
# Executes in CONSTANT time
#
# B = 1 = [return result] // BASIC instructions, ALWAYS executed by the function
#
# NOTE: This calculation depends on what the item encounters consist of
def encounter_item(item):
"""
Presents the item to the user and records the outcome of the encounter
Arguments:
item -- the item to be presented
Returns:
'guessed', 'not_guessed' or 'skipped' depending on what the outcome of the encounter was
"""
return "guessed / not_guessed / skipped"
# Execution DEPENDS on values of arguments
#
# B = 2 = [assign new_alpha, return new_alpha] // BASIC instructions, ALWAYS executed by the function
#
# |=========================================================================================|
# | CONDITIONS | INSTR COUNT | CUR INSTR LIST | TOTAL INSTR COUNT |
# |=========================================================================================|
# | "skipped" | B + 2 | [if, elif] | 4 |
# |=========================================================================================|
# | "guessed" & | B + 6 | [if, if, -, /, -, | 8 |
# | > alpha_min | | assign new_alpha] | |
# |-------------------------|------------------|----------------------|---------------------|
# | "guessed" & | B + 2 | [if, if] | 4 |
# | < alpha_min | | | |
# |=========================================================================================|
# | "not_guessed" & | B + 6 | [if, elif, if, /, +, | 8 |
# | < alpha_max | | assign new_alpha] | |
# |-------------------------|------------------|----------------------|---------------------|
# | "not_guessed" & | B + 3 | [if, elif, if] | 5 |
# | > alpha_max | | | |
# |=========================================================================================|
# NOTE: This calculation may get more complicated depending on how the alpha is adjusted
def calc_new_alpha(old_alpha, item_recall_prob, last_enc_result):
"""
Calculates the new alpha value, based on the result of the last encounter with the item and the item's recall_probability
Arguments:
old_alpha -- the item's old alpha value
last_enc_result -- the result of the user's last encounter with the item
item_recall_prob -- the item's recall_probability during the last encounter
Returns:
the item's new alpha value
"""
new_alpha = old_alpha
# If the last encounter was SUCCESSFUL
if last_enc_result == "guessed":
if old_alpha > model_params["alpha_min"]:
new_alpha = new_alpha - 0.05
# If the last encounter was NOT SUCCESSFUL
elif last_enc_result == "not_guessed":
if old_alpha < model_params["alpha_max"]:
new_alpha = new_alpha + 0.05
# NOTE: If the last encounter was SKIPPED, the alpha stays the same
return new_alpha
|
slavov-vili/ba_thesis
|
activation_code/act_alg_semi_pseudo_old.py
|
act_alg_semi_pseudo_old.py
|
py
| 22,650 |
python
|
en
|
code
| 0 |
github-code
|
50
|
5936441245
|
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse,JsonResponse
from django.db import connection
from django.db import models
from .models import Users
from django.contrib import auth
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
import json
@method_decorator(csrf_exempt)
def indexs(request):
users=Users.objects.all()
users=list(users.values())
return JsonResponse(users,safe=False)
@method_decorator(csrf_exempt)
def user_register(request):
if request.method=='GET':
special_user=request.GET.get('user_id',None)
if request.method=='POST':
special_user = request.POST.get('user_id', None) # client로부터 user_id를 받기
Already = "already joined"
NoInput="Not inputed user_id"
if not special_user: # 만약 받은 user_id가 없으면 {'success':False}를 json형태로 반환
response = {'success': False,
'reason':NoInput}
elif Users.objects.filter(user_id=special_user).exists():
response = {'success': False,
'reason':Already}
else: # 만약 유저가 id를 생성했다면 해당 id를 Users라는 모델에 저장하고 {'success':True}를 json형태로 반환
user_name = Users(user_id=special_user)
user_name.save()
response = {'success': True}
return JsonResponse(response, safe=False)
@method_decorator(csrf_exempt)
def user_remove(request): #유저 삭제 함수
special_user=request.POST.get('user_id',None) #query 값으로 user_id를 받아오기
if not special_user: #해당 data가 없으면 {'success':False}를 json 형태로 반환
response={'success':False}
else:
try:
#해당 데이터가 있다면, 해당 데이터를 삭제하고 {'success':True}를 json 형태로 반환
user_name = Users.objects.get(user_id=special_user)
user_name.delete() # 해당 유저의 id를 삭제하는 작업
response = {'success': True}
except Users.DoesNotExist:
response={'success':False}
return JsonResponse(response,safe=False)
# Create your views here.
|
Dongkw324/CodeDokDok_Baekend
|
User_Function/views.py
|
views.py
|
py
| 2,223 |
python
|
ko
|
code
| 0 |
github-code
|
50
|
4197431456
|
def solution(T):
"""
[73,74]
[1, 0]
at index i = 0 have to wait 1 day
at index i = 1 is the end
[73, 74, 75]
[1, 1, 0]
we could find the # of days but subtracting the index of the warmer day - previous colder day
we could process one day by a time in a stack to keep track which has been looked up yet
if we find a warmer day than the top index of the stack, then we find the # days that index has to wait, and we keep popping the stack until it is stack or the day in the stack is warmer that current index
"""
previous_days = []
res = [0] * len(T)
for i in range(len(T)):
while previous_days and T[i] > T[previous_days[-1]]:
colder_day = previous_days.pop()
res[colder_day] = i - colder_day
previous_days.append(i)
return res
|
Prakort/competitive_programming
|
daily-temperatures.py
|
daily-temperatures.py
|
py
| 795 |
python
|
en
|
code
| 0 |
github-code
|
50
|
26563775466
|
from panpipelines.utils.util_functions import *
from panpipelines.scripts.panscript import *
import os
import glob
# TEST
#from panpipelines.scripts import *
#SCRIPT="fmriprep_panscript"
#panscript=eval("{}.{}".format(SCRIPT,SCRIPT))
#labels_dict={"COMM": "ls"}
#pancomm = panscript(labels_dict)
#pancomm.run()
class fmriprep_panscript(panscript):
def __init__(self,labels_dict,name='fmriprep_panscript',params="",command="",execution={}):
super().__init__(self,labels_dict,name=name,params=params,command=command)
self.params = "--participant_label <PARTICIPANT_LABEL>" \
" --output-spaces MNI152NLin6Asym:res-2 MNI152NLin2009cAsym:res-2 fsLR fsaverage anat func"\
" --skip-bids-validation"\
" --mem_mb <BIDSAPP_MEMORY>" \
" --nthreads <BIDSAPP_THREADS>"\
" --fs-license-file <FSLICENSE>"\
" --omp-nthreads <BIDSAPP_THREADS>"\
" -w <OUTPUT_DIR>/fmriwork"
self.command = "singularity run --cleanenv --nv --no-home <FMRIPREP_CONTAINER>"\
" <BIDS_DIR>"\
" <OUTPUT_DIR>/fmrioutput"\
" participant"
def pre_run(self):
print("pre run - setting template flow directory")
TEMPLATEFLOW_HOME=getParams(self.labels_dict,"TEMPLATEFLOW_HOME")
os.environ["TEMPLATEFLOW_HOME"]=TEMPLATEFLOW_HOME
os.environ["SINGULARITYENV_TEMPLATEFLOW_HOME"]=TEMPLATEFLOW_HOME
print("Creating output directory")
output_dir = getParams(self.labels_dict,"OUTPUT_DIR")
if os.path.exists(output_dir):
os.makedirs(output_dir)
def post_run(self):
print("post run")
def get_results(self):
self.results = {}
return self.results
|
MRIresearch/PANpipelines
|
src/panpipelines/scripts/fmriprep_panscript.py
|
fmriprep_panscript.py
|
py
| 1,772 |
python
|
en
|
code
| 0 |
github-code
|
50
|
38297049752
|
from __future__ import print_function
import argparse
import os
from pprint import pprint
import multiprocessing
import numpy as np
import torch
import torch.optim as optim
import torch.backends.cudnn as cudnn
import torch.nn as nn
cudnn.benchmark = True
import datasets
import util
import packing
def train(model, train_loader, val_loader, args):
criterion = nn.CrossEntropyLoss().cuda()
optimizer = torch.optim.SGD(model.parameters(), args.lr,
momentum=args.momentum,
weight_decay=args.weight_decay)
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, args.epochs)
prune_epoch = 0
max_prune_rate = 0.85
max_prune_rate = 0.8
final_prune_epoch = int(0.5*args.epochs)
num_prune_epochs = 10
prune_rates = [max_prune_rate*(1 - (1 - (i / num_prune_epochs))**3)
for i in range(num_prune_epochs)]
prune_rates[-1] = max_prune_rate
prune_epochs = np.linspace(0, final_prune_epoch, num_prune_epochs).astype('i').tolist()
print("Pruning Epochs: {}".format(prune_epochs))
print("Pruning Rates: {}".format(prune_rates))
curr_weights, num_weights = util.num_nonzeros(model)
macs = curr_weights
model.stats = {'train_loss': [], 'test_acc': [], 'test_loss': [],
'weight': [], 'lr': [], 'macs': [], 'efficiency': []}
best_path = args.save_path.split('.pth')[0] + '.best.pth'
best_test_acc = 0
for epoch in range(1, args.epochs + 1):
scheduler.step()
for g in optimizer.param_groups:
lr = g['lr']
break
# prune smallest weights up to a set prune_rate
if epoch in prune_epochs:
util.prune(model, prune_rates[prune_epoch])
curr_weights, num_weights = util.num_nonzeros(model)
packing.pack_model(model, args.gamma)
macs = np.sum([x*y for x, y in model.packed_layer_size])
curr_weights, num_weights = util.num_nonzeros(model)
prune_epoch += 1
if epoch == prune_epochs[-1]:
# disable l1 penalty, as target sparsity is reached
args.l1_penalty = 0
print(' :: [{}]\tLR {:.4f}\tNonzeros ({}/{})'.format(
epoch, lr, curr_weights, num_weights))
train_loss = util.train(train_loader, model, criterion, optimizer, epoch, args)
test_loss, test_acc = util.validate(val_loader, model, criterion, epoch, args)
is_best = test_acc > best_test_acc
best_test_acc = max(test_acc, best_test_acc)
model.stats['lr'].append(lr)
model.stats['macs'].append(macs)
model.stats['weight'].append(curr_weights)
model.stats['efficiency'].append(100.0 * (curr_weights / macs))
model.optimizer = optimizer.state_dict()
model.epoch = epoch
model.cpu()
torch.save(model, args.save_path)
if is_best:
torch.save(model, best_path)
model.cuda()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Basic Training Script')
parser.add_argument('--dataset-root', default='datasets/', help='dataset root folder')
parser.add_argument('--dataset', default='cifar10', help='dataset name')
parser.add_argument('--input-size', type=int, help='spatial width/height of input')
parser.add_argument('--input-channels', default=3, type=int, help='number of input channels')
parser.add_argument('--n-class', type=int, help='number of classes')
parser.add_argument('--aug', default='+', help='data augmentation level (`-`, `+`)')
parser.add_argument('--save-path', required=True, help='path to save model')
parser.add_argument('--batch-size', type=int, default=64,
help='input batch size for training (default: 64)')
parser.add_argument('--epochs', type=int, default=50,
help='number of epochs to train (default: 50)')
parser.add_argument('--sample-ratio', type=float, default=1.,
help='ratio of training data used')
parser.add_argument('--lr', type=float, default=0.1,
help='learning rate (default: 0.1)')
parser.add_argument('--l1-penalty', type=float, default=0.0,
help='l1 penalty (default: 0.0)')
parser.add_argument('--gamma', type=float, default=1.75,
help='column combine gamma parameter (default: 1.75)')
parser.add_argument('--momentum', default=0.9, type=float, help='momentum')
parser.add_argument('--wd', '--weight-decay', default=1e-4, type=float,
help='weight decay (default: 1e-4)', dest='weight_decay')
parser.add_argument('--print-freq', default=100, type=int, help='printing frequency')
parser.add_argument('--seed', type=int, default=1, help='random seed (default: 1)')
parser.add_argument('--load-path', default=None,
help='path to load model - trains new model if None')
parser.add_argument('--reshape-stride', type=int, default=1, help='checkerboard reshape stride')
parser.add_argument('--filters', nargs='+', type=int, help='size of layers in each block')
parser.add_argument('--layers', nargs='+', type=int, help='number of layers for each block')
parser.add_argument('--strides', nargs='+', type=int, help='stride for each block')
parser.add_argument('--groups', nargs='+', type=int, help='number of sparse groups')
parser.add_argument('--layer-type', default='shift', choices=['vgg', 'shift'],
help='type of layer')
parser.add_argument('--dropout', action='store_true')
args = parser.parse_args()
args.cuda = torch.cuda.is_available()
print('Arguments:')
pprint(args.__dict__, width=1)
#set random seed
torch.manual_seed(args.seed)
if args.cuda:
torch.cuda.manual_seed(args.seed)
# load dataset
data = datasets.get_dataset(args.dataset_root, args.dataset, args.batch_size,
args.cuda, args.aug, input_size=args.input_size,
sample_ratio=args.sample_ratio)
train_dataset, train_loader, test_dataset, test_loader = data
# load or create model
if args.load_path == None:
model = util.build_model(args)
else:
model = torch.load(args.load_path)
if args.cuda:
model = model.cuda()
print(model)
print(util.num_nonzeros(model))
print('Target Nonzeros:', util.target_nonzeros(model))
train(model, train_loader, test_loader, args)
|
BradMcDanel/column-combine
|
train.py
|
train.py
|
py
| 6,643 |
python
|
en
|
code
| 26 |
github-code
|
50
|
73677829594
|
from django.shortcuts import render
from rest_framework import generics, status
from django.views.decorators.csrf import csrf_exempt
from rest_framework.views import APIView
from rest_framework.response import Response #send custom response from view
from .serializers import TeamSerializer, CreateTeamSerializer
from .models.team import Team
class TeamsView(generics.ListAPIView): ## CreateAPIView
queryset = Team.objects.all()
serializer_class = TeamSerializer
# @csrf_exempt # only on method views
class CreateTeamView(APIView): ## CreateAPIView
#
serializer_class = CreateTeamSerializer
# define GET POST UPDATE DELETE methods
def post(self, request, format=None):
# sessions needed? lets try
#get access to session ID
if not self.request.session.exists(self.request.session.session_key):
#create session
self.request.session.create()
serializer = self.serializer_class(data=request.data)
message = 'Invalid request'
if (not serializer.is_valid()):
resp_status = status.HTTP_406_NOT_ACCEPTABLE
return Response({'message':message, 'status':resp_status}, status=resp_status) # message = Bad Request
team_name = serializer.data.get('team_name')
queryset = Team.objects.filter(team_name=team_name)
if (queryset.exists()):
resp_status = status.HTTP_409_CONFLICT
message = team_name+" already exists"
return Response({'message':message, 'status':resp_status}, status=resp_status) # message = Conflict
abbr_name = serializer.data.get('abbr_name')
division_ind = serializer.data.get('division_ind')
try:
team = Team(team_name = team_name,
abbr_name = abbr_name,
division_ind = division_ind)
team.save()
message = 'New Team, '+team_name+', added'
team = TeamSerializer(team).data
resp_status = status.HTTP_200_OK
except Exception as exp:
message = exp
team = None
resp_status = status.HTTP_500_INTERNAL_SERVER_ERROR
response_data = {
'message': message ,
'team': team,
'status' : resp_status,
}
return Response(response_data, status=resp_status)
class TeamProfileView(APIView):
"""
Retrieve, update or delete a snippet instance.
"""
def get_object(self, team_name):
try:
print("try: ", team_name)
return Team.objects.get(team_name=team_name)
except Team.DoesNotExist:
print("Team does not exist")
message = "Bad Request: "+team_name + " does not exist"
return Response({'message': message}, status=status.HTTP_404_NOT_FOUND)
def get(self, request, team_name, format=None):
team = self.get_object(team_name)
serializer = PlayerSerializer(team)
return Response(serializer.data)
def put(self, request, team_name, format=None):
team = self.get_object(team_name)
serializer = PlayerSerializer(team, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, team_name, format=None):
team = self.get_object(team_name)
team.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
|
ivanManzalez/FY3
|
teams/views.py
|
views.py
|
py
| 3,366 |
python
|
en
|
code
| 0 |
github-code
|
50
|
34884647599
|
class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
s_list = list(s)
t_list = list(t)
def f(str_list):
stack = []
for item in str_list:
if not stack and item == "#":
continue
else:
if item == "#":
stack.pop()
else:
stack.append(item)
# stack.append(item)
return stack
return f(s_list) == f(t_list)
if __name__ == "__main__":
s = Solution()
S ="ab##"
T ="c#d#"
# S = "ab##"
# T = "c#d#"
s.backspaceCompare(S, T)
|
Dong98-code/leetcode
|
codes/Stack/844.比叫含退格的字符串.py
|
844.比叫含退格的字符串.py
|
py
| 680 |
python
|
en
|
code
| 0 |
github-code
|
50
|
22361452008
|
import discord
from asyncpraw.models import Submission
class Embeds:
@staticmethod
def post(submission: Submission) -> discord.Embed:
embed = discord.Embed()
embed.title = submission.title
embed.set_author(name=submission.author.name, icon_url=submission.author.icon_img)
embed.set_image(url=submission.url)
embed.set_footer(text="👍 {0} | 💬 {1}".format(submission.score, submission.num_comments))
return embed
|
AltF02/fwp-bot
|
src/embeds.py
|
embeds.py
|
py
| 475 |
python
|
en
|
code
| 0 |
github-code
|
50
|
20025439990
|
import datetime
from enum import IntEnum
from typing import List
from pydantic import validator
from .base import BaseScheduleObject
from .lesson import Lesson
__all__ = ['Day', 'Weekday']
class Weekday(IntEnum):
monday = 0
tuesday = 1
wednesday = 2
thursday = 3
friday = 4
saturday = 5
sunday = 6
class Day(BaseScheduleObject):
weekday: Weekday
date: datetime.date
lessons: List[Lesson]
@property
def iso_weekday(self):
return self.weekday + 1
def __iter__(self):
for lesson in self.lessons:
yield lesson
@validator('weekday', pre=True)
def _format_weekday(cls, weekday):
return weekday - 1
@validator('lessons', pre=True, whole=True)
def _filter_lessons_duplicates(cls, lessons: list):
filtered_lessons = []
is_duplicate = False
for next_lesson_index, lesson in enumerate(lessons, start=1):
if is_duplicate:
is_duplicate = False
continue
next_lesson = lessons[next_lesson_index] if next_lesson_index < len(lessons) else None
is_duplicate = (next_lesson and next_lesson['subject'] == lesson['subject']
and lesson['time_start'] == next_lesson['time_start']
and lesson['typeObj']['id'] == next_lesson['typeObj']['id'])
if is_duplicate:
if lesson['auditories'] and next_lesson['auditories']:
lesson['auditories'] += [audit for audit in next_lesson['auditories']
if audit not in lesson['auditories']]
if lesson['teachers'] and next_lesson['teachers']:
lesson['teachers'] += [teacher for teacher in next_lesson['teachers']
if teacher not in lesson['teachers']]
elif next_lesson['teachers']:
lesson['teachers'] = next_lesson['teachers']
if lesson['additional_info'] != next_lesson['additional_info']:
lesson['additional_info'] += '\n' + next_lesson['additional_info']
filtered_lessons.append(lesson)
return filtered_lessons
|
Bobronium/aiospbstu
|
aiospbstu/types/day.py
|
day.py
|
py
| 2,252 |
python
|
en
|
code
| 0 |
github-code
|
50
|
34733859527
|
class Solution(object):
def duplicateZeros(self, arr):
"""
:type arr: List[int]
:rtype: None Do not return anything, modify arr in-place instead.
"""
# Store old length
oldLen = len(arr)
i = 0
while i < oldLen :
# Insert 0 into list
if arr[i] == 0 :
arr.insert(i+1 , 0)
i += 1
i += 1
# Snip arr to old length
arr[:] = arr[:oldLen]
|
nabbott98/LeetCode
|
duplicate-zeros/duplicate-zeros.py
|
duplicate-zeros.py
|
py
| 492 |
python
|
en
|
code
| 0 |
github-code
|
50
|
31069762113
|
#!/bin/python
import math
import os
import random
import re
import sys
'''
Given a set of distinct integers, print the size of a maximal subset of S where the sum of any 2 numbers in S' is not evenly divisible by K.
For example, the array [19,10,12,10,24,25,22] and k=4. One of the arrays that can be created is [10,12,25]. Another is [19,22,24];
After testing all permutations, the maximum length solution array has 3 elements.
'''
# Complete the nonDivisibleSubset function below.
def nonDivisibleSubset(k, S):
r = [0] * k
for value in S:
r[value%k] += 1
result = 0
for a in range(1, (k+1)//2):
result += max(r[a], r[k-a]) # single them out
if k % 2 == 0 and r[k//2]: # odd number of the median, count one
result += 1
if r[0]: #
result += 1
return result
S = [19,10,12,10,24,25,22]
k = 4
r = nonDivisibleSubset(k, S)
print (r)
|
haroldmei/GeneralProgramming
|
interview/nonDivisibleSubset.py
|
nonDivisibleSubset.py
|
py
| 932 |
python
|
en
|
code
| 2 |
github-code
|
50
|
7619208294
|
"""
FludServer.py (c) 2003-2006 Alen Peacock. This program is distributed under
the terms of the GNU General Public License (the GPL), version 3.
flud server operations
"""
import threading, binascii, time, os, stat, httplib, gc, re, sys, logging, sets
from twisted.web import server, resource, client
from twisted.web.resource import Resource
from twisted.internet import reactor, threads, defer
from twisted.web import http
from twisted.python import threadable, failure
from flud.FludCrypto import FludRSA
import flud.FludkRouting
from ServerPrimitives import *
from ServerDHTPrimitives import *
from LocalPrimitives import *
from FludCommUtil import *
threadable.init()
class FludServer(threading.Thread):
"""
This class runs the webserver, responding to all requests.
"""
def __init__(self, node, port):
threading.Thread.__init__(self)
self.port = port
self.node = node
self.clientport = node.config.clientport
self.logger = node.logger
self.root = ROOT(self)
self.root.putChild('ID', ID(self)) # GET (node identity)
self.root.putChild('file', FILE(self)) # POST, GET, and DELETE (files)
self.root.putChild('hash', HASH(self)) # GET (verify op)
self.root.putChild('proxy', PROXY(self)) # currently noop
self.root.putChild('nodes', NODES(self))
self.root.putChild('meta', META(self))
self.site = server.Site(self.root)
reactor.listenTCP(self.port, self.site)
reactor.listenTCP(self.clientport, LocalFactory(node),
interface="127.0.0.1")
#print "FludServer will listen on port %d, local client on %d"\
# % (self.port, self.clientport)
self.logger.log(logging.INFO,\
"FludServer will listen on port %d, local client on %d"
% (self.port, self.clientport))
def run(self):
self.logger.log(logging.INFO, "FludServer starting")
return reactor.run(installSignalHandlers=0)
def stop(self):
self.logger.log(logging.INFO, "FludServer stopping")
reactor.stop()
|
alenpeacock/flud
|
flud/protocol/FludServer.py
|
FludServer.py
|
py
| 2,131 |
python
|
en
|
code
| 12 |
github-code
|
50
|
21542368532
|
from os import P_WAIT
import openpyxl
import random
import docx
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.shared import Pt, RGBColor
wb = openpyxl.load_workbook('工资统计.xlsx')
sheet = wb['工作量汇总']
lst = []
for index, values in enumerate(sheet.rows, 1):
t = list(map(lambda x: x.value, values))
lst.append(t)
doc = docx.Document()
p = doc.add_paragraph('工资表')
p.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
p.runs[0].font.size = Pt(30)
p.runs[0].font.bold = True
table = doc.add_table(rows=13, cols=6, style='Table Grid')
for i in range(13):
for j in range(6):
value = lst[i][j]
if type(value) == int:
value = str(value)
elif type(value) == float:
value = '{:.2f}'.format(value)
cell = table.cell(i, j)
cell.text = value
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
color = (random.randint(0, 255)for i in range(3))
cell.paragraphs[0].runs[0].font.color.rgb = RGBColor(*color)
doc.save('table.docx')
|
hurttttr/MyPythonCode
|
文件操作/2906-制作word表格.py
|
2906-制作word表格.py
|
py
| 1,057 |
python
|
en
|
code
| 3 |
github-code
|
50
|
26082749703
|
def get_loop_size(public_key: int) -> int:
initial_subject_number = 7
divider = 20201227
value = 1
loop = 0
while value != public_key:
value *= initial_subject_number
value %= divider
loop += 1
return loop
def calculate_encryption_key(card_public_key: int, door_public_key: int) -> int:
card_loop_size = get_loop_size(card_public_key)
divider = 20201227
value = 1
for _ in range(0, card_loop_size):
value *= door_public_key
value %= divider
return value
if __name__ == '__main__':
print(calculate_encryption_key(2448427, 6929599))
|
tosoba/Grind
|
advent_of_code_2020/d25_encryption_key.py
|
d25_encryption_key.py
|
py
| 623 |
python
|
en
|
code
| 0 |
github-code
|
50
|
1812305371
|
import functools
from typing import Tuple
import chex
import jax
import jax.numpy as jnp
from jumanji import specs
from jumanji.env import Environment
from jumanji.types import TimeStep, restart, termination, transition
from matrax.types import Observation, State
class MatrixGame(Environment[State]):
"""JAX implementation of the 2-player matrix game environment:
https://github.com/uoe-agents/matrix-games
A matrix game is a two-player game where each player has a set of actions and a payoff matrix.
The payoff matrix is a 2D array where the rows correspond to the actions of player 1 and the
columns correspond to the actions of player 2. The entry at row i and column j for player 1 is
the reward given to player 1 when playing action i and player 2 plays action j. Similarly, the
entry at row i and column j for player 2 is the reward given to player 2 when playing action j
and player 1 plays action i.
```python
from matrax import MatrixGame
payoff_matrix = jnp.array([[1, -1], [-1, 1]])
env = MatrixGame(payoff_matrix)
key = jax.random.PRNGKey(0)
state, timestep = jax.jit(env.reset)(key)
action = env.action_spec().generate_value()
state, timestep = jax.jit(env.step)(state, action)
```
"""
def __init__(
self,
payoff_matrix: chex.Array,
keep_state: bool = True,
time_limit: int = 500,
):
"""Instantiates a `MatrixGame` environment.
Args:
payoff_matrix: a 2D array of shape (num_agents, num_agents) containing the payoff
matrix of the game.
keep_state: whether to keep state by giving agents the actions of all players in
the previous round as observations. Defaults to True.
time_limit: the maximum step limit allowed within the environment.
Defaults to 500.
"""
self.payoff_matrix = payoff_matrix
self.keep_state = keep_state
self.num_agents = self.payoff_matrix.shape[0]
self.num_actions = self.payoff_matrix.shape[1]
self.time_limit = time_limit
def __repr__(self) -> str:
return f"MatrixGame(\n" f"\tpayoff_matrix={self.payoff_matrix!r},\n" ")"
def reset(self, key: chex.PRNGKey) -> Tuple[State, TimeStep[Observation]]:
"""Resets the environment.
Args:
key: random key used to reset the environment since it is stochastic.
Returns:
state: State object corresponding to the new state of the environment.
timestep: TimeStep object corresponding the first timestep returned by the environment.
"""
# create environment state
state = State(
step_count=jnp.array(0, int),
key=key,
)
dummy_actions = jnp.ones((self.num_agents,), int) * -1
# collect first observations and create timestep
agent_obs = jax.vmap(
functools.partial(self._make_agent_observation, dummy_actions)
)(jnp.arange(self.num_agents))
observation = Observation(
agent_obs=agent_obs,
step_count=state.step_count,
)
timestep = restart(observation=observation)
return state, timestep
def step(
self,
state: State,
actions: chex.Array,
) -> Tuple[State, TimeStep[Observation]]:
"""Perform an environment step.
Args:
state: State object containing the dynamics of the environment.
actions: Array containing actions of each agent.
Returns:
state: State object corresponding to the next state of the environment.
timestep: TimeStep object corresponding the timestep returned by the environment.
"""
def compute_reward(
actions: chex.Array, payoff_matrix_per_agent: chex.Array
) -> chex.Array:
reward_idx = tuple(actions)
return payoff_matrix_per_agent[reward_idx]
rewards = jax.vmap(functools.partial(compute_reward, actions))(
self.payoff_matrix
)
# construct timestep and check environment termination
steps = state.step_count + 1
done = steps >= self.time_limit
# compute next observation
agent_obs = jax.vmap(functools.partial(self._make_agent_observation, actions))(
jnp.arange(self.num_agents)
)
next_observation = Observation(
agent_obs=agent_obs,
step_count=steps,
)
timestep = jax.lax.cond(
done,
termination,
transition,
rewards,
next_observation,
)
# create environment state
next_state = State(
step_count=steps,
key=state.key,
)
return next_state, timestep
def _make_agent_observation(
self,
actions: chex.Array,
agent_id: int,
) -> chex.Array:
return jax.lax.cond(
self.keep_state,
lambda: actions,
lambda: jnp.zeros(self.num_agents, int),
)
def observation_spec(self) -> specs.Spec[Observation]:
"""Specification of the observation of the MatrixGame environment.
Returns:
Spec for the `Observation`, consisting of the fields:
- agent_obs: BoundedArray (int32) of shape (num_agents, num_agents).
- step_count: BoundedArray (int32) of shape ().
"""
obs_shape = (self.num_agents, self.num_agents)
low = jnp.zeros(obs_shape)
high = jnp.ones(obs_shape) * self.num_actions
agent_obs = specs.BoundedArray(obs_shape, jnp.int32, low, high, "agent_obs")
step_count = specs.BoundedArray((), jnp.int32, 0, self.time_limit, "step_count")
return specs.Spec(
Observation,
"ObservationSpec",
agent_obs=agent_obs,
step_count=step_count,
)
def action_spec(self) -> specs.MultiDiscreteArray:
"""Returns the action spec.
Since this is a multi-agent environment, the environment expects an array of actions.
This array is of shape (num_agents,).
"""
return specs.MultiDiscreteArray(
num_values=jnp.array([self.num_actions] * self.num_agents, jnp.int32),
name="action",
)
|
instadeepai/matrax
|
matrax/env.py
|
env.py
|
py
| 6,417 |
python
|
en
|
code
| 5 |
github-code
|
50
|
17264620320
|
'''
Created on 27 Dec 2016
@author: af
'''
'''
Created on 22 Apr 2016
@author: af
'''
import pdb
import numpy as np
import sys
from os import path
import scipy as sp
import theano
import theano.tensor as T
import lasagne
from lasagne.regularization import regularize_layer_params_weighted, l2, l1
from lasagne.regularization import regularize_layer_params
import theano.sparse as S
from lasagne.layers import DenseLayer, DropoutLayer
import logging
import json
import codecs
import pickle
import gzip
from collections import OrderedDict
from _collections import defaultdict
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO)
'''
These sparse classes are copied from https://github.com/Lasagne/Lasagne/pull/596/commits
'''
class SparseInputDenseLayer(DenseLayer):
def get_output_for(self, input, **kwargs):
if not isinstance(input, (S.SparseVariable, S.SparseConstant,
S.sharedvar.SparseTensorSharedVariable)):
raise ValueError("Input for this layer must be sparse")
activation = S.structured_dot(input, self.W)
if self.b is not None:
activation = activation + self.b.dimshuffle('x', 0)
return self.nonlinearity(activation)
class SparseInputDropoutLayer(DropoutLayer):
def get_output_for(self, input, deterministic=False, **kwargs):
if not isinstance(input, (S.SparseVariable, S.SparseConstant,
S.sharedvar.SparseTensorSharedVariable)):
raise ValueError("Input for this layer must be sparse")
if deterministic or self.p == 0:
return input
else:
# Using Theano constant to prevent upcasting
one = T.constant(1, name='one')
retain_prob = one - self.p
if self.rescale:
input = S.mul(input, one/retain_prob)
input_shape = self.input_shape
if any(s is None for s in input_shape):
input_shape = input.shape
return input * self._srng.binomial(input_shape, p=retain_prob,
dtype=input.dtype)
#copied from a tutorial that I don't rememmber!
# ############################# Batch iterator ###############################
# This is just a simple helper function iterating over training data in
# mini-batches of a particular size, optionally in random order. It assumes
# data is available as numpy arrays. For big datasets, you could load numpy
# arrays as memory-mapped files (np.load(..., mmap_mode='r')), or write your
# own custom data iteration function. For small datasets, you can also copy
# them to GPU at once for slightly improved performance. This would involve
# several changes in the main program, though, and is not demonstrated here.
def iterate_minibatches(inputs, targets, batchsize, shuffle=False):
assert inputs.shape[0] == targets.shape[0]
if shuffle:
indices = np.arange(inputs.shape[0])
np.random.shuffle(indices)
for start_idx in range(0, inputs.shape[0] - batchsize + 1, batchsize):
if shuffle:
excerpt = indices[start_idx:start_idx + batchsize]
else:
excerpt = slice(start_idx, start_idx + batchsize)
yield inputs[excerpt], targets[excerpt]
class MLP():
def __init__(self,
n_epochs=10,
batch_size=1000,
init_parameters=None,
complete_prob=False,
add_hidden=True,
regul_coefs=[5e-5, 5e-5],
save_results=False,
hidden_layer_size=None,
drop_out=False,
drop_out_coefs=[0.5, 0.5],
early_stopping_max_down=100000,
loss_name='log',
nonlinearity='rectify'):
self.n_epochs = n_epochs
self.batch_size = batch_size
self.init_parameters = init_parameters
self.complete_prob = complete_prob
self.add_hidden = add_hidden
self.regul_coefs = regul_coefs
self.save_results = save_results
self.hidden_layer_size = hidden_layer_size
self.drop_out = drop_out
self.drop_out_coefs = drop_out_coefs
self.early_stopping_max_down = early_stopping_max_down
self.loss_name = loss_name
self.nonlinearity = 'rectify'
def fit(self, X_train, Y_train, X_dev, Y_dev):
logging.info('building the network...' + ' hidden:' + str(self.add_hidden))
in_size = X_train.shape[1]
drop_out_hid, drop_out_in = self.drop_out_coefs
if self.complete_prob:
out_size = Y_train.shape[1]
else:
out_size = len(set(Y_train.tolist()))
logging.info('output size is %d' %out_size)
if self.hidden_layer_size:
pass
else:
self.hidden_layer_size = min(5 * out_size, int(in_size / 20))
logging.info('input layer size: %d, hidden layer size: %d, output layer size: %d' %(X_train.shape[1], self.hidden_layer_size, out_size))
# Prepare Theano variables for inputs and targets
if not sp.sparse.issparse(X_train):
logging.info('input matrix is not sparse!')
self.X_sym = T.matrix()
else:
self.X_sym = S.csr_matrix(name='inputs', dtype='float32')
if self.complete_prob:
self.y_sym = T.matrix()
else:
self.y_sym = T.ivector()
l_in = lasagne.layers.InputLayer(shape=(None, in_size),
input_var=self.X_sym)
if self.nonlinearity == 'rectify':
nonlinearity = lasagne.nonlinearities.rectify
elif self.nonlinearity == 'sigmoid':
nonlinearity = lasagne.nonlinearities.sigmoid
elif self.nonlinearity == 'tanh':
nonlinearity = lasagne.nonlinearities.tanh
else:
nonlinearity = lasagne.nonlinearities.rectify
if self.drop_out:
l_in = lasagne.layers.dropout(l_in, p=drop_out_in)
if self.add_hidden:
if not sp.sparse.issparse(X_train):
l_hid1 = lasagne.layers.DenseLayer(
l_in, num_units=self.hidden_layer_size,
nonlinearity=nonlinearity,
W=lasagne.init.GlorotUniform())
else:
l_hid1 = SparseInputDenseLayer(
l_in, num_units=self.hidden_layer_size,
nonlinearity=nonlinearity,
W=lasagne.init.GlorotUniform())
if self.drop_out:
self.l_hid1 = lasagne.layers.dropout(l_hid1, drop_out_hid)
self.l_out = lasagne.layers.DenseLayer(
l_hid1, num_units=out_size,
nonlinearity=lasagne.nonlinearities.softmax)
else:
if not sp.sparse.issparse(X_train):
self.l_out = lasagne.layers.DenseLayer(
l_in, num_units=out_size,
nonlinearity=lasagne.nonlinearities.softmax)
if self.drop_out:
l_hid1 = lasagne.layers.dropout(l_hid1, drop_out_hid)
else:
self.l_out = SparseInputDenseLayer(
l_in, num_units=out_size,
nonlinearity=lasagne.nonlinearities.softmax)
if self.drop_out:
l_hid1 = SparseInputDropoutLayer(l_hid1, drop_out_hid)
if self.add_hidden:
self.embedding = lasagne.layers.get_output(l_hid1, self.X_sym, deterministic=True)
self.f_get_embeddings = theano.function([self.X_sym], self.embedding)
self.output = lasagne.layers.get_output(self.l_out, self.X_sym, deterministic=False)
self.pred = self.output.argmax(-1)
self.eval_output = lasagne.layers.get_output(self.l_out, self.X_sym, deterministic=True)
self.eval_pred = self.eval_output.argmax(-1)
eval_loss = lasagne.objectives.categorical_crossentropy(self.eval_output, self.y_sym)
eval_loss = eval_loss.mean()
if self.loss_name == 'log':
loss = lasagne.objectives.categorical_crossentropy(self.output, self.y_sym)
elif self.loss_name == 'hinge':
loss = lasagne.objectives.multiclass_hinge_loss(self.output, self.y_sym)
loss = loss.mean()
l1_share_out = 0.5
l1_share_hid = 0.5
regul_coef_out, regul_coef_hid = self.regul_coefs
logging.info('regul coefficient for output and hidden lasagne_layers are ' + str(self.regul_coefs))
l1_penalty = lasagne.regularization.regularize_layer_params(self.l_out, l1) * regul_coef_out * l1_share_out
l2_penalty = lasagne.regularization.regularize_layer_params(self.l_out, l2) * regul_coef_out * (1-l1_share_out)
if self.add_hidden:
l1_penalty += lasagne.regularization.regularize_layer_params(l_hid1, l1) * regul_coef_hid * l1_share_hid
l2_penalty += lasagne.regularization.regularize_layer_params(l_hid1, l2) * regul_coef_hid * (1-l1_share_hid)
loss = loss + l1_penalty + l2_penalty
eval_loss = eval_loss + l1_penalty + l2_penalty
if self.complete_prob:
self.y_sym_one_hot = self.y_sym.argmax(-1)
self.acc = T.mean(T.eq(self.pred, self.y_sym_one_hot))
self.eval_ac = T.mean(T.eq(self.eval_pred, self.y_sym_one_hot))
else:
self.acc = T.mean(T.eq(self.pred, self.y_sym))
self.eval_acc = T.mean(T.eq(self.eval_pred, self.y_sym))
if self.init_parameters:
lasagne.layers.set_all_param_values(self.l_out, self.init_parameters)
parameters = lasagne.layers.get_all_params(self.l_out, trainable=True)
#print(params)
#updates = lasagne.updates.nesterov_momentum(loss, parameters, learning_rate=0.01, momentum=0.9)
#updates = lasagne.updates.sgd(loss, parameters, learning_rate=0.01)
#updates = lasagne.updates.adagrad(loss, parameters, learning_rate=0.1, epsilon=1e-6)
#updates = lasagne.updates.adadelta(loss, parameters, learning_rate=0.1, rho=0.95, epsilon=1e-6)
updates = lasagne.updates.adam(loss, parameters, learning_rate=0.002, beta1=0.9, beta2=0.999, epsilon=1e-8)
self.f_train = theano.function([self.X_sym, self.y_sym], [loss, self.acc], updates=updates)
self.f_val = theano.function([self.X_sym, self.y_sym], [eval_loss, self.eval_acc])
self.f_predict = theano.function([self.X_sym], self.eval_pred)
self.f_predict_proba = theano.function([self.X_sym], self.eval_output)
X_train = X_train.astype('float32')
X_dev = X_dev.astype('float32')
if self.complete_prob:
Y_train = Y_train.astype('float32')
Y_dev = Y_dev.astype('float32')
else:
Y_train = Y_train.astype('int32')
Y_dev = Y_dev.astype('int32')
logging.info('training (n_epochs, batch_size) = (' + str(self.n_epochs) + ', ' + str(self.batch_size) + ')' )
best_params = None
best_val_loss = sys.maxint
best_val_acc = 0.0
n_validation_down = 0
for n in xrange(self.n_epochs):
for batch in iterate_minibatches(X_train, Y_train, self.batch_size, shuffle=True):
x_batch, y_batch = batch
l_train, acc_train = self.f_train(x_batch, y_batch)
l_val, acc_val = self.f_val(X_dev, Y_dev)
if acc_val > best_val_acc:
best_val_loss = l_val
best_val_acc = acc_val
best_params = lasagne.layers.get_all_param_values(self.l_out)
n_validation_down = 0
else:
#early stopping
n_validation_down += 1
logging.info('epoch ' + str(n) + ' ,train_loss ' + str(l_train) + ' ,acc ' + str(acc_train) + ' ,val_loss ' + str(l_val) + ' ,acc ' + str(acc_val) + ',best_val_acc ' + str(best_val_acc))
if n_validation_down > self.early_stopping_max_down:
logging.info('validation results went down. early stopping ...')
break
lasagne.layers.set_all_param_values(self.l_out, best_params)
logging.info('***************** final results based on best validation **************')
l_val, acc_val = self.f_val(X_dev, Y_dev)
logging.info('Best dev acc: %f' %(acc_val))
def predict(self, X_test):
X_test = X_test.astype('float32')
return self.f_predict(X_test)
def predict_proba(self, X_test):
X_test = X_test.astype('float32')
return self.f_predict_proba(X_test)
def accuracy(self, X_test, Y_test):
X_test = X_test.astype('float32')
if self.complete_prob:
Y_test = Y_test.astype('float32')
else:
Y_test = Y_test.astype('int32')
test_loss, test_acc = self.f_val(X_test, Y_test)
return test_acc
def score(self, X_test, Y_test):
return self.accuracy(X_test, Y_test)
def get_embedding(self, X):
return self.f_get_embeddings(X)
class MLPDense():
def __init__(self, input_sparse, in_size, out_size, architecture, batch_size=1000, regul=1e-6, dropout=0.0, lr=3e-4, batchnorm=False):
self.in_size = in_size
self.out_size = out_size
self.architecture = architecture
self.regul = regul
self.dropout = dropout
self.input_sparse = input_sparse
self.lr = lr
self.batchnorm = batchnorm
self.fitted = False
def build(self, seed=77):
np.random.seed(seed)
logging.info('Building model with in_size {} out size {} batchnorm {} regul {} dropout {} and architecture {}'.format(self.in_size, self.out_size, str(self.batchnorm), self.regul, self.dropout, str(self.architecture)))
if self.input_sparse:
X_sym = S.csr_matrix(name='sparse_input')
else:
X_sym = T.matrix('dense input')
y_sym = T.ivector()
l_in = lasagne.layers.InputLayer(shape=(None, self.in_size), input_var=X_sym)
l_hid = l_in
nonlinearity = lasagne.nonlinearities.rectify
#W = lasagne.init.HeNormal() #for selu
W = lasagne.init.GlorotUniform(gain='relu')
for i, hid_size in enumerate(self.architecture):
if i == 0 and self.input_sparse:
l_hid = SparseInputDenseLayer(l_hid, num_units=hid_size, nonlinearity=nonlinearity, W=W)
if self.batchnorm:
l_hid = lasagne.layers.batch_norm(l_hid)
else:
l_hid = lasagne.layers.DenseLayer(l_hid, num_units=hid_size, nonlinearity=nonlinearity, W=W)
if self.batchnorm:
l_hid = lasagne.layers.batch_norm(l_hid)
l_hid = lasagne.layers.dropout(l_hid, p=self.dropout)
l_out = lasagne.layers.DenseLayer(l_hid, num_units=self.out_size, nonlinearity=lasagne.nonlinearities.softmax)
self.l_out = l_out
output = lasagne.layers.get_output(l_out, X_sym, deterministic=False)
eval_output = lasagne.layers.get_output(l_out, X_sym, deterministic=True)
pred = output.argmax(-1)
eval_pred = eval_output.argmax(-1)
acc = T.mean(T.eq(pred, y_sym))
eval_acc = T.mean(T.eq(eval_pred, y_sym))
loss = lasagne.objectives.categorical_crossentropy(output, y_sym).mean()
regul_loss = lasagne.regularization.regularize_network_params(l_out, penalty=l2) * self.regul
regul_loss += lasagne.regularization.regularize_network_params(l_out, penalty=l1) * self.regul
eval_loss = loss
loss += regul_loss
parameters = lasagne.layers.get_all_params(self.l_out, trainable=True)
updates = lasagne.updates.adam(loss, parameters, learning_rate=self.lr, beta1=0.9, beta2=0.999, epsilon=1e-8)
self.f_train = theano.function([X_sym, y_sym], [eval_loss, acc], updates=updates)
self.f_val = theano.function([X_sym, y_sym], [eval_pred, eval_loss, eval_acc])
self.f_predict = theano.function([X_sym], eval_pred)
self.init_params = lasagne.layers.get_all_param_values(self.l_out)
def predict(self, X):
return self.f_predict(X)
def fit(self, X_train, y_train, X_dev, y_dev, n_epochs=100, early_stopping_max_down=5, verbose=True, batch_size=1000, seed=77):
np.random.seed(seed)
best_params = None
best_val_loss = sys.maxint
best_val_acc = 0.0
n_validation_down = 0
for epoch in xrange(n_epochs):
l_train_batches = []
acc_train_batches = []
for batch in iterate_minibatches(X_train, y_train, batch_size, shuffle=True):
l_train, acc_train = self.f_train(batch[0], batch[1])
l_train, acc_train = l_train.item(), acc_train.item()
l_train_batches.append(l_train)
acc_train_batches.append(acc_train)
l_train = np.mean(l_train_batches)
acc_train = np.mean(acc_train_batches)
pred_val, l_val, acc_val = self.f_val(X_dev, y_dev)
l_val, acc_val = l_val.item(), acc_val.item()
if l_val < best_val_loss:
best_val_loss = l_val
best_val_acc = acc_val
best_params = lasagne.layers.get_all_param_values(self.l_out)
n_validation_down = 0
else:
#early stopping
n_validation_down += 1
#logging.info('epoch {} train loss {} acc {} val loss {} acc {}'.format(epoch, l_train, acc_train, l_val, acc_val))
if verbose:
logging.info('epoch {} train loss {:.2f} acc {:.2f} val loss {:.2f} acc {:.2f} best acc {:.2f} maxdown {}'.format(epoch, l_train, acc_train, l_val, acc_val, best_val_acc, n_validation_down))
if n_validation_down > early_stopping_max_down:
logging.info('validation results went down. early stopping ...')
break
lasagne.layers.set_all_param_values(self.l_out, best_params)
self.fitted = True
def reset(self):
lasagne.layers.set_all_param_values(self.l_out, self.init_params)
if __name__ == '__main__':
pass
|
afshinrahimi/geographconv
|
mlp.py
|
mlp.py
|
py
| 18,612 |
python
|
en
|
code
| 67 |
github-code
|
50
|
34025219462
|
import sys
import os
import pytest
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from cvxpy import installed_solvers
from hysut.utils.defaults import ModelSettings
def test_ModelSettings():
settings = ModelSettings()
# wrong solver
output = settings.validate_solver("dummy")
expected_output = {
"value": settings.solver,
"warning": [
f"dummy is not a valid solver or not installed on your machine. Default solver ({settings.solver}) is used."
],
}
assert output == expected_output
# wrong log_path
output = settings.validate_log_path(12)
expected_output = {
"value": settings.log_path,
"warning": [
f"log_path should be str. Default log_path ({settings.log_path}) is used."
],
}
|
HySUT/hysut
|
tests/test_defaults.py
|
test_defaults.py
|
py
| 833 |
python
|
en
|
code
| 0 |
github-code
|
50
|
27386073504
|
from tkinter import *
def submit():
print("It is " + str(scale.get()) + " degrees C.")
window = Tk()
#placed at top
hotImage = PhotoImage(file = "GUI_Icon.png") #placeholder for fire image
hotLabel = Label(image=hotImage)
hotLabel.pack()
scale = Scale(window,
from_=100, #sets range for scale
to=0,
length=600, #length of scale
orient=VERTICAL, #scale orientation
font = ("Consolas",20),
tickinterval = 10, #adds indicator for values
#showvalue = 0, #Hide current numeric value of slider
troughcolor= "green", #changes color of slider
fg = "#FF1C00",
bg = "Black"
)
scale.set(50) #has the scale start at 50 \\\\ ((scale["from"]-scale["to"])/2)+scale("to") will always start at the middle
scale.pack()
#placed at bottom
coldImage = PhotoImage(file = "GUI_Icon.png") #placeholder for snowflake image
coldLabel = Label(image=hotImage)
coldLabel.pack()
button = Button(window,
text = "submit",
command = submit)
button.pack()
window.mainloop()
|
18gwoo/Python-Practice
|
BroCode70_GUI_Scale.py
|
BroCode70_GUI_Scale.py
|
py
| 1,136 |
python
|
en
|
code
| 0 |
github-code
|
50
|
38189202195
|
import re
from SymbolTable import SymbolTable
class CodeWriter:
CONVERT_KIND = {
'ARG': 'ARG',
'STATIC': 'STATIC',
'VAR': 'LOCAL',
'FIELD': 'THIS'
}
ARITHMETIC = {
'+': 'ADD',
'-': 'SUB',
'=': 'EQ',
'>': 'GT',
'<': 'LT',
'&': 'AND',
'|': 'OR'
}
ARITHMETIC_UNARY = {
'-': 'NEG',
'~': 'NOT'
}
if_index = -1
while_index = -1
def __init__(self, tokenizer, output_file):
self.output = output_file
self.tokenizer = tokenizer
self.symbol_table = SymbolTable()
self.buffer = []
def compile_class(self):
self.get_token()
self.class_name = self.get_token()
self.get_token()
while self.is_class_var_dec():
self.compile_classVarDec()
while self.is_subroutine_dec():
self.compile_subroutineDec()
self.close()
def compile_classVarDec(self):
kind = self.get_token()
type = self.get_token()
name = self.get_token()
self.symbol_table.define(name, type, kind.upper())
while self.peek() != ';':
self.get_token()
name = self.get_token()
self.symbol_table.define(name, type, kind.upper())
self.get_token()
def compile_subroutineDec(self):
subroutine_kind = self.get_token()
self.get_token()
subroutine_name = self.get_token()
self.symbol_table.start_subroutine()
if subroutine_kind == 'method':
self.symbol_table.define('instance', self.class_name, 'ARG')
self.get_token()
self.compile_parameterList()
self.get_token()
self.get_token()
while self.peek() == 'var':
self.compile_var_dec()
function_name = '{}.{}'.format(self.class_name, subroutine_name)
num_locals = self.symbol_table.var_count('VAR')
self.write_function(function_name, num_locals)
if subroutine_kind == 'constructor':
num_fields = self.symbol_table.var_count('FIELD')
self.write_push('CONST', num_fields)
self.write_call('Memory.alloc', 1)
self.write_pop('POINTER', 0)
elif subroutine_kind == 'method':
self.write_push('ARG', 0)
self.write_pop('POINTER', 0)
self.compile_statements()
self.get_token()
def write_push(self, segment, index):
if segment == 'CONST':
segment = 'constant'
elif segment == 'ARG':
segment = 'argument'
self.output.write('push {} {}\n'.format(segment.lower(), index))
def write_pop(self, segment, index):
if segment == 'CONST':
segment = 'constant'
elif segment == 'ARG':
segment = 'argument'
self.output.write('pop {} {}\n'.format(segment.lower(), index))
def write_arithmetic(self, command):
self.output.write(command.lower() + '\n')
def write_label(self, label):
self.output.write('label {}'.format(label))
def write_goto(self, label):
self.output.write('goto {}'.format(label))
def write_if(self, label):
self.output.write('if-goto {}'.format(label))
def write_call(self, name, nArgs):
self.output.write('call {} {}\n'.format(name, nArgs))
def write_function(self, name, nLocals):
self.output.write('function {} {}\n'.format(name, nLocals))
def write_return(self):
self.output.write('return\n')
def close(self):
self.output.close()
def write(self, stuff):
self.output.write(stuff)
def compile_parameterList(self):
if ')' != self.peek():
type = self.get_token()
name = self.get_token()
self.symbol_table.define(name, type, 'ARG')
while ')' != self.peek():
self.get_token()
type = self.get_token()
name = self.get_token()
self.symbol_table.define(name, type, 'ARG')
def compile_var_dec(self):
self.get_token()
type = self.get_token()
name = self.get_token()
self.symbol_table.define(name, type, 'VAR')
while self.peek() != ';':
self.get_token()
name = self.get_token()
self.symbol_table.define(name, type, 'VAR')
self.get_token()
def compile_statements(self):
while self.is_statement():
token = self.get_token()
if token == 'let':
self.compile_letStatement()
elif token == 'if':
self.compile_ifStatement()
elif token == 'while':
self.compile_whileStatement()
elif token == 'do':
self.compile_doStatement()
elif token == 'return':
self.compile_returnStatement()
def compile_doStatement(self):
self.compile_subroutine_call()
self.write_pop('TEMP', 0)
self.get_token()
def compile_letStatement(self):
var_name = self.get_token()
var_kind = self.CONVERT_KIND[self.symbol_table.kind_of(var_name)]
var_index = self.symbol_table.index_of(var_name)
if self.peek() == '[':
self.get_token()
self.compile_expression()
self.get_token()
self.write_push(var_kind, var_index)
self.write_arithmetic('ADD')
self.write_pop('TEMP', 0)
self.get_token()
self.compile_expression()
self.get_token()
self.write_push('TEMP', 0)
self.write_pop('POINTER', 1)
self.write_pop('THAT', 0)
else:
self.get_token()
self.compile_expression()
self.get_token()
self.write_pop(var_kind, var_index)
def compile_whileStatement(self):
self.while_index += 1
while_index = self.while_index
self.write_label('WHILE{}\n'.format(while_index))
self.get_token()
self.compile_expression()
self.write_arithmetic('NOT')
self.get_token()
self.get_token()
self.write_if('WHILE_END{}\n'.format(while_index))
self.compile_statements()
self.write_goto('WHILE{}\n'.format(while_index))
self.write_label('WHILE_END{}\n'.format(while_index))
self.get_token()
def compile_returnStatement(self):
if self.peek() != ';':
self.compile_expression()
else:
self.write_push('CONST', 0)
self.write_return()
self.get_token()
def compile_ifStatement(self):
self.if_index += 1
if_index = self.if_index
self.get_token()
self.compile_expression()
self.get_token()
self.get_token()
self.write_if('IF_TRUE{}\n'.format(if_index))
self.write_goto('IF_FALSE{}\n'.format(if_index))
self.write_label('IF_TRUE{}\n'.format(if_index))
self.compile_statements() # statements
self.write_goto('IF_END{}\n'.format(if_index))
self.get_token() # '}'
self.write_label('IF_FALSE{}\n'.format(if_index))
if self.peek() == 'else':
self.get_token()
self.get_token()
self.compile_statements()
self.get_token()
self.write_label('IF_END{}\n'.format(if_index))
def compile_expression(self):
self.compile_term()
while self.is_op():
op = self.get_token()
self.compile_term()
if op in self.ARITHMETIC.keys():
self.write_arithmetic(self.ARITHMETIC[op])
elif op == '*':
self.write_call('Math.multiply', 2)
elif op == '/':
self.write_call('Math.divide', 2)
def compile_term(self):
if self.is_unary_op_term():
unary_op = self.get_token() # unaryOp
self.compile_term() # term
self.write_arithmetic(self.ARITHMETIC_UNARY[unary_op])
elif self.peek() == '(':
self.get_token() # '('
self.compile_expression() # expression
self.get_token() # ')'
elif self.peek_type() == 'INT_CONST': # integerConstant
self.write_push('CONST', self.get_token())
elif self.peek_type() == 'STRING_CONST': # stringConstant
self.compile_string()
elif self.peek_type() == 'KEYWORD': # keywordConstant
self.compile_keyword()
else: # first is a var or subroutine
if self.is_array():
array_var = self.get_token() # varName
self.get_token() # '['
self.compile_expression() # expression
self.get_token() # ']'
array_kind = self.symbol_table.kind_of(array_var)
array_index = self.symbol_table.index_of(array_var)
self.write_push(self.CONVERT_KIND[array_kind], array_index)
self.write_arithmetic('ADD')
self.write_pop('POINTER', 1)
self.write_push('THAT', 0)
elif self.is_subroutine_call():
self.compile_subroutine_call()
else:
var = self.get_token()
var_kind = self.CONVERT_KIND[self.symbol_table.kind_of(var)]
var_index = self.symbol_table.index_of(var)
self.write_push(var_kind, var_index)
def compile_expression_list(self):
number_args = 0
if self.peek() != ')':
number_args += 1
self.compile_expression()
while self.peek() != ')':
number_args += 1
self.get_token() # ','
self.compile_expression()
return number_args
def compile_keyword(self):
keyword = self.get_token() # keywordConstant
if keyword == 'this':
self.write_push('POINTER', 0)
else:
self.write_push('CONST', 0)
if keyword == 'true':
self.write_arithmetic('NOT')
def compile_subroutine_call(self):
identifier = self.get_token()
function_name = identifier
number_args = 0
if self.peek() == '.':
self.get_token()
subroutine_name = self.get_token()
type = self.symbol_table.type_of(identifier)
if type != 'NONE':
instance_kind = self.symbol_table.kind_of(identifier)
instance_index = self.symbol_table.index_of(identifier)
self.write_push(self.CONVERT_KIND[instance_kind], instance_index)
function_name = '{}.{}'.format(type, subroutine_name)
number_args += 1
else: # it's a class
class_name = identifier
function_name = '{}.{}'.format(class_name, subroutine_name)
elif self.peek() == '(':
subroutine_name = identifier
function_name = '{}.{}'.format(self.class_name, subroutine_name)
number_args += 1
self.write_push('POINTER', 0)
self.get_token() # '('
number_args += self.compile_expression_list()
self.get_token() # ')'
self.write_call(function_name, number_args)
def compile_string(self):
string = self.get_token()
self.write_push('CONST', len(string))
self.write_call('String.new', 1)
for char in string:
self.write_push('CONST', ord(char))
self.write_call('String.appendChar', 2)
def is_subroutine_call(self):
token = self.get_token()
subroutine_call = self.peek() in ['.', '(']
self.unget_token(token)
return subroutine_call
def is_array(self):
token = self.get_token()
array = self.peek() == '['
self.unget_token(token)
return array
def is_class_var_dec(self):
return self.peek() in ['static', 'field']
def is_subroutine_dec(self):
return self.peek() in ['constructor', 'function', 'method']
def is_statement(self):
return self.peek() in ['let', 'if', 'while', 'do', 'return']
def is_op(self):
return self.peek() in ['+', '-', '*', '/', '&', '|', '<', '>', '=']
def is_unary_op_term(self):
return self.peek() in ['~', '-']
def peek(self):
return self.peek_info()[0]
def peek_type(self):
return self.peek_info()[1]
def peek_info(self):
token_info = self.get_token_info()
self.unget_token_info(token_info)
return token_info
def get_token(self):
return self.get_token_info()[0]
def get_token_info(self):
if self.buffer:
return self.buffer.pop(0)
else:
return self.get_next_token()
def unget_token(self, token):
self.unget_token_info((token, 'UNKNOWN'))
def unget_token_info(self, token):
self.buffer.insert(0, token)
def get_next_token(self):
if self.tokenizer.has_more_tokens():
self.tokenizer.advance()
if self.tokenizer.token_type() is 'KEYWORD':
return self.tokenizer.key_word().lower(), self.tokenizer.token_type()
elif self.tokenizer.token_type() is 'SYMBOL':
return self.tokenizer.symbol(), self.tokenizer.token_type()
elif self.tokenizer.token_type() is 'IDENTIFIER':
return self.tokenizer.identifier(), self.tokenizer.token_type()
elif self.tokenizer.token_type() is 'INT_CONST':
return self.tokenizer.int_val(), self.tokenizer.token_type()
elif self.tokenizer.token_type() is 'STRING_CONST':
return self.tokenizer.string_val(), self.tokenizer.token_type()
|
abarat256/JACK_Compiler
|
CodeWriter.py
|
CodeWriter.py
|
py
| 14,451 |
python
|
en
|
code
| 0 |
github-code
|
50
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.