id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
11243597 | <reponame>joshdabosh/autopack<gh_stars>0
import RPi.GPIO as GPIO
import time
from threading import Thread
distances = []
TRIG = 24
ECHO = 26
GPIO.setmode(GPIO.BOARD)
GPIO.setup(TRIG, GPIO.OUT) # trigger voltage setup
GPIO.setup(ECHO, GPIO.IN) # echo input setup
GPIO.output(TRIG, False)
distances = []
def scan_for_obstacles():
GPIO.setmode(GPIO.BOARD)
while True:
GPIO.setmode(GPIO.BOARD)
# tells the sensor to fire a burst of sound
GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)
while GPIO.input(ECHO) == 0:
pass
startTime = time.time()
while GPIO.input(ECHO) == 1:
pass
stopTime = time.time()
distance = (stopTime-startTime) * 17000
distances.append(distance)
time.sleep(0.025)
def move():
dist = distances[-1]
if dist <= 10:
print 'uh oh a-somebody toucha mah spagheett'
def Main():
try:
t1 = Thread(target = scan_for_obstacles)
t1.start()
t2 = Thread(target=move)
t2.start()
t2.join()
print distances
except KeyboardInterrupt:
# shut down cleanly
GPIO.cleanup()
if __name__ == '__main__':
Main()
| StarcoderdataPython |
4938003 | import os
import cv2
import time
import itertools
import numpy as np
repository = f"{os.getcwd()}/images"
watermark_file = "watermark.png"
color = [255, 0, 0] # blue
def get_files(path):
for _, _, files in os.walk(path):
return files
def watermark(image):
watermark = cv2.imread(watermark_file)
overlay = image.copy()
output = image.copy()
watermark_height, watermark_width = watermark.shape[:2]
image_height, image_width = overlay.shape[:2]
overlay[
image_height-watermark_height:image_height,
0:watermark_width] = watermark
cv2.addWeighted(overlay, 0.5, output, 1 - 0.5, 0, output)
return output
def border(image):
bordered_image = cv2.copyMakeBorder(
image, 20, 20, 20, 20, cv2.BORDER_CONSTANT, value=color)
return bordered_image
def load(file):
image = cv2.imread(os.path.join(repository, file))
return image
def show(image):
cv2.imshow('showing_images', image)
time.sleep(2)
def apply(image):
bordered_image = border(image)
watermarked_image = watermark(bordered_image)
return watermarked_image
def get_next_image_index(file, files):
index = files.index(file)
if index > len(files):
return 0
return index-1
def transition_image(current_image, file, files):
next_image = get_next_image(file, files)
next_image_applied = apply(next_image)
for alpha in range(1, 11):
alpha = alpha/10.0
beta = 1 - alpha
cv2.imshow('showing_images', cv2.addWeighted(current_image, alpha, next_image_applied, beta, 0.1))
time.sleep(0.1)
if cv2.waitKey(1) & 0xFF == ord('q'):
exit()
def get_next_image(file, files):
next_image_index = get_next_image_index(file, files)
return load(files[next_image_index])
def display_images(files):
for current_file in itertools.cycle(files):
image = load(current_file)
applied_image = apply(image)
show(applied_image)
transition_image(applied_image, current_file, files)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
if __name__ == "__main__":
files = get_files(repository)
display_images(files)
| StarcoderdataPython |
11353709 | <filename>cupyx/optimizing/__init__.py
from cupyx.optimizing._optimize import optimize # NOQA
| StarcoderdataPython |
8033650 | # Copyright 2020 <NAME>, Pôle OFB-INRAE ECLA, UR RECOVER
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This module contains the TimeSeries class.
A TimeSeries object is a new kind of product, made from either L1, L2, or L3
products, and allowing one to build a time series:
* Masks can be used to clip data.
* Basic statistics can be calculated.
* Generic plots can easily be made.
Example::
paths = [<first S2_ESA_L2A product>, <second S2_ESA_L2A product>, ...,
<n-th S2_ESA_L2A product>]
mask_paths = [
[<first water_mask>, <second water_mask>, ..., <n-th water_mask>],
[<first mask2>
config = {
'paths': paths,
'product_type': 'S2_ESA_L2A',
'requested_bands': ['B2', 'B3', 'B4', 'B5', 'B6'],
'wkt': wkt,
'srid': 4326,
}
S2L2A_ts = factory.create('TS', **config)
S2L2A_ts.compute_stats(<filename>)
S2L2A_ts.plot()
"""
import warnings
from copy import deepcopy
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable, List, Optional, Tuple, Union
import numpy as np
import pandas as pd
import plotly.figure_factory as ff
import plotly.graph_objects as go
import plotly.io as pio
import xarray as xr
from PIL import Image, ImageDraw, ImageFont
from plotly.subplots import make_subplots
from tqdm import tqdm
from sisppeo.utils.config import resources
from sisppeo.utils.lazy_loader import LazyLoader
from sisppeo.utils.products import (get_grid, get_enc, normalize_arr,
CoordinatesMixin)
from sisppeo.utils.readers import resample_band_array
pio.templates.default = 'simple_white'
warnings.filterwarnings('ignore', category=xr.SerializationWarning)
colorcet = LazyLoader('colorcet', globals(), 'colorcet')
ds = LazyLoader('ds', globals(), 'datashader')
# pylint: disable=invalid-name
# P is a custom static type.
N = Union[int, float]
P = Union[Path, str]
@dataclass
class TimeSeries(CoordinatesMixin):
"""A 'L4' product, made from either L1, L2, or L3 products.
This product contain one or more DataArrays (e.g., one for ndwi, one for
each band extracted...). Each DataArrays is a data cube (i.e. 3D: x, y,
time). It allows one to study time series of data, and compute and plot
statistics over time and/or space.
Attributes:
dataset: A dataset containing one or more 3D-dataarrays.
"""
__slots__ = 'dataset',
dataset: xr.Dataset
def __post_init__(self):
self.dataset = self.dataset.sortby('time')
@classmethod
def from_file(cls, filename: Path):
"""Load a TimeSeries object from disk.
Args:
filename: The path of the netCDF file.
Returns:
A TimeSeries object (i.e. a 3D dataset : time, x, y).
"""
return TimeSeries(xr.open_dataset(filename))
@classmethod
def from_files(cls, paths: List[Path]):
"""Load and merge a list of L3 products from disk.
Args:
paths: A list of paths (to L3 products saved as netCDF files).
Returns:
A TimeSeries object (i.e. a 3D dataset : time, x, y).
"""
ts = xr.open_mfdataset(paths, concat_dim='time', combine='nested',
join='inner', data_vars='minimal',
coords='minimal', compat='override')
return TimeSeries(ts)
@classmethod
def from_l3products(cls, lst: Iterable):
"""Load and merge a list of L3 products.
Args:
lst: A list of L3 products (loaded in memory).
Returns:
A TimeSeries object (i.e. a 3D dataset : time, x, y).
"""
ts = xr.concat([product.dataset for product in lst], dim='time',
data_vars='minimal', coords='minimal',
compat='override', join='inner',
combine_attrs='override')
return TimeSeries(ts)
@property
def title(self) -> str:
"""Returns the title of the underlying dataset."""
return self.dataset.attrs.get('title')
@property
def data_vars(self):
"""Returns a list of DataArrays corresponding to variables."""
return [data_var for data_var in self.dataset.data_vars
if data_var not in ('crs', 'product_metadata')]
@property
def start_date(self) -> pd.Timestamp:
"""Return the start date."""
return self.dataset.get_index('time').min()
@property
def end_date(self) -> pd.Timestamp:
"""Return the end date."""
return self.dataset.get_index('time').max()
def save(self, filename: P) -> None:
"""See base class."""
enc = {data_var: get_enc(self.dataset[data_var].values, 0.001, True)
for data_var in self.data_vars}
enc.update({
'crs': {'dtype': 'byte'},
'product_metadata': {'dtype': 'byte'},
'x': get_enc(self.dataset.x.values, 0.1),
'y': get_enc(self.dataset.y.values, 0.1)
})
self.dataset.to_netcdf(filename, encoding=enc)
def compute_stats(self, filename: P, plot: bool = True) -> None:
"""Computes (and save on disk) statistics about embedded data at each date.
Args:
filename: The path of the output product (a CSV file).
plot: A boolean flag that indicates if computed statistics should
be plotted or not.
"""
lst_df = []
for var in tqdm(self.data_vars, unit='vars'):
lst_series = []
for date in tqdm(self.dataset.time.values, leave=False,
unit='dates'):
mean = float(self.dataset[var].sel(time=str(date)).mean())
std = float(self.dataset[var].sel(time=str(date)).std())
min_ = float(self.dataset[var].sel(time=str(date)).min())
q1 = float(
self.dataset[var].sel(time=str(date)).quantile(0.25)
)
median = np.nanmedian(self.dataset[var].sel(time=str(date)).values)
q3 = float(
self.dataset[var].sel(time=str(date)).quantile(0.75)
)
max_ = float(self.dataset[var].sel(time=str(date)).max())
series = pd.Series(
data=[mean, std, min_, q1, median, q3, max_],
index=['mean', 'std', 'min', 'q1', 'median', 'q3', 'max'],
name=str(date)
)
lst_series.append(series)
df = pd.concat(lst_series, axis=1).transpose()
if plot:
lst_df.append(df)
df.to_csv(f'{filename}_{var}.csv', index_label='date')
if plot:
for df in lst_df:
print(df)
def _grayscale_timelapse(self, data_var: str, filename: P,
out_res: Optional[int] = None, write_time: bool = True):
min_ = np.nanmin(self.dataset[data_var].values)
max_ = np.nanmax(self.dataset[data_var].values)
lst_img = [Image.fromarray(normalize_arr(
cond_resample(self.dataset[data_var].isel(time=i).values, self.res,
out_res), min_, max_
).astype(np.uint8)) for i in range(len(self.dataset.time))]
if write_time:
font = ImageFont.truetype(str(resources / 'fonts/Ubuntu-R.ttf'),
32)
for i, img in enumerate(lst_img):
draw = ImageDraw.Draw(img)
draw.text((10, img.height-10),
self.dataset.get_index('time')[i].isoformat(),
255, font, 'lb', stroke_width=2, stroke_fill=127)
lst_img[0].save(filename, save_all=True, append_images=lst_img[1:],
duration=1500, optimize=True)
def _rgb_timelapse(self, data_vars: List[str], filename: P,
out_res: Optional[int] = None, write_time: bool = True):
min_ = {data_var: np.nanmin(self.dataset[data_var].values)
for data_var in data_vars}
max_ = {data_var: np.nanmax(self.dataset[data_var].values)
for data_var in data_vars}
lst_img = [Image.fromarray(np.stack([normalize_arr(
cond_resample(self.dataset.isel(time=i)[data_var].values, self.res,
out_res), min_[data_var], max_[data_var]
).astype(np.uint8) for data_var in data_vars], axis=-1), mode='RGB')
for i in range(len(self.dataset.time))]
if write_time:
font = ImageFont.truetype(str(resources / 'fonts/Ubuntu-R.ttf'),
32)
for i, img in enumerate(lst_img):
draw = ImageDraw.Draw(img)
draw.text(
(10, img.height-10),
self.dataset.get_index('time')[i].isoformat(),
'yellow', font, 'lb', stroke_width=2, stroke_fill='red'
)
lst_img[0].save(filename, save_all=True, append_images=lst_img[1:],
duration=1500, optimize=True)
def timelapse(self, data_vars: Union[str, List[str]], filename: P,
out_res: Optional[int] = None, write_time: bool = True):
"""Creates a timelapse and save it on disk (as a GIF file).
Args:
data_vars: The data_var(s) to plot; 1 for a grayscale image, and a
list of 3 for a RGB one.
filename: The path of the output gif.
out_res: The resolution of the timelapse; must be coarser than the
one of the time series.
write_time: If True, the corresponding date will be written on each
frame.
"""
if isinstance(data_vars, str):
self._grayscale_timelapse(data_vars, filename, out_res, write_time)
else:
self._rgb_timelapse(data_vars, filename, out_res, write_time)
def _plot_1d_1var(self, data_var, lst_coordinates, buffer=None, epsg=4326,
mode='xy'):
fig = go.Figure()
lst_data = self.extract_points(data_var, lst_coordinates, buffer, epsg,
mode)
for i, (data, coordinates) in enumerate(zip(lst_data, lst_coordinates)):
if buffer is not None:
data = np.nanmean(data)
fig.add_trace(go.Scatter(
x=self.dataset.time.values,
y=data,
name=f'Point {i + 1} ({coordinates[0]}, {coordinates[1]})'
))
fig.update_xaxes(title_text='date')
fig.update_yaxes(title_text=self.dataset[data_var].long_name)
return fig
def _plot_1d_nvars(self, data_vars, lst_coordinates, buffer=None,
epsg=4326, mode='xy'):
rows, cols = get_grid(len(data_vars))
fig = make_subplots(rows=rows, cols=cols, shared_xaxes=True,
vertical_spacing=0.05, horizontal_spacing=0.05)
for i, data_var in enumerate(data_vars):
row = i // cols + 1
col = i % cols + 1
lst_data = self.extract_points(data_var, lst_coordinates, buffer,
epsg, mode)
for j, (data, coordinates) in enumerate(zip(lst_data,
lst_coordinates)):
if buffer is not None:
data = np.nanmean(data)
fig.add_trace(go.Scatter(
x=self.dataset.time.values,
y=data,
name=f'Point {j + 1} ({coordinates[0]}, {coordinates[1]})'
), row=row, col=col)
fig.update_xaxes(title_text='date')
fig.update_yaxes(title_text=self.dataset[data_var].long_name)
width = 450 * cols
height = 450 * rows
fig.update_layout(width=width, height=height,
margin={'b': 0, 'l': 0, 'r': 0, 't': 0})
return fig
# pylint: disable=too-many-locals
# 17 local variables is acceptable here (plotting stuff).
def plot_1d(self,
lst_coordinates: Union[Tuple[int, int], List[Tuple[int, int]]],
data_var: Union[str, List[str]] = 'all',
buffer=None,
epsg=4326,
mode='xy',
filename: Optional[P] = None,
fmt: str = 'jpeg') -> None:
"""Plots time series of data_var(s) for one or more given points.
Args:
lst_coordinates: A tuple of coordinates (x, y) that locates the
point to extract (/a list of tuples of coordinates, locating
points of interest).
data_var: Optional; A variable (e.g. "aCDOM") or a list of
variables to plot.
buffer:
epsg:
mode:
filename: Optional; If a filename is provided, the figure will be
saved using this path.
fmt: The format of the exported figure. Can be either "png",
"jpeg", "webp", "svg" or "pdf".
"""
if isinstance(lst_coordinates, tuple):
lst_coordinates = [lst_coordinates]
if data_var == 'all':
data_var = self.data_vars
if isinstance(data_var, list):
fig = self._plot_1d_nvars(data_var, lst_coordinates, buffer, epsg,
mode)
else:
fig = self._plot_1d_1var(data_var, lst_coordinates, buffer, epsg,
mode)
fig.show()
if filename is not None:
fig.write_image(f'{filename}.{fmt}')
# pylint: disable=too-many-locals
# 17 local variables is acceptable here (plotting stuff).
def plot_2d(self,
data_vars: Union[str, List[str]] = 'all',
filename: Optional[P] = None,
fmt: str = 'jpeg') -> None:
"""Plots timelapse as a mosaic (one per data_var).
For each data_var, create a figure composed of multiples subplots, each
one of them being a image of the given data_var at a given date.
Args:
data_vars: A variable (e.g. "aCDOM") or a list for variables to
plot. If 'all', creates a figure for each variable (i.e.
DataArray) embedded into this dataset.
filename: Optional; If a filename is provided, the figure will be
saved using this path.
fmt: The format of the exported figure. Can be either "png",
"jpeg", "webp", "svg" or "pdf".
"""
if data_vars == 'all':
data_vars = self.data_vars
elif isinstance(data_vars, str):
data_vars = [data_vars]
x = self.dataset.x.values
y = self.dataset.y.values
for data_var in data_vars:
rows, cols = get_grid(len(self.dataset.time))
fig = make_subplots(rows=rows, cols=cols,
shared_yaxes=True, shared_xaxes=True,
subplot_titles=[str(time) for time
in self.dataset.time.values],
vertical_spacing=0.05, horizontal_spacing=0.05)
for i, row in enumerate(range(1, rows + 1)):
for j, col in enumerate(range(1, cols + 1)):
data = self.dataset[data_var].isel(time=i + j).values
if len(x) + len(y) >= 9000:
z = ds.Canvas(
plot_width=np.round(len(x) / 10).astype(np.int16),
plot_height=np.round(len(y) / 10).astype(np.int16)
).raster(data)
else:
z = data
fig.add_trace(go.Heatmap(z=z, x=x, y=y, hoverongaps=False,
coloraxis='coloraxis'), row, col)
if row == rows:
fig.update_xaxes(title_text=self.dataset.x.long_name,
row=row, col=col)
if col == 1:
fig.update_yaxes(title_text=self.dataset.y.long_name,
row=row, col=col)
fig.update_xaxes(showline=False)
fig.update_yaxes(showline=False)
width = 450 * cols
height = 450 * rows
fig.update_layout(coloraxis={'colorscale': colorcet.rainbow,
'colorbar': {'title': data_var}},
width=width, height=height,
margin={'b': 0, 'l': 0, 'r': 0, 't': 50})
fig.show()
if filename is not None:
fig.write_image(f'{filename}.{fmt}')
def get_mean_map(self,
var: str,
plot: bool = True,
filename: Optional[P] = None,
save: bool = False,
savefig: bool = False,
fmt: str = 'jpeg') -> xr.DataArray:
"""Gets the map of (temporal) mean values for a given data_var.
Compute a map (a DataArray of dimension N * M) from a DataArray of
dimension t * N * M. Each pixel of this map is the mean value of the
N * M t-vectors.
Args:
var: The name of the DataArray to use.
plot: A boolean flag that indicates if the figure should be
plotted or not.
filename: Optional; The path of the output product (a figure and/or
a netCDF file).
save: Optional; A boolean flag that indicates if the mean map
should be saved on disk or not.
savefig: Optional; A boolean flag that indicates if the figure
should be saved or not.
fmt: The format of the static image that is saved on disk. Can be
either "png", "jpeg", "webp", "svg" or "pdf".
Returns:
A map (a dataarray of dimension N * M) of mean values for a given
data_var.
"""
res = self.dataset[var].mean(dim='time')
if plot:
if len(res.x) + len(res.y) >= 9000:
z = ds.Canvas(
plot_width=np.round(len(res.x) / 10).astype(np.int16),
plot_height=np.round(len(res.y) / 10).astype(np.int16)
).raster(res)
else:
z = res
fig = go.Figure(go.Heatmap(
z=z, x=res.x.values, y=res.y.values,
hoverongaps=False,
colorscale=colorcet.rainbow, colorbar={'title': var}
))
fig.update_xaxes(title_text=self.dataset.x.long_name,
showline=False)
fig.update_yaxes(title_text=self.dataset.y.long_name,
showline=False, )
fig.update_layout(width=900, height=900,
margin={'b': 0, 'l': 0, 'r': 0, 't': 0})
fig.show()
if savefig and filename is not None:
fig.write_image(f'{filename}.{fmt}')
if save and filename is not None:
np.save(filename, res, False)
return res
def get_min_map(self,
var: str,
plot: bool = True,
filename: Optional[P] = None,
save: bool = False,
savefig: bool = False,
fmt: str = 'jpeg') -> xr.DataArray:
"""Gets the map of (temporal) min values for a given data_var.
Compute a map (a dataarray of dimension N * M) from a dataarray of
dimension t * N * M. Each pixel of this map is the min value of the
N * M t-vectors.
Args:
var: The name of the dataarray to use.
plot: A boolean flag that indicates if the figure should be
plotted or not.
filename: Optional; The path of the output product (a figure and/or
a netCDF file).
save: Optional; A boolean flag that indicates if the mean map
should be saved on disk or not.
savefig: Optional; A boolean flag that indicates if the figure
should be saved or not.
fmt: The format of the static image that is saved on disk. Can be
either "png", "jpeg", "webp", "svg" or "pdf".
Returns:
A map (a dataarray of dimension N * M) of min values for a given
data_var.
"""
res = self.dataset[var].min(dim='time')
if plot:
if len(res.x) + len(res.y) >= 9000:
z = ds.Canvas(
plot_width=np.round(len(res.x) / 10).astype(np.int16),
plot_height=np.round(len(res.y) / 10).astype(np.int16)
).raster(res)
else:
z = res
fig = go.Figure(go.Heatmap(
z=z, x=res.x.values, y=res.y.values,
hoverongaps=False,
colorscale=colorcet.rainbow, colorbar={'title': var}
))
fig.update_xaxes(title_text=self.dataset.x.long_name,
showline=False)
fig.update_yaxes(title_text=self.dataset.y.long_name,
showline=False)
fig.update_layout(width=900, height=900,
margin={'b': 0, 'l': 0, 'r': 0, 't': 0})
fig.show()
if savefig and filename is not None:
fig.write_image(f'{filename}.{fmt}')
if save and filename is not None:
np.save(filename, res, False)
return res
def get_max_map(self,
var: str,
plot: bool = True,
filename: Optional[P] = None,
save: bool = False,
savefig: bool = False,
fmt: str = 'jpeg') -> xr.DataArray:
"""Gets the map of (temporal) max values for a given data_var.
Compute a map (a dataarray of dimension N * M) from a dataarray of
dimension t * N * M. Each pixel of this map is the max value of the
N * M t-vectors.
Args:
var: The name of the dataarray to use.
plot: A boolean flag that indicates if the figure should be
plotted or not.
filename: Optional; The path of the output product (a figure and/or
a netCDF file).
save: Optional; A boolean flag that indicates if the mean map
should be saved on disk or not.
savefig: Optional; A boolean flag that indicates if the figure
should be saved or not.
fmt: The format of the static image that is saved on disk. Can be
either "png", "jpeg", "webp", "svg" or "pdf".
Returns:
A map (a dataarray of dimension N * M) of max values for a given
data_var.
"""
res = self.dataset[var].max(dim='time')
if plot:
if len(res.x) + len(res.y) >= 9000:
z = ds.Canvas(
plot_width=np.round(len(res.x) / 10).astype(np.int16),
plot_height=np.round(len(res.y) / 10).astype(np.int16)
).raster(res)
else:
z = res
fig = go.Figure(go.Heatmap(
z=z, x=res.x.values, y=res.y.values,
hoverongaps=False,
colorscale=colorcet.rainbow, colorbar={'title': var}
))
fig.update_xaxes(title_text=self.dataset.x.long_name,
showline=False)
fig.update_yaxes(title_text=self.dataset.y.long_name,
showline=False)
fig.update_layout(width=900, height=900,
margin={'b': 0, 'l': 0, 'r': 0, 't': 0})
fig.show()
if savefig and filename is not None:
fig.write_image(f'{filename}.{fmt}')
if save and filename is not None:
np.save(filename, res, False)
return res
def plot_stats_maps(self,
data_vars: Union[str, List[str]] = 'all',
filename: P = None,
savefig: bool = False,
fmt: str = 'jpeg') -> None:
"""Plots a figure of stats (temporal mean/min/max) map (one per data_var).
For each data_var, create a figure composed of 3 subplots : a mean-,
min-, and max-map.
See 'get_mean_map', 'get_min_map', and 'get_max_map' for more
information about what the so-called maps are.
Args:
data_vars: The name of the dataarray to plot. If 'all', create a
figure for each dataarray (i.e. for each data_var in
data_vars).
filename: Optional; The path of the output figure.
savefig: Optional; A boolean flag that indicates if the figure
should be saved or not.
fmt: The format of the static image that is saved on disk. Can be
either "png", "jpeg", "webp", "svg" or "pdf".
"""
if data_vars == 'all':
data_vars = self.data_vars
else:
data_vars = [data_vars]
for var in data_vars:
mean_map = self.get_mean_map(var, False)
min_map = self.get_min_map(var, False)
max_map = self.get_max_map(var, False)
if len(self.dataset.x) + len(self.dataset.y) >= 9000:
mean_map = ds.Canvas(
plot_width=np.round(len(self.dataset.x)
/ 10).astype(np.int16),
plot_height=np.round(len(self.dataset.y)
/ 10).astype(np.int16)
).raster(mean_map)
min_map = ds.Canvas(
plot_width=np.round(len(self.dataset.x)
/ 10).astype(np.int16),
plot_height=np.round(len(self.dataset.y)
/ 10).astype(np.int16)
).raster(min_map)
max_map = ds.Canvas(
plot_width=np.round(len(self.dataset.x)
/ 10).astype(np.int16),
plot_height=np.round(len(self.dataset.y)
/ 10).astype(np.int16)
).raster(max_map)
fig = make_subplots(rows=1, cols=3, shared_yaxes=True,
subplot_titles=['mean', 'min', 'max'],
horizontal_spacing=0.05)
fig.add_trace(go.Heatmap(z=mean_map,
x=self.dataset.x.values,
y=self.dataset.y.values,
hoverongaps=False,
coloraxis='coloraxis'),
row=1, col=1)
fig.add_trace(go.Heatmap(z=min_map,
x=self.dataset.x.values,
y=self.dataset.y.values,
hoverongaps=False,
coloraxis='coloraxis'),
row=1, col=2)
fig.add_trace(go.Heatmap(z=max_map,
x=self.dataset.x.values,
y=self.dataset.y.values,
hoverongaps=False,
coloraxis='coloraxis'),
row=1, col=3)
fig.update_xaxes(title_text=self.dataset.x.long_name,
showline=False)
fig.update_yaxes(title_text=self.dataset.y.long_name,
showline=False)
fig.update_layout(coloraxis={'colorscale': colorcet.rainbow,
'colorbar': {'title': var}},
width=1350, height=450,
margin={'b': 0, 'l': 0, 'r': 0, 't': 50})
fig.show()
if savefig and filename is not None:
fig.write_image(f'{filename}.{fmt}')
def plot_hists(self,
data_vars: Union[str, List[str]] = 'all',
dates: Union[str, List[str]] = 'all',
plot: bool = True,
filename: Optional[P] = None,
fmt: str = 'jpeg') -> None:
"""Plots an histogram (per data_var, per date).
For each data_var, at each date, plots an histogram using the right
array of values.
Args:
data_vars: The name of the dataarray to plot. If 'all', create a
figure for each dataarray (i.e. for each data_var in
data_vars).
dates: The wanted date. If 'all', create a histogram for each date.
plot: A boolean flag that indicates if the figure should be
plotted or not.
filename: Optional; The path of the output figure.
fmt: The format of the static image that is saved on disk. Can be
either "png", "jpeg", "webp", "svg" or "pdf".
"""
if data_vars == 'all':
data_vars = self.data_vars
else:
data_vars = [data_vars]
if dates == 'all':
dates = self.dataset.time.values
else:
dates = [dates]
for var in data_vars:
hist_data, group_labels = [], []
for date in dates:
data = self.dataset[var].sel(time=str(date)).values.flatten()
hist_data.append(data[~np.isnan(data)])
group_labels.append(f'{var}_{str(date)}')
fig = ff.create_distplot(hist_data, group_labels)
if plot:
fig.show()
if filename is not None:
fig.write_image(f'{filename}_{var}.{fmt}')
def mask_time_series(ts_algo: TimeSeries,
ts_masks: Union[TimeSeries, List[TimeSeries]],
lst_mask_type: Union[str, List[str]],
inplace=False) -> Optional[TimeSeries]:
"""Masks time series of L3AlgoProducts.
Masks a TimeSeries made of L3AlgoProducts with one (or multiple ones)
made of L3MaskProducts. It can be used for instance to get rid of clouds
or to extract only water areas.
Args:
ts_algo: The TimeSeries to be masked.
ts_masks: The TimeSeries or list of TimeSeries to use as mask (/list of
masks).
lst_mask_type: The type of the input mask (or the list of the types of
input masks). Can either be 'IN' or 'OUT', indicating if the
corresponding mask is inclusive or exclusive.
inplace: If True, do operation inplace and return None.
Returns:
A masked TimeSeries.
"""
if not inplace:
ts_algo = deepcopy(ts_algo)
if isinstance(ts_masks, TimeSeries):
ts_masks = [ts_masks]
if isinstance(lst_mask_type, str):
lst_mask_type = [lst_mask_type]
# Get the shared bounding box (i.e. intersection)
x_min = max([ts_mask.x.values.min() for ts_mask in ts_masks]
+ [ts_algo.x.values.min()])
x_max = min([ts_mask.x.values.max() for ts_mask in ts_masks]
+ [ts_algo.x.values.max()])
y_min = max([ts_mask.y.values.min() for ts_mask in ts_masks]
+ [ts_algo.y.values.min()])
y_max = min([ts_mask.y.values.max() for ts_mask in ts_masks]
+ [ts_algo.y.values.max()])
# Clip masks with the previous bounding box
arr_masks = [ts_mask.dataset[ts_mask.title.split(' ', 1)[0]].sel(
x=slice(x_min, x_max), y=slice(y_max, y_min)).values
for ts_mask in ts_masks]
# Merge 'IN' masks (<=> what to include)
idx_in = [i for i, mask_type in enumerate(lst_mask_type)
if mask_type.upper() == 'IN']
mask_in = np.sum([arr_masks[i] for i in idx_in], axis=0)
# Merge 'OUT' masks (<=> what to exclude)
idx_out = [i for i, mask_type in enumerate(lst_mask_type)
if mask_type.upper() == 'OUT']
mask_out = np.sum([arr_masks[i] for i in idx_out], axis=0)
# Create the final mask
if not idx_in:
mask = np.where(mask_out == 0, True, False)
elif not idx_out:
mask = np.where(mask_in > 0, True, False)
else:
mask = np.where((mask_in > 0) & (mask_out == 0), True, False)
# Apply the previously computed mask to the product
for var in ts_algo.data_vars:
ts_algo.dataset = ts_algo.dataset.sel(x=slice(x_min, x_max),
y=slice(y_max, y_min))
ts_algo.dataset[var].values = np.where(mask,
ts_algo.dataset[var].values,
np.nan)
# Store masks' names
masks = []
dico = {'s2cloudless': 'cloudmask', 'waterdetect': 'watermask'}
for ts_mask, mask_type in zip(ts_masks, lst_mask_type):
mask = ts_mask.title.split(' ', 1)[0]
if mask in ('s2cloudless', 'waterdetect'):
version = ts_mask.dataset[mask].attrs['version']
ts_algo.dataset.attrs[dico[mask]] = f'{mask} ({version}) [{mask_type}]'
else:
masks.append(f'{mask} [{mask_type}]')
if masks:
ts_algo.dataset.attrs['masks'] = masks
if not inplace:
return ts_algo
return None
def cond_resample(arr, in_res, out_res):
"""See resample_band_array(...)."""
if out_res is None or in_res == out_res:
return arr
else:
return resample_band_array(arr, in_res, out_res, False)
| StarcoderdataPython |
3284335 | <filename>setup.py
from setuptools import setup
with open('README.rst') as f:
long_description = f.read()
setup(
name='csvtomd',
version='0.1.1',
description='Convert your CSV files into Markdown tables.',
long_description=long_description,
url='https://github.com/mplewis/csvtomd',
license='MIT',
author='<NAME>',
author_email='<EMAIL>',
py_modules=['csvtomd'],
entry_points={
'console_scripts': [
'csvtomd = csvtomd:main'
]
},
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Topic :: Text Processing :: Markup'
],
)
| StarcoderdataPython |
6665257 | x = ["ala", "marcin", "zygmunt"]
print(len(x))
# x.append("zbigniew")
print(len(x))
x.remove("marcin")
for i, y in enumerate(x):
print("Element i", i, ": ", y)
if "zbigniew" in x:
print("Jest zbigniew na liscie! :)")
else:
print("kogo z nami nie ma? Zbigniewa")
| StarcoderdataPython |
3266266 | # importing the required modules
import matplotlib.pyplot as plt
import numpy as np
# setting the x - coordinates
x = np.arange(0, 2*(np.pi)*5, 0.1)
# setting the corresponding y - coordinates
y = np.sin(x)
# potting the points
plt.plot(x, y, label ='sin(x)')
# naming the x axis
# naming the y axis
plt.ylabel('y(x)=sin(x)')
# giving a title to my graph
plt.title('Sine curve')
# show a legend on the plot
plt.legend()
# function to show the plot
plt.xlabel('x - axis')
plt.show() | StarcoderdataPython |
6438469 | <reponame>jcf94/FlexTensor<filename>flextensor/testing/others/hand-craft/schedule_shift_cuda.py<gh_stars>1-10
import tvm
import math
import torch
import numpy as np
from flextensor.nn import ShiftConv2d_nhwc
shift_conv2d_shape = [
# ShiftNet(https://arxiv.org/abs/1801.09392) with input size: 256*256
(1, 128, 128, 64, 3, 1),
# (1, 128, 128, 64, 3, 1),
(1, 64, 64, 128, 5, 1),
(1, 32, 32, 256, 3, 1),
(1, 16, 16, 512, 3, 1)
]
DEV_ID = 0
def schedule_shift_1_cuda(s, Img, KernelIndex, Output):
Pad = s[Output].op.input_tensors[1]
s[Pad].compute_inline()
write_cache = s.cache_write(Output, "local")
share_kernel = s.cache_read(s[write_cache].op.input_tensors[0], "shared", [write_cache])
share_pad = s.cache_read(s[write_cache].op.input_tensors[1], "shared", [write_cache])
n, h, w, c = s[Output].op.axis
# 1, 126, 126, 64
n_factors = [1, 1, 1, 1]
h_factors = [18, 1, 7, 1]
w_factors = [9, 7, 2, 1]
c_factors = [2, 1, 32, 1]
bn, ni = s[Output].split(n, nparts=n_factors[0])
vn, ni = s[Output].split(ni, nparts=n_factors[1])
nm, ni = s[Output].split(ni, nparts=n_factors[2])
bh, hi = s[Output].split(h, nparts=h_factors[0])
vh, hi = s[Output].split(hi, nparts=h_factors[1])
hm, hi = s[Output].split(hi, nparts=h_factors[2])
bw, wi = s[Output].split(w, nparts=w_factors[0])
vw, wi = s[Output].split(wi, nparts=w_factors[1])
wm, wi = s[Output].split(wi, nparts=w_factors[2])
bc, ci = s[Output].split(c, nparts=c_factors[0])
vc, ci = s[Output].split(ci, nparts=c_factors[1])
cm, ci = s[Output].split(ci, nparts=c_factors[2])
s[Output].reorder(bn, bh, bw, bc, vn, vh, vw, vc, nm, hm, wm, cm, ni, hi, wi, ci)
bx = tvm.thread_axis("blockIdx.x")
by = tvm.thread_axis("blockIdx.y")
bz = tvm.thread_axis("blockIdx.z")
vx = tvm.thread_axis("vthread")
vy = tvm.thread_axis("vthread")
vz = tvm.thread_axis("vthread")
tx = tvm.thread_axis("threadIdx.x")
ty = tvm.thread_axis("threadIdx.y")
tz = tvm.thread_axis("threadIdx.z")
s[Output].bind(bh, bz)
s[Output].bind(bw, by)
s[Output].bind(bc, bx)
s[Output].bind(vh, vz)
s[Output].bind(vw, vy)
s[Output].bind(vc, vx)
s[Output].bind(hm, tz)
s[Output].bind(wm, ty)
s[Output].bind(cm, tx)
s[write_cache].compute_at(s[Output], cm)
a, b, c, d = s[write_cache].op.axis
s[share_pad].compute_inline()
s[share_kernel].compute_at(s[write_cache], a)
# a, b, c, d = s[share_pad].op.axis
# pad_z, b = s[share_pad].split(b, nparts=h_factors[2])
# pad_y, c = s[share_pad].split(c, nparts=w_factors[2])
# pad_x, d = s[share_pad].split(d, nparts=c_factors[2])
# s[share_pad].bind(pad_z, tz)
# s[share_pad].bind(pad_y, ty)
# s[share_pad].bind(pad_x, tx)
fused = s[share_kernel].op.axis[0]
# pad_z, fused = s[share_kernel].split(fused, nparts=h_factors[2])
pad_y, fused = s[share_kernel].split(fused, nparts=w_factors[2])
pad_x, fused = s[share_kernel].split(fused, nparts=c_factors[2])
# s[share_kernel].bind(pad_z, tz)
s[share_kernel].bind(pad_y, ty)
s[share_kernel].bind(pad_x, tx)
s[Output].pragma(bn, 'auto_unroll_max_step', 200)
s[Output].pragma(bn, 'unroll_explicit', 1)
def schedule_shift_2_cuda(s, Img, KernelIndex, Output):
Pad = s[Output].op.input_tensors[1]
s[Pad].compute_inline()
write_cache = s.cache_write(Output, "local")
share_kernel = s.cache_read(s[write_cache].op.input_tensors[0], "shared", [write_cache])
share_pad = s.cache_read(s[write_cache].op.input_tensors[1], "shared", [write_cache])
n, h, w, c = s[Output].op.axis
# 1, 60, 60, 128
n_factors = [1, 1, 1, 1]
h_factors = [12, 1, 5, 1]
w_factors = [15, 1, 4, 1]
c_factors = [4, 1, 32, 1]
bn, ni = s[Output].split(n, nparts=n_factors[0])
vn, ni = s[Output].split(ni, nparts=n_factors[1])
nm, ni = s[Output].split(ni, nparts=n_factors[2])
bh, hi = s[Output].split(h, nparts=h_factors[0])
vh, hi = s[Output].split(hi, nparts=h_factors[1])
hm, hi = s[Output].split(hi, nparts=h_factors[2])
bw, wi = s[Output].split(w, nparts=w_factors[0])
vw, wi = s[Output].split(wi, nparts=w_factors[1])
wm, wi = s[Output].split(wi, nparts=w_factors[2])
bc, ci = s[Output].split(c, nparts=c_factors[0])
vc, ci = s[Output].split(ci, nparts=c_factors[1])
cm, ci = s[Output].split(ci, nparts=c_factors[2])
s[Output].reorder(bn, bh, bw, bc, vn, vh, vw, vc, nm, hm, wm, cm, ni, hi, wi, ci)
bx = tvm.thread_axis("blockIdx.x")
by = tvm.thread_axis("blockIdx.y")
bz = tvm.thread_axis("blockIdx.z")
vx = tvm.thread_axis("vthread")
vy = tvm.thread_axis("vthread")
vz = tvm.thread_axis("vthread")
tx = tvm.thread_axis("threadIdx.x")
ty = tvm.thread_axis("threadIdx.y")
tz = tvm.thread_axis("threadIdx.z")
s[Output].bind(bh, bz)
s[Output].bind(bw, by)
s[Output].bind(bc, bx)
s[Output].bind(vh, vz)
s[Output].bind(vw, vy)
s[Output].bind(vc, vx)
s[Output].bind(hm, tz)
s[Output].bind(wm, ty)
s[Output].bind(cm, tx)
s[write_cache].compute_at(s[Output], cm)
a, b, c, d = s[write_cache].op.axis
s[share_pad].compute_inline()
s[share_kernel].compute_at(s[write_cache], a)
# a, b, c, d = s[share_pad].op.axis
# pad_z, b = s[share_pad].split(b, nparts=h_factors[2])
# pad_y, c = s[share_pad].split(c, nparts=w_factors[2])
# pad_x, d = s[share_pad].split(d, nparts=c_factors[2])
# s[share_pad].bind(pad_z, tz)
# s[share_pad].bind(pad_y, ty)
# s[share_pad].bind(pad_x, tx)
fused = s[share_kernel].op.axis[0]
# pad_z, fused = s[share_kernel].split(fused, nparts=h_factors[2])
pad_y, fused = s[share_kernel].split(fused, nparts=w_factors[2])
pad_x, fused = s[share_kernel].split(fused, nparts=c_factors[2])
# s[share_kernel].bind(pad_z, tz)
s[share_kernel].bind(pad_y, ty)
s[share_kernel].bind(pad_x, tx)
s[Output].pragma(bn, 'auto_unroll_max_step', 200)
s[Output].pragma(bn, 'unroll_explicit', 1)
def schedule_shift_3_cuda(s, Img, KernelIndex, Output):
Pad = s[Output].op.input_tensors[1]
s[Pad].compute_inline()
write_cache = s.cache_write(Output, "local")
share_kernel = s.cache_read(s[write_cache].op.input_tensors[0], "shared", [write_cache])
share_pad = s.cache_read(s[write_cache].op.input_tensors[1], "shared", [write_cache])
n, h, w, c = s[Output].op.axis
# 1, 30, 30, 256
n_factors = [1, 1, 1, 1]
h_factors = [15, 1, 2, 1]
w_factors = [15, 1, 2, 1]
c_factors = [2, 1, 128, 1]
bn, ni = s[Output].split(n, nparts=n_factors[0])
vn, ni = s[Output].split(ni, nparts=n_factors[1])
nm, ni = s[Output].split(ni, nparts=n_factors[2])
bh, hi = s[Output].split(h, nparts=h_factors[0])
vh, hi = s[Output].split(hi, nparts=h_factors[1])
hm, hi = s[Output].split(hi, nparts=h_factors[2])
bw, wi = s[Output].split(w, nparts=w_factors[0])
vw, wi = s[Output].split(wi, nparts=w_factors[1])
wm, wi = s[Output].split(wi, nparts=w_factors[2])
bc, ci = s[Output].split(c, nparts=c_factors[0])
vc, ci = s[Output].split(ci, nparts=c_factors[1])
cm, ci = s[Output].split(ci, nparts=c_factors[2])
s[Output].reorder(bn, bh, bw, bc, vn, vh, vw, vc, nm, hm, wm, cm, ni, hi, wi, ci)
bx = tvm.thread_axis("blockIdx.x")
by = tvm.thread_axis("blockIdx.y")
bz = tvm.thread_axis("blockIdx.z")
vx = tvm.thread_axis("vthread")
vy = tvm.thread_axis("vthread")
vz = tvm.thread_axis("vthread")
tx = tvm.thread_axis("threadIdx.x")
ty = tvm.thread_axis("threadIdx.y")
tz = tvm.thread_axis("threadIdx.z")
s[Output].bind(bh, bz)
s[Output].bind(bw, by)
s[Output].bind(bc, bx)
s[Output].bind(vh, vz)
s[Output].bind(vw, vy)
s[Output].bind(vc, vx)
s[Output].bind(hm, tz)
s[Output].bind(wm, ty)
s[Output].bind(cm, tx)
s[write_cache].compute_at(s[Output], cm)
a, b, c, d = s[write_cache].op.axis
s[share_pad].compute_inline()
s[share_kernel].compute_at(s[write_cache], a)
# a, b, c, d = s[share_pad].op.axis
# pad_z, b = s[share_pad].split(b, nparts=h_factors[2])
# pad_y, c = s[share_pad].split(c, nparts=w_factors[2])
# pad_x, d = s[share_pad].split(d, nparts=c_factors[2])
# s[share_pad].bind(pad_z, tz)
# s[share_pad].bind(pad_y, ty)
# s[share_pad].bind(pad_x, tx)
fused = s[share_kernel].op.axis[0]
# pad_z, fused = s[share_kernel].split(fused, nparts=h_factors[2])
pad_y, fused = s[share_kernel].split(fused, nparts=w_factors[2])
pad_x, fused = s[share_kernel].split(fused, nparts=c_factors[2])
# s[share_kernel].bind(pad_z, tz)
s[share_kernel].bind(pad_y, ty)
s[share_kernel].bind(pad_x, tx)
s[Output].pragma(bn, 'auto_unroll_max_step', 200)
s[Output].pragma(bn, 'unroll_explicit', 1)
def schedule_shift_4_cuda(s, Img, KernelIndex, Output):
Pad = s[Output].op.input_tensors[1]
s[Pad].compute_inline()
write_cache = s.cache_write(Output, "local")
share_kernel = s.cache_read(s[write_cache].op.input_tensors[0], "shared", [write_cache])
share_pad = s.cache_read(s[write_cache].op.input_tensors[1], "shared", [write_cache])
n, h, w, c = s[Output].op.axis
# 1, 14, 14, 512
n_factors = [1, 1, 1, 1]
h_factors = [7, 1, 2, 1]
w_factors = [7, 1, 2, 1]
c_factors = [4, 1, 128, 1]
bn, ni = s[Output].split(n, nparts=n_factors[0])
vn, ni = s[Output].split(ni, nparts=n_factors[1])
nm, ni = s[Output].split(ni, nparts=n_factors[2])
bh, hi = s[Output].split(h, nparts=h_factors[0])
vh, hi = s[Output].split(hi, nparts=h_factors[1])
hm, hi = s[Output].split(hi, nparts=h_factors[2])
bw, wi = s[Output].split(w, nparts=w_factors[0])
vw, wi = s[Output].split(wi, nparts=w_factors[1])
wm, wi = s[Output].split(wi, nparts=w_factors[2])
bc, ci = s[Output].split(c, nparts=c_factors[0])
vc, ci = s[Output].split(ci, nparts=c_factors[1])
cm, ci = s[Output].split(ci, nparts=c_factors[2])
s[Output].reorder(bn, bh, bw, bc, vn, vh, vw, vc, nm, hm, wm, cm, ni, hi, wi, ci)
bx = tvm.thread_axis("blockIdx.x")
by = tvm.thread_axis("blockIdx.y")
bz = tvm.thread_axis("blockIdx.z")
vx = tvm.thread_axis("vthread")
vy = tvm.thread_axis("vthread")
vz = tvm.thread_axis("vthread")
tx = tvm.thread_axis("threadIdx.x")
ty = tvm.thread_axis("threadIdx.y")
tz = tvm.thread_axis("threadIdx.z")
s[Output].bind(bh, bz)
s[Output].bind(bw, by)
s[Output].bind(bc, bx)
s[Output].bind(vh, vz)
s[Output].bind(vw, vy)
s[Output].bind(vc, vx)
s[Output].bind(hm, tz)
s[Output].bind(wm, ty)
s[Output].bind(cm, tx)
s[write_cache].compute_at(s[Output], cm)
a, b, c, d = s[write_cache].op.axis
s[share_pad].compute_inline()
s[share_kernel].compute_at(s[write_cache], a)
# a, b, c, d = s[share_pad].op.axis
# pad_z, b = s[share_pad].split(b, nparts=h_factors[2])
# pad_y, c = s[share_pad].split(c, nparts=w_factors[2])
# pad_x, d = s[share_pad].split(d, nparts=c_factors[2])
# s[share_pad].bind(pad_z, tz)
# s[share_pad].bind(pad_y, ty)
# s[share_pad].bind(pad_x, tx)
fused = s[share_kernel].op.axis[0]
pad_z, fused = s[share_kernel].split(fused, nparts=h_factors[2])
pad_y, fused = s[share_kernel].split(fused, nparts=w_factors[2])
pad_x, fused = s[share_kernel].split(fused, nparts=c_factors[2])
s[share_kernel].bind(pad_z, tz)
s[share_kernel].bind(pad_y, ty)
s[share_kernel].bind(pad_x, tx)
s[Output].pragma(bn, 'auto_unroll_max_step', 200)
s[Output].pragma(bn, 'unroll_explicit', 1)
def evaluate(shape, schedule_func):
N, H, W, C, k, dilation = shape
stride = 1
Img = tvm.placeholder([N, H, W, C], dtype="float32")
KernelIndex = tvm.placeholder([C], dtype="int32")
Output = ShiftConv2d_nhwc(Img, KernelIndex, k, dilation, stride)
s = tvm.create_schedule(Output.op)
schedule_func(s, Img, KernelIndex, Output)
func = tvm.build(s, [Img, KernelIndex, Output], "cuda")
# print(func.imported_modules[0].get_source())
Img_torch = torch.rand([N, H, W, C], dtype=torch.float32)
Kernel_torch = torch.rand([C, k, k], dtype=torch.float32)
KernelIndex_torch = torch.argmax(Kernel_torch.reshape([C, -1]), dim=1)
paddings = [math.ceil(((stride - 1) * H - stride + dilation * (k - 1)) / 2),
math.ceil(((stride - 1) * W - stride + dilation * (k - 1)) / 2)]
image_height = H
image_width = W
out_height = math.floor((image_height + 2 * paddings[0]- dilation * (k - 1) - 1) / stride + 1)
out_width = math.floor((image_width + 2 * paddings[1] - dilation * (k - 1) - 1) / stride + 1)
output_shape = (N, out_height, out_width, C)
Output_torch = torch.zeros(output_shape, dtype=torch.float32)
ctx = tvm.context("cuda", DEV_ID)
Img_tvm = tvm.nd.array(Img_torch.numpy().astype(np.float32), ctx)
KernelIndex_tvm = tvm.nd.array(KernelIndex_torch.numpy().astype(np.int32), ctx)
Output_tvm = tvm.nd.array(Output_torch.numpy().astype(np.float32), ctx)
evaluator = func.time_evaluator(func.entry_name, ctx, number=10)
time_cost = evaluator(Img_tvm, KernelIndex_tvm, Output_tvm).mean * 1e3
return time_cost
def main():
print(evaluate(shift_conv2d_shape[0], schedule_shift_1_cuda))
print(evaluate(shift_conv2d_shape[1], schedule_shift_2_cuda))
print(evaluate(shift_conv2d_shape[2], schedule_shift_3_cuda))
print(evaluate(shift_conv2d_shape[3], schedule_shift_4_cuda))
if __name__ == "__main__":
main() | StarcoderdataPython |
1715424 | """supervisr core form fields"""
from django.forms import ChoiceField
STATUS_CHOICE_SUCCESS = 'success'
STATUS_CHOICE_WARNING = 'warning'
STATUS_CHOICE_ERROR = 'error'
class StatusField(ChoiceField):
"""Field to show one of three different statuses"""
minimum = None
recommended = None
current = None
below_minimum_message = 'Current below minimum requirement.'
def __init__(self, minimum=None, recommended=None, current=None, **kwargs):
kwargs.update({
'required': False
})
super().__init__(choices=(
(STATUS_CHOICE_SUCCESS, STATUS_CHOICE_SUCCESS),
(STATUS_CHOICE_WARNING, STATUS_CHOICE_WARNING),
(STATUS_CHOICE_ERROR, STATUS_CHOICE_ERROR),
), **kwargs)
self.minimum = minimum
self.recommended = recommended
self.current = current
def clean(self, value=''):
if self.current < self.minimum:
value = STATUS_CHOICE_ERROR
elif self.current < self.recommended:
value = STATUS_CHOICE_WARNING
else:
value = STATUS_CHOICE_SUCCESS
return super().clean(value)
| StarcoderdataPython |
9787453 | <reponame>AoWangPhilly/cryptsenal
from cryptsenal.autokey import AutoKey
import pytest
def test_encrypt():
plainText = "THEFISHSWIMSATMIDNIGHT"
keys = ["gesture", "highlight", "enemy", "cane", "executive"]
cipherTexts = ["zlwycjlldmrasaeelzagaf",
"apkmtanzpbtwfbepvjqszt",
"xuirglowbqezspuuvnbspw",
"vhrjbzlxeatkwbyadguokg",
"<KEY>"]
for key, cipherText in zip(keys, cipherTexts):
assert AutoKey(plainText, key).encrypt() == cipherText.upper()
def test_decrypt():
plainText = "THEFISHSWIMSATMIDNIGHT"
keys = ["gesture", "highlight", "enemy", "cane", "executive"]
cipherTexts = ["zlwycjlldmrasaeelzagaf",
"apkmtanzpbtwfbepvjqszt",
"<KEY>",
"<KEY>",
"<KEY>"]
for key, cipherText in zip(keys, cipherTexts):
assert AutoKey(cipherText, key).decrypt() == plainText
| StarcoderdataPython |
5055136 | from django import forms
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect, Http404
from homepage.models import *
from manager import models as mmod
from . import templater
def process_request(request):
'''Get products from the DB'''
users = mmod.User.objects.filter(is_active=True)
template_vars = {
'users': users,
}
return templater.render_to_response(request, 'userlookup.html', template_vars)
def process_request__search(request):
try:
users = mmod.User.objects.filter(first_name__icontains=request.POST.get('first', '')).filter(last_name__icontains=request.POST.get('last', '')).filter(phone__icontains=request.POST.get('phone', ''))
except User.DoesNotExist:
users = mmod.User.ojects.none()
if len(users)==0:
try:
users = mmod.User.objects.filter(first_name__icontains=request.POST.get('first', '')).filter(last_name__icontains=request.POST.get('last', ''))
except User.DoesNotExist:
users = mmod.User.objects.none()
if len(users)==0:
try:
users = mmod.User.objects.filter(phone__icontains=request.POST.get('phone', ''))
except User.DoesNotExist:
users = mmod.User.objects.none()
if len(users)==0:
try:
users = mmod.User.objects.filter(last_name__icontains=request.POST.get('last', ''))
except User.DoesNotExist:
users = mmod.User.objects.none()
if len(users)==0:
try:
users = mmod.User.objects.filter(first_name__icontains=request.POST.get('first', ''))
except User.DoesNotExist:
users = mmod.User.objects.none()
template_vars = {
'users': users,
}
return templater.render_to_response(request, 'userlookup.html', template_vars)
# class LookupForm(forms.Form):
# '''The Lookup form'''
# first = forms.CharField()
# last = forms.CharField()
# phone = forms.CharField()
| StarcoderdataPython |
6636195 | BRACKET_TYPE_CHAMPIONSHIP = "championship"
BRACKET_TYPE_CONSOLATION = "consolation"
GAME_TYPE_REGULAR = "REGULAR"
GAME_TYPE_PLAYOFF = "PLAYOFF"
GAME_TYPE_CONSOLATION = "CONSOLATION"
STORAGE_JSON = "json"
STORAGE_AIRTABLE = "airtable"
DATA_TYPE_GAMES = "games"
DATA_TYPE_TEAMS = "teams"
| StarcoderdataPython |
4993342 | <gh_stars>10-100
# (C) Copyright 2017- ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
#
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergovernmental organisation
# nor does it submit to any jurisdiction.
import os
from metview import bindings
PATH = os.path.dirname(__file__)
MAX_VALUE = 316.06060791015625
SEMI_EQUATOR = 20001600.0
MAX_SQRT_GPT = 16.867127793433
MAX_GPT = 284.5
def file_in_testdir(filename):
return os.path.join(PATH, filename)
def test_push_number():
bindings.lib.p_push_number(5)
bindings.lib.p_push_number(4)
def test_dict_to_pushed_request():
dict = {
"param1": True,
"param2": False,
"param3": 10,
"param4": 10.5,
"param5": "metview",
"param6": ["1", "2", "3"],
}
bindings.dict_to_pushed_args(dict)
def test_bind_functions():
namespace = {}
bindings.bind_functions(namespace, module_name="metview")
result = namespace["dictionary"]
assert "dictionary" in namespace
assert result.__name__ == result.__qualname__ == "dictionary"
assert result.__module__ == "metview"
def test_lists_as_input():
my_list = [1, 5, 6]
assert bindings.count(my_list) == 3
def test_tuples_as_input():
my_tuple = [1, 0, 5, 6]
assert bindings.count(my_tuple) == 4
| StarcoderdataPython |
1857782 | from annolid.gui.widgets.extract_frame_dialog import ExtractFrameDialog
from annolid.gui.widgets.convert_coco_dialog import ConvertCOODialog
from annolid.gui.widgets.train_model_dialog import TrainModelDialog
from annolid.gui.widgets.track_dialog import TrackDialog
from annolid.gui.widgets.glitter2_dialog import Glitter2Dialog
from annolid.gui.widgets.progressing_dialog import ProgressingWindow
from annolid.gui.widgets.quality_control_dialog import QualityControlDialog
| StarcoderdataPython |
6534319 | '''
This file is part of PM4Py (More Info: https://pm4py.fit.fraunhofer.de).
PM4Py is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PM4Py is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PM4Py. If not, see <https://www.gnu.org/licenses/>.
'''
from pm4py.objects.bpmn.obj import BPMN
def reduce_xor_gateways(bpmn_graph, parameters=None):
"""
Reduces the number of XOR gateways in the diagram
Parameters
------------
bpmn_graph
BPMN graph
parameters
Parameters
Returns
------------
bpmn_graph
(possibly reduced) BPMN graph
"""
if parameters is None:
parameters = {}
changed = True
while changed:
changed = False
outgoing_edges = None
incoming_edges = None
outgoing_edges = {}
incoming_edges = {}
for flow in bpmn_graph.get_flows():
source = flow.get_source()
target = flow.get_target()
if source not in outgoing_edges:
outgoing_edges[source] = set()
outgoing_edges[source].add(flow)
if target not in incoming_edges:
incoming_edges[target] = set()
incoming_edges[target].add(flow)
nodes = list(bpmn_graph.get_nodes())
for node in nodes:
if isinstance(node, BPMN.ExclusiveGateway):
if node in outgoing_edges and node in incoming_edges and len(outgoing_edges[node]) == 1 and len(
incoming_edges[node]) == 1:
changed = True
source_node = None
target_node = None
for flow in incoming_edges[node]:
source_node = flow.get_source()
if flow in bpmn_graph.get_flows():
bpmn_graph.remove_flow(flow)
for flow in outgoing_edges[node]:
target_node = flow.get_target()
if flow in bpmn_graph.get_flows():
bpmn_graph.remove_flow(flow)
if node in bpmn_graph.get_nodes():
bpmn_graph.remove_node(node)
bpmn_graph.add_flow(BPMN.Flow(source_node, target_node))
break
return bpmn_graph
def apply(bpmn_graph, parameters=None):
"""
Reduce the complexity of a BPMN graph by removing useless elements
Parameters
------------
bpmn_graph
BPMN graph
parameters
Parameters
Returns
------------
bpmn_graph
(possibly reduced) BPMN graph
"""
if parameters is None:
parameters = {}
bpmn_graph = reduce_xor_gateways(bpmn_graph, parameters=parameters)
return bpmn_graph
| StarcoderdataPython |
8133800 | <filename>mysockpool/exceptions.py
# coding=utf-8
"""
Copyright (c) 2018-present, Ant Financial Service Group
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Original Copyright 2008-2016 <NAME> and contributors
(see https://github.com/urllib3/urllib3/blob/master/CONTRIBUTORS.txt)
under the MIT license (https://opensource.org/licenses/MIT).
------------------------------------------------------
File Name : exceptions
"""
class MysockpoolError(Exception):
"Base exception for errors caused within a pool."
def __init__(self, pool, message):
self.pool = pool
super(MysockpoolError, self).__init__(self, "%s: %s" % (pool, message))
def __reduce__(self):
# For pickling purposes.
return self.__class__, (None, None)
class EmptyPoolError(MysockpoolError):
"Raised when a pool runs out of connections and no more are allowed."
pass
class ClosedPoolError(MysockpoolError):
"Raised when a request enters a pool after the pool has been closed."
pass
class LocationValueError(ValueError, MysockpoolError):
"Raised when there is something wrong with a given URL input."
pass
class SocketValueError(ValueError, MysockpoolError):
"Raised when socket is unable to register in selector."
| StarcoderdataPython |
11348539 | # ##############################################################################
# This file is part of df_config #
# #
# Copyright (C) 2020 <NAME> <<EMAIL>> #
# All Rights Reserved #
# #
# You may use, distribute and modify this code under the #
# terms of the (BSD-like) CeCILL-B license. #
# #
# You should have received a copy of the CeCILL-B license with #
# this file. If not, please visit: #
# https://cecill.info/licences/Licence_CeCILL-B_V1-en.txt (English) #
# or https://cecill.info/licences/Licence_CeCILL-B_V1-fr.txt (French) #
# #
# ##############################################################################
# noinspection PyClassHasNoInit,PyAbstractClass
import os
import subprocess
from pathlib import Path
from django.conf import settings
if settings.USE_PIPELINE:
# noinspection PyPackageRequirements,PyUnresolvedReferences
from pipeline.compressors import CompressorBase, SubProcessCompressor
# noinspection PyPackageRequirements,PyUnresolvedReferences
from pipeline.compilers import CompilerBase
# noinspection PyPackageRequirements,PyUnresolvedReferences
from pipeline.storage import PipelineManifestStorage, PipelineMixin
else:
CompressorBase = object
CompilerBase = object
SubProcessCompressor = object
PipelineManifestStorage = None
PipelineMixin = None
if settings.USE_WHITENOISE:
# noinspection PyPackageRequirements,PyUnresolvedReferences
from whitenoise.storage import CompressedManifestStaticFilesStorage
else:
CompressedManifestStaticFilesStorage = None
class RcssCompressor(CompressorBase):
"""
CSS compressor based on the Python library slimit
(https://github.com/ndparker/rcssmin).
"""
def filter_css(self, css):
raise NotImplementedError
def filter_js(self, js):
raise NotImplementedError
# noinspection PyMethodMayBeStatic
def compress_css(self, css):
# noinspection PyUnresolvedReferences,PyPackageRequirements
from rcssmin import cssmin
return cssmin(css)
class CssNanoCompressor(SubProcessCompressor):
def compress_css(self, css):
command = [settings.CSSNANO_BINARY] + settings.CSSNANO_ARGUMENTS
return self.execute_command(command, css)
def filter_css(self, css):
raise NotImplementedError
def filter_js(self, js):
raise NotImplementedError
class TerserCompressor(SubProcessCompressor):
def compress_js(self, js):
command = [settings.TERSER_BINARY, settings.TERSER_ARGUMENTS, "--"]
if self.verbose:
command += ["--verbose"]
return self.execute_command(command, js)
def filter_css(self, css):
raise NotImplementedError
def filter_js(self, js):
raise NotImplementedError
# noinspection PyClassHasNoInit
class PyScssCompiler(CompilerBase):
""" SASS (.scss) compiler based on the Python library pyScss.
(http://pyscss.readthedocs.io/en/latest/ ).
However, this compiler is limited to SASS 3.2 and cannot compile modern projets like Bootstrap 4.
Please use :class:`pipeline.compilers.sass.SASSCompiler` if you use modern SCSS files.
"""
output_extension = "css"
# noinspection PyMethodMayBeStatic
def match_file(self, filename):
return filename.endswith(".scss") or filename.endswith(".sass")
# noinspection PyUnusedLocal
def compile_file(self, infile, outfile, outdated=False, force=False):
# noinspection PyUnresolvedReferences,PyUnresolvedReferences,PyPackageRequirements
from scss import Compiler
root = Path(os.path.abspath(settings.STATIC_ROOT))
compiler = Compiler(root=root, search_path=("./",))
css_content = compiler.compile(infile)
with open(outfile, "w") as fd:
fd.write(css_content)
# noinspection PyUnresolvedReferences
if self.verbose:
print(css_content)
# noinspection PyClassHasNoInit
class TypescriptCompiler(CompilerBase):
""" TypeScript (.ts) compiler using "tsc".
(https://www.typescriptlang.org ).
"""
output_extension = "js"
# noinspection PyMethodMayBeStatic
def match_file(self, filename):
return filename.endswith(".ts")
# noinspection PyMethodMayBeStatic,PyUnusedLocal
def compile_file(self, infile, outfile, outdated=False, force=False):
# noinspection PyPackageRequirements,PyUnresolvedReferences
from pipeline.exceptions import CompilerError
command = (
[settings.TYPESCRIPT_BINARY]
+ settings.TYPESCRIPT_ARGUMENTS
+ ["-out", outfile, infile]
)
try:
p = subprocess.Popen(
command,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, __ = p.communicate(b"")
if p.returncode != 0:
raise CompilerError(
"Unable to execute TypeScript",
command=command,
error_output=stdout.decode(),
)
except Exception as e:
raise CompilerError(e, command=command, error_output=str(e))
if PipelineManifestStorage:
class NicerPipelineCachedStorage(PipelineManifestStorage):
""" display a better exception"""
def hashed_name(self, name, content=None, filename=None):
try:
return super().hashed_name(name, content=content)
except ValueError as e:
raise ValueError(
"%s. Did you run the command 'collectstatic'?" % e.args[0]
)
else:
NicerPipelineCachedStorage = None
if PipelineMixin and CompressedManifestStaticFilesStorage:
class PipelineCompressedManifestStaticFilesStorage(
PipelineMixin, CompressedManifestStaticFilesStorage
):
"""mix django-pipeline and whitenoise"""
pass
else:
PipelineCompressedManifestStaticFilesStorage = None
| StarcoderdataPython |
8122686 | <gh_stars>0
from multiprocessing.dummy import Pool as ThreadPool
import requests
import itertools
def get_request(requests_session, urls):
try:
return requests_session.get(urls, timeout=3)
except:
return
def get_request_multi(urls):
try:
return requests.get(urls, timeout=3)
except:
return
# https://stackoverflow.com/questions/2846653/how-can-i-use-threading-in-python
def parse_url_with_parallel(urls):
requests_session= requests.Session()
# Make the Pool of workers
pool = ThreadPool(len(urls)) # this seems to be more optimised
# Open the URLs in their own threads
# and return the results
results = pool.starmap(get_request, zip(itertools.repeat(requests_session), urls)) # starmap - https://stackoverflow.com/questions/5442910/how-to-use-multiprocessing-pool-map-with-multiple-arguments
# Close the pool and wait for the work to finish
pool.close()
pool.join()
return results
def generate_class_url(course_code:str, term:str, year:str):
if year != "2021":
return "https://nss.cse.unsw.edu.au/sitar/classes" + f"{year}" + f"/{course_code}_{term}.html"
return "http://classutil.unsw.edu.au/" + course_code + "_" + term + ".html"
def get_faculty_data():
engineering = ["ACIV" ,"AERO" ,"AVEN" ,"BINF" ,"BIOM" ,"CEIC" ,"CHEN" ,"COMP" ,"CVEN" ,"ELEC" ,"ENGG" ,
"FOOD" ,"FUEL" ,"GENE" ,"GENS" ,"GENZ" ,"GSOE" , "INDC" ,"MANF" ,"MATS" ,"MECH" ,"MINE" ,"MMAN" ,"MNNG" ,
"MTRN" ,"NANO" ,"NAVL" ,"PHTN" ,"POLY" ,"PTRL" ,"SAFE" ,"SENG" ,"SOLA" ,"TELE" ,"TEXT" ,"WOOL" ,"ZEIT" ,"ZINT"]
arts = ["ARTS", "ASIA", "AUST", "COFA", "COMD", "DANC", "EDST", "ENGL", "EURO", "EXPA", "FILM", "GEND",
"GENT", "GLST", "HUMS", "IRSH", "ITAL", "JWST", "MDCM", "MDIA", "MEFT", "MUSC", "SAHT", "SART",
"SDES", "SLST", "SOMA", "SPRC", "THST", "WOMS"]
environment = ["ARCH", "BENV", "BLDG", "GEOH", "GSBE", "IDES", "INTA", "LAND", "MUPS", "PLAN", "SUSD", "UDES"]
science = ["AENG", "AGOC", "AHIS", "ANAM", "APHY", "APOL", "ATSI", "BABS", "BIOC", "BIOC", "BIOD",
"BSSM", "CHEM", "CRIM", "HESC", "HIST", "HPSC", "HPST", "INOV", "INST", "LIFE",
"MATH", "MICM", "MICR", "NEUR", "OPTM", "PATM", "PECO", "PHAR", "PHPH", "PHSL", "PHYS",
"POLS", "PROR", "PSYC", "SCIF", "SCIF", "SCOM", "SCTS", "SESC", "SLSP", "SOCA", "SOCF",
"SOCW", "SOMS", "SRAP", "VISN", "ZHSS", "ZHSS", "ZPEM"]
medicine = ["SURG", "MEDM", "MFAC", "PDCS", "MEED", "RUHE", "GENM", "MDSG",
"PHCM", "NEUR", "PDCS", "CMED", "MDCN", "HEAL"]
law = ["HPSC", "LEGT", "GENC", "GENC", "TABL", "LAWS", "JURD", "GENL",
"LEGT", "JURD", "ATAX"]
business = ["ACCT", "AECM", "COMM", "ECON", "FINS", "GBAT", "GENC", "GSOE", "IBUS", "IROB", "LEGT",
"MFIN", "MGMT", "MNGT", "REGZ", "STRE", "TABL", "XACC", "XBUS", "XFIN", "XINT", "XMKM", "XPRO",
"ZBUS", "ZGEN", "ZINT"]
res = engineering + environment + arts + science + medicine + law + business
return list(set(res))
def get_urls():
res = []
with open("url_lists.txt", "r") as f:
lines = f.readlines()
for n, l in enumerate(lines):
try:
s = "http://"
s += l.split()[1].rstrip()
if any(i in s for i in ["google", "blogspot"]):
continue
res.append(s)
except:
pass
return res
# urls = [
# 'http://www.python.org',
# 'http://www.python.org/about/',
# 'http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html',
# 'http://www.python.org/doc/',
# 'http://www.python.org/download/',
# 'http://www.python.org/getit/',
# 'http://www.python.org/community/',
# 'https://wiki.python.org/moin/',
# ]
urls = []
urls = get_urls()
#print(urls[:20])
# data = get_faculty_data()
# print(len(data))
# year = "2020"
# for term in ["U1", "T1", "T2", "T3"]:
# for code in data:
# urls.append( generate_class_url(code, term, year))
# print(len(urls))
# import sys
# sys.exit(1)
import time
start_time = time.time()
# res = parse_url_with_parallel(urls)
###
if __name__ == "__main__":
from multiprocessing import Pool
import itertools
p = Pool(processes=4)
#requests_session = requests.Session()
try:
res = p.map(get_request_multi, urls)
except Exception as e:
print(e)
import sys
sys.exit(1)
###
l = [i for i in res if i]
print (len(l))
#print(res)
print("--- %s seconds ---" % (time.time() - start_time))
| StarcoderdataPython |
5077449 | from logging import getLogger
import json
# logger = getLogger(__name__)
logger = getLogger('app')
def info(scid, res, parm, msg):
if res is not None:
response = str(res.status_code) + ':' + res.reason
url = ', ' + res.url
logger.info(response + ', ' + scid + ', ' + msg + url)
elif parm is not None:
logger.info(scid + ', ' + msg + parm)
else:
logger.info(scid + ', ' + msg)
def debug(scid, msg, res, param):
if param is not None:
logger.debug(scid + ' Message:' + msg + ' Response:' + res, param)
else:
logger.error(scid + ' Message:' + msg)
def error(scid, res, ex):
if res is not None and ex is not None:
response = str(res.status_code) + ':' + res.reason
logger.error(response + ', ' + scid + ', ' + str(ex))
if res is not None and ex is None:
response = str(res.status_code) + ':' + res.reason
logger.error(response + ', ' + scid)
else:
logger.error(scid + ', ' + str(ex))
def errorMessage(res, ex):
if not res and not ex:
errormsg = apiErrorMessage(res)
return errormsg + str(ex)
elif not res and ex:
errormsg = apiErrorMessage(res)
return errormsg
else:
return str(ex)
def apiErrorMessage(res):
response = json.loads(res.text)
apimsg = response.get('error')
errormsg = str(res.status_code) + ':' + res.reason + ' ' + apimsg
return errormsg
| StarcoderdataPython |
271008 | <gh_stars>0
import glob
import numpy as np
from sklearn.metrics import roc_curve, auc
import matplotlib.pyplot as plt
def read_scoring_matrix(filename):
with open(filename,'r') as f:
line = f.readline()
while(line.startswith("#")): line = f.readline()
#This will be the row containing the amino acid labels. Make a dictionary mapping the amino acid letter to the index of the scoring matrix
aa_labels = list(line.split())
aa_dict = {}
for aa in aa_labels: aa_dict[aa] = aa_labels.index(aa)
#Convert every row from a string into a list of integers, then add it to a numpy array to create the scoring matrix
matrix = np.zeros((len(aa_labels),len(aa_labels)))
for i in range(len(aa_labels)): matrix[i,:] = list(map(int, f.readline().split()))
return matrix, aa_dict, aa_labels
def read_sequences(cwd):
filenames = glob.glob(cwd + '/sequences/*.fa')
sequences = {}
for filename in filenames:
name = filename[-22:] #e.g.: name = 'sequences/prot-0014.fa'
with open(filename, 'r') as f:
seq = ''
f.readline() #skips header row
for line in f.readlines(): seq += line.strip()
seq = seq.upper()
sequences[name] = seq
return sequences
def read_pairs(filename):
pairs = []
with open(filename, 'r') as f:
for line in f: pairs.append(line.split())
return pairs
def prepare_output(filename):
with open(filename, 'w') as f: f.write("")
return filename
def write_alignment(pair,alignment,score,filename,pospairs,negpairs):
with open(filename, 'a') as f:
f.write("#New Alignment\n")
f.write("Sequence 1: %s\n" %pair[0])
f.write("Sequence 2: %s\n" %pair[1])
f.write("%s\n" %alignment[0])
f.write("%s\n" %alignment[1])
f.write("Score = %f\n" %score)
return
def make_roc_curve(pos_scores,neg_scores,matrix):
#Create a label array, y, with 1's for positives and 0's for negatives, and a scoring array with the scores for each labeled pair.
y = np.array([1]*len(pos_scores)+[0]*len(neg_scores))
scores = np.array(pos_scores + neg_scores)
#Using scikit-learn's roc_curve and auc, calculate the parameters necessary for an ROC curve, and use them to compute the area under the curve
fpr,tpr,thresholds = roc_curve(y,scores)
roc_auc = auc(fpr, tpr)
#plot and save an ROC curve.
plt.figure()
plt.title('Receiver Operating Characteristic, %s' %matrix)
plt.plot(fpr,tpr, 'b', label='AUC = %0.2f'% roc_auc)
plt.legend(loc='lower right')
plt.plot([0,1],[0,1],'r--')
plt.xlim([0,1])
plt.ylim([0,1])
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
plt.savefig('roc_%s.png' %matrix)
return
| StarcoderdataPython |
6431838 | """ Interface layer for user authentication/authorization """
import hug
from api.transport.auth import authentication
api = hug.API(__name__)
@hug.get('/', api=api, requires=authentication)
def get_user(user: hug.directives.user):
return 'hello {}!'.format(user)
| StarcoderdataPython |
110340 | <reponame>nguyenthieu95/machine_learning
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 15 10:17:15 2018
@author: thieunv
Magic method: https://www.youtube.com/watch?v=3ohzBxoFHAY
"""
class Employee:
# class variable
raise_amount = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + "." + last + "@company.com"
def fullname(self):
return "{} {}".format(self.first, self.last)
def apply_raise(self):
self.pay = int(self.pay * self.raise_amount)
def __repr__(self): # representation method
return "Employee('{}', '{}', '{}')".format(self.first, self.last, self.pay)
def __str__(self): # string method, stronger than __repr__
return "{} - {}".format(self.fullname(), self.email)
def __add__(self, other):
return self.pay + other.pay
def __len__(self):
return len(self.fullname())
# Instance
e1 = Employee("thieu", "nguyen", 5000)
e2 = Employee("tien", "pham", 3000)
print e1
print repr(e2) # Same: print e2.__repr__()
print str(e2) # Same: print e2.__str__()
## Add method
print(1 + 2)
print(int.__add__(1, 2))
print(str.__add__('a', 'b'))
print(e1 + e2) # Understand how to add using __add__
## Len method
print(len('test'))
print('test'.__len__())
print(len(e1))
| StarcoderdataPython |
3419879 | <reponame>mttcnnff/bytewax
import time
import bytewax
def slow(x):
print("start slow")
# time.sleep(5) # Works in parallel.
# bytewax.sleep_release_gil(5) # Works in parallel.
bytewax.sleep_keep_gil(5) # Does not.
print("stop slow")
return x
def busy(x):
print("start busy")
y = 0
for i in range(50000000):
y += 1
print("stop busy")
return x
def output(x):
return x.replace("in", "out")
ec = bytewax.Executor()
flow = ec.Dataflow(enumerate(["in1", "in2", "in3", "in4", "in5"]))
flow.inspect(print)
# flow.map(slow)
flow.map(busy)
flow.map(output)
flow.inspect(print)
if __name__ == "__main__":
ec.build_and_run()
| StarcoderdataPython |
5056391 | <filename>apps/single_cam_detector/scripts/publish_event.py
#!/bin/bash
import redis
import time
HOST = 'localhost'
PORT = '6379'
CHANNEL = 'motion-detection-channel'
if __name__ == '__main__':
r = redis.Redis(host=HOST, port=PORT)
pub = r.publish(
channel=CHANNEL,
message='Motion detected!'
)
| StarcoderdataPython |
6445567 | """
Unit testing of the piserverstatusd.py module
To run:
nosetests -s test_piserverstatusd.py
"""
import unittest
import piserverstatusd
class PiServerStatusdTestCase(unittest.TestCase):
def setUp(self):
self.daemon = piserverstatusd.StatusDaemon('/tmp/test_piserverstatusd.pid')
def test_mps_to_kt(self):
speed = 100
self.assertAlmostEqual(self.daemon.mps_to_kt(speed), 51.44, 2)
def test_cloud(self):
self.assertEqual('', self.daemon.cloud(0))
self.assertEqual('FEW', self.daemon.cloud(12))
self.assertEqual('SCT', self.daemon.cloud(30))
self.assertEqual('BKN', self.daemon.cloud(70))
self.assertEqual('OVC', self.daemon.cloud(99))
def test_dewpoint(self):
self.assertAlmostEqual(self.daemon.dewpoint(40, 50), 27.59, 2)
def test_metar_dewpoint(self):
test_values = [
{'t': 40, 'rh': 50, 'dp': '28'},
{'t': -10, 'rh': 66, 'dp': 'M15'},
{'t': 25, 'rh': 100, 'dp': '25'},
{'t': 10, 'rh': 50, 'dp': '00'}
]
for vals in test_values:
self.assertEqual(vals['dp'], self.daemon.metar_dewpoint(vals['t'], vals['rh']))
def test_metar_temperature(self):
test_values = [
(0, '00'), (-1, 'M01'), (-0.51, 'M01'), (-0.5, 'M00'), (15, '15')
]
for vals in test_values:
self.assertEqual(vals[1], self.daemon.metar_temperature(vals[0]))
def test_metar_wind(self):
test_values = [
{'speed': 20, 'deg': 320, 'result': '32010KT'},
{'speed': 2, 'deg': 320, 'result': '00001KT'},
{'speed': 50, 'deg': 90, 'gust': 85, 'result': '09025G43KT'}
]
for vals in test_values:
self.assertEqual(vals['result'], self.daemon.metar_wind(vals))
def test_metar_pressure(self):
test_values = [
{'press': 1043, 'sea_level': 1046, 'result': 'Q1046 QFE1043'},
{'press': 1043, 'sea_level': None, 'result': 'QFE1043'},
{'press': None, 'sea_level': 1046, 'result': 'Q1046'},
{'press': 997, 'sea_level': 999, 'result': 'Q0999 QFE0997'},
]
for vals in test_values:
self.assertEqual(vals['result'], self.daemon.metar_pressure(vals))
def test_metar_weather(self):
self.assertEqual('SQ TSRA', self.daemon.metar_weather([771, 201]))
self.assertEqual('', self.daemon.metar_weather(800))
self.assertEqual('TSRA', self.daemon.metar_weather([201, 800]))
| StarcoderdataPython |
11328681 | <reponame>jfroche/groovylint
#!/usr/bin/env python3
#
# Copyright (c) 2019 Ableton AG, Berlin. All rights reserved.
#
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file.
"""A script to download JAR file dependencies for run_codenarc.py."""
import argparse
import logging
import os
import zipfile
import requests
def download_file(url, output_dir, force=False):
"""Download a file from a URL to the download directory."""
output_file_name = url.split('/')[-1]
output_file_path = os.path.join(output_dir, output_file_name)
if force:
try:
os.remove(output_file_path)
except FileNotFoundError:
pass
elif os.path.exists(output_file_path):
logging.debug('%s already exists, skipping download', output_file_path)
return output_file_path
logging.debug('Downloading %s to %s', url, output_file_path)
response = requests.get(url, stream=True)
response.raise_for_status()
with open(output_file_path, mode='wb') as output_file:
for chunk in response.iter_content(chunk_size=256):
output_file.write(chunk)
logging.info('Downloaded %s', output_file_name)
return output_file_path
def fetch_jars(args):
"""Fetch JAR file dependencies."""
if not os.path.exists(args.output_dir):
os.mkdir(args.output_dir)
jar_urls = [
(
'https://github.com/CodeNarc/CodeNarc/releases/download'
f'/v{args.codenarc_version}/CodeNarc-{args.codenarc_version}.jar'
),
(
'https://github.com/dx42/gmetrics/releases/download'
f'/v{args.gmetrics_version}/GMetrics-{args.gmetrics_version}.jar'
),
(
f'https://repo1.maven.org/maven2/org/slf4j/slf4j-api/{args.slf4j_version}'
f'/slf4j-api-{args.slf4j_version}.jar'
),
(
f'https://repo1.maven.org/maven2/org/slf4j/slf4j-simple/{args.slf4j_version}'
f'/slf4j-simple-{args.slf4j_version}.jar'
),
]
for url in jar_urls:
verify_jar(download_file(url, args.output_dir, args.force))
def parse_args():
"""Parse arguments from the command line."""
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument(
'--codenarc-version', help='Version of CodeNarc to download.', required=True
)
arg_parser.add_argument(
'--gmetrics-version', help='Version of GMetrics to download.', required=True
)
arg_parser.add_argument(
'--slf4j-version', help='Version of SLF4J to download.', required=True
)
arg_parser.add_argument(
'-f',
'--force',
action='store_true',
help='Download JAR files regardless of whether or not they already exist.',
)
arg_parser.add_argument(
'-o',
'--output-dir',
default=os.path.abspath(os.path.curdir),
help='Directory to save JAR files to.',
)
arg_parser.add_argument(
'-v', '--verbose', action='store_true', help='Show verbose output.'
)
args = arg_parser.parse_args()
log_level = logging.DEBUG if args.verbose else logging.INFO
logging.basicConfig(level=log_level)
return args
def verify_jar(file_path):
"""Verify that a file is a valid JAR file."""
logging.debug('Verifying %s', file_path)
with zipfile.ZipFile(file_path, 'r') as jar_file:
if 'META-INF/MANIFEST.MF' not in jar_file.namelist():
raise ValueError(f'{file_path} does not appear to be a valid JAR')
if __name__ == '__main__':
fetch_jars(parse_args())
| StarcoderdataPython |
5034712 | #
# PyANC350v4 example file
# by <NAME>, adapted from pyanc-example.py by <NAME>
#
from pyanc350.v4 import discover, Positioner
import time
ax = {'x': 0, 'y': 1, 'z': 2}
# define a dict of axes to make things simpler
dev_count = discover()
if dev_count != 0:
anc = Positioner(0)
# instantiate positioner as anc
print('-------------------------------------------------------------')
print('capacitances:')
for axis in sorted(ax.keys()):
print(axis, anc.measureCapacitance(ax[axis]))
anc.setFrequency(ax[axis], 200)
anc.setAmplitude(ax[axis], 45)
# print('-------------------------------------------------------------')
# print('setting static amplitude to 2V')
# anc.staticAmplitude(2000)
# #set staticAmplitude to 2V to ensure accurate positioning info
# staticAmplitude function does not exist in v4
print('-------------------------------------------------------------')
print('moving to x = 3mm')
anc.setAxisOutput(ax['x'], 1, 0)
anc.setTargetRange(ax['x'], 1e-6)
anc.setTargetPosition(ax['x'], 9e-3)
anc.startAutoMove(ax['x'], 1, 0)
# check what's happening
time.sleep(0.5)
moving = 1
target = 0
while target == 0:
connected, enabled, moving, target, eotFwd, eotBwd, error = anc.getAxisStatus(ax['x']) # find bitmask of status
if target == 0:
print('axis moving, currently at', anc.getPosition(ax['x']))
elif target == 1:
print('axis arrived at', anc.getPosition(ax['x']))
anc.startAutoMove(ax['x'], 0, 0)
time.sleep(0.5)
print('and moving y:')
anc.setAxisOutput(ax['y'], 1, 0)
anc.setTargetRange(ax['y'], 1e-6)
anc.setTargetPosition(ax['y'], 8e-3)
anc.startAutoMove(ax['y'], 1, 0)
time.sleep(0.5)
target = 0
while target == 0:
connected, enabled, moving, target, eotFwd, eotBwd, error = anc.getAxisStatus(ax['y']) # find bitmask of status
if target == 0:
print('axis moving, currently at', anc.getPosition(ax['y']))
elif target == 1:
print('axis arrived at', anc.getPosition(ax['y']))
anc.startAutoMove(ax['y'], 0, 0)
time.sleep(0.5)
print('-------obtaining all possible gettable values for x---------')
# get every possible gettable value
print('getActuatorName', anc.getActuatorName(ax['x']))
print('getActuatorType', anc.getActuatorType(ax['x']))
print('getAmplitude', anc.getAmplitude(ax['x']))
print('getAxisStatus', anc.getAxisStatus(ax['x']))
print('getDeviceConfig', anc.getDeviceConfig())
print('getDeviceInfo', anc.getDeviceInfo())
print('getFirmwareVersion', anc.getFirmwareVersion())
print('getFrequency', anc.getFrequency(ax['x']))
print('getPosition', anc.getPosition(ax['x']))
print('-------------------------------------------------------------')
print('testing \'functions for manual positioning\'')
anc.setFrequency(ax['x'], 50)
print('set frequency to 50Hz')
for i in range(30):
anc.startSingleStep(ax['x'], 0)
time.sleep(0.1)
print('arrived at:', anc.getPosition(ax['x']), 'after 30 pulses')
anc.startContinuousMove(ax['x'], 1, 0)
print('waiting 3 seconds...')
time.sleep(3)
anc.startContinuousMove(ax['x'], 0, 0)
print('and stopped at', anc.getPosition(ax['x']))
print('set frequency to 200Hz')
anc.setFrequency(ax['x'], 200)
anc.startContinuousMove(ax['x'], 1, 0)
print('waiting 3 seconds...')
time.sleep(3)
anc.startContinuousMove(ax['x'], 0, 0)
print('-------------------------------------------------------------')
print('closing connection...')
anc.disconnect()
print('-------------------------------------------------------------')
| StarcoderdataPython |
1959349 | class EventCounter(object):
def __init__(self):
self._active_counts = dict()
self._active_counts_meta = dict()
def event(self, segment_name, meta = None):
if segment_name not in self._active_counts:
self._active_counts[segment_name] = 0
self._active_counts[segment_name] += 1
if meta is not None:
if segment_name not in self._active_counts_meta:
self._active_counts_meta[segment_name] = []
self._active_counts_meta[segment_name].append(meta)
def __str__(self):
s = ''
for name, counts in self._active_counts.items():
s += f'{name} {counts} time(s). {"" if name not in self._active_counts_meta else f" Meta: {str(self._active_counts_meta[name])}" }\n'
return s | StarcoderdataPython |
5098799 | <gh_stars>0
by <NAME> Telegram: @AhmedoPlus
x-x-x ACCOUNT: <EMAIL>:Bubbles12
---CheckTime: 2021/02/14 03:13 AM
---ONLINE ID: JamesJonBerry
---COUNTRY: GB
---DATEOFBIRTH: 1994-08-18
---DEACTIVATION: Yes
---DEVICES: PS4[1]
---PLAYSTATION PLUS: PlayStation Plus: 12 Month Membership [12/30/2021]
---PAYMENT METHODS: [VISA 2021-8]
---BALANCE: £0.00
---HAS MORE TRANSACTIONS: NO
-------------------- Transactions --------------------
FUT 21 – FIFA Points 750 [4.99£][2021-02-10]
FUT 21 – FIFA Points 1600 [9.99£][2021-01-30]
FUT 21 – FIFA Points 1600 [9.99£][2020-11-18]
FUT 21 – FIFA Points 1600 [9.99£][2020-10-22]
FIFA 21 Standard Edition PS4™ & PS5™ [49.99£][2020-10-15]
PGA TOUR 2K21 [41.66£][2020-08-26]
South Park™: The Fractured but Whole™ - SEASON PASS [6.66£][2020-06-22]
Mafia II: Definitive Edition [20.82£][2020-06-22]
Madden NFL 20 [13.32£][2020-06-13]
NBA 2K20 [3.32£][2020-05-17]
Tennis World Tour [5.41£][2020-05-17]
Snooker 19 [12.49£][2020-05-11]
FIFA Points 250 [1.66£][2020-04-18]
FIFA Points 1050 [6.66£][2020-04-18]
FIFA Points 1050 [6.66£][2020-04-16]
STAR WARS Jedi: Fallen Order™ [29.16£][2020-04-07]
eFootball PES 2020 Standard Edition [13.32£][2020-04-07]
PLAYERUNKNOWN'S BATTLEGROUNDS [6.66£][2020-03-08]
FIFA Points 250 [1.66£][2020-02-14]
FIFA Points 250 [1.66£][2020-02-06]
FIFA Points 1050 [6.66£][2020-02-06]
Mafia III [7.49£][2020-01-03]
FIFA Points 250 [1.66£][2019-12-26]
FIFA Points 250 [1.66£][2019-12-26]
FIFA Points 2200 [13.32£][2019-12-26]
NBA 2K Playgrounds 2 [7.49£][2019-11-28]
Peggle 2 [8.32£][2019-11-05]
Call of Duty®: Modern Warfare® [49.99£][2019-11-03]
FIFA Points 1050 [6.66£][2019-10-30]
FIFA Points 1050 [6.66£][2019-10-04]
FIFA Points 250 [1.66£][2019-09-26]
FIFA Points 1050 [6.66£][2019-09-26]
EA SPORTS™ FIFA 20 Champions Edition [66.66£][2019-09-24]
FIFA Points 2,200 [13.32£][2019-07-29]
FIFA Points 100 [0.66£][2019-06-22]
FIFA Points 500 [3.32£][2019-06-22]
Grand Theft Auto: San Andreas [5.16£][2019-06-02]
The Warriors [5.16£][2019-06-02]
FIFA Points 1,600 [9.99£][2019-05-27]
NBA 2K19 20th Anniversary Edition [29.16£][2019-03-27]
FIFA Points 1,600 [9.99£][2019-03-26]
FIFA Points 1,050 [6.66£][2019-01-26]
EA SPORTS™ UFC® 3 [13.32£][2019-01-16]
Uncharted™: The Nathan Drake Collection [13.32£][2019-01-16]
FIFA Points 1,600 [9.99£][2019-01-04]
RUGBY 18 [10.82£][2019-01-01]
Pure Pool Snooker Bundle [2.32£][2019-01-01]
==============================================================
==============================================================
x-x-x ACCOUNT: <EMAIL>:frenzy11
---CheckTime: 2021/02/14 04:12 AM
---ONLINE ID: ravjyot
---COUNTRY: IN
---DATEOFBIRTH: 1987-06-11
---DEACTIVATION: Yes
---DEVICES: PS4[1]
---PLAYSTATION PLUS: PlayStation Plus: 12 Month Membership [01/12/2022]
---PAYMENT METHODS: [VISA 2022-3]
---BALANCE: Rs 0
---HAS MORE TRANSACTIONS: NO
-------------------- Transactions --------------------
Destiny 2: Beyond Light Deluxe Edition [37.7Rs][2020-11-15]
Destiny 2: Shadowkeep Digital Deluxe Edition [29.65Rs][2019-09-25]
Anthem™ Standard Edition [28.6Rs][2019-01-13]
Destiny 2: Forsaken + Annual Pass [33.89Rs][2018-09-04]
The Witcher 3: Wild Hunt – Game of the Year Edition [16.94Rs][2018-04-02]
Battlefield™ 1 Premium Pass [10.58Rs][2018-01-09]
Destiny 2 - Digital Deluxe Edition [61.86Rs][2017-09-05]
==============================================================
==============================================================
x-x-x ACCOUNT: <EMAIL>:ferris007
---CheckTime: 2021/02/14 01:44 AM
---ONLINE ID: GhasanMudah
---COUNTRY: ZA
---DATEOFBIRTH: 1986-12-31
---DEACTIVATION: Yes
---DEVICES: PS4[1]
---PLAYSTATION PLUS: PlayStation Plus: 12 Month Membership [07/13/2021]
---PAYMENT METHODS: [MC 2024-11]
---BALANCE: R 0.00
---HAS MORE TRANSACTIONS: NO
-------------------- Transactions --------------------
2,400 Call of Duty®: Modern Warfare® Points [286.09R][2020-12-30]
EA SPORTS™ FIFA 20 [138.26R][2020-06-16]
PlayStation®Plus: 30% off 12 Month Membership [455.65R][2020-06-16]
Need for Speed™ [77.39R][2019-12-26]
PlayStation®Plus: 12 Month Membership 20% Off [625.22R][2018-11-23]
==============================================================
==============================================================
x-x-x ACCOUNT: <EMAIL>:Andres1998
---CheckTime: 2021/02/14 01:55 AM
---ONLINE ID: AEFC98
---COUNTRY: MX
---DATEOFBIRTH: 1998-02-25
---DEACTIVATION: Yes
---DEVICES: PS4[1]
---PLAYSTATION PLUS: NO
---PAYMENT METHODS: N/A
---BALANCE: US$0.00
---HAS MORE TRANSACTIONS: NO
-------------------- Transactions --------------------
200 Call of Duty®: Modern Warfare® Points [1.99US$][2020-12-06]
Call of Duty®: Modern Warfare® - Battle Pass Edition [59.99US$][2020-07-29]
Grand Theft Auto V: Premium Edition [14.99US$][2020-04-20]
==============================================================
==============================================================
x-x-x ACCOUNT: <EMAIL>:jjordan8
---CheckTime: 2021/02/14 02:08 AM
---ONLINE ID: cece1doe
---COUNTRY: US
---DATEOFBIRTH: 1989-08-06
---DEACTIVATION: Yes
---DEVICES: PS4[1]
---PLAYSTATION PLUS: PlayStation Plus 12-Month Subscription [04/05/2021]
---PAYMENT METHODS: [VISA 2023-12] [MC 2023-10] [VISA 2022-12]
---BALANCE: $0.00
---HAS MORE TRANSACTIONS: NO
-------------------- Transactions --------------------
Online ID Change [4.99$][2021-01-23]
RISK [5.99$][2020-05-13]
MONOPOLY PLUS [14.99$][2020-05-13]
UNO® Ultimate Edition [8.99$][2020-05-13]
Fortnite - 2,800 V-Bucks [24.99$][2020-04-24]
Starter Pack and Whale Shark Card Bundle [59.99$][2020-04-07]
Crash Bandicoot™ N. Sane Trilogy [39.99$][2017-10-11]
==============================================================
==============================================================
x-x-x ACCOUNT: <EMAIL>:forifesta1984
---CheckTime: 2021/02/14 02:18 AM
---ONLINE ID: VivoEnUnSaco
---COUNTRY: ES
---DATEOFBIRTH: 1984-10-21
---DEACTIVATION: Yes
---DEVICES: PS4[1]
---PLAYSTATION PLUS: NO
---PAYMENT METHODS: [VISA 2021-3] [VISA 2020-12]
---BALANCE: 0,00 €
---HAS MORE TRANSACTIONS: NO
-------------------- Transactions --------------------
PlayStation Now: 1 Month Subscription [8.26€][2021-02-12]
MotoGP™19 [9.5€][2020-03-24]
==============================================================
==============================================================
x-x-x ACCOUNT: <EMAIL>:peterete8
---CheckTime: 2021/02/14 02:27 AM
---ONLINE ID: VictorRebellon
---COUNTRY: ES
---DATEOFBIRTH: 1986-07-10
---DEACTIVATION: Yes
---DEVICES: PS4[1]
---PLAYSTATION PLUS: NO
---PAYMENT METHODS: [VISA 2024-8]
---BALANCE: 0,00 €
---HAS MORE TRANSACTIONS: NO
-------------------- Transactions --------------------
STAR WARS™ Battlefront™ II: Celebration Edition [9.91€][2021-01-19]
TEKKEN 7 [8.26€][2020-11-03]
God of War™ [16.52€][2020-11-03]
eFootball PES 2020 Standard Edition [16.52€][2020-04-11]
The Crew® 2 - Deluxe Edition [12.39€][2020-04-01]
Ghost Recon® Breakpoint [16.52€][2020-03-29]
MX vs. ATV Supercross Encore [4.12€][2020-03-28]
PRO EVOLUTION SOCCER 2019 STANDARD EDITION [20.65€][2019-01-03]
==============================================================
==============================================================
x-x-x ACCOUNT: <EMAIL>:jesus2004
---CheckTime: 2021/02/14 02:47 AM
---ONLINE ID: Big_Red1022
---COUNTRY: US
---DATEOFBIRTH: 1993-10-22
---DEACTIVATION: Yes
---DEVICES: PS4[1]
---PLAYSTATION PLUS: NO
---PAYMENT METHODS: N/A
---BALANCE: $0.00
---HAS MORE TRANSACTIONS: NO
-------------------- Transactions --------------------
15,000 VC (NBA 2K20) [4.99$][2020-06-06]
15,000 VC (NBA 2K20) [4.99$][2020-06-06]
Call of Duty®: Modern Warfare® [39.59$][2020-01-02]
5,000 VC [1.69$][2019-07-31]
STAR WARS™ Battlefront™ II [7.49$][2019-07-26]
LittleBigPlanet™ 3 [19.99$][2019-07-19]
Grand Theft Auto V [14.99$][2019-06-07]
Minecraft: PlayStation®4 Edition [9.99$][2019-05-19]
NBA 2K19 [19.79$][2019-03-19]
Rocket League® [9.99$][2019-01-05]
Fortnite Battle Royale - Starter Pack [4.99$][2018-05-05]
Fortnite - 1,000 V-Bucks [9.99$][2018-05-01]
==============================================================
==============================================================
x-x-x ACCOUNT: <EMAIL>ty<EMAIL>:bruinsfan1
---CheckTime: 2021/02/14 03:04 AM
---ONLINE ID: WickedestCash69
---COUNTRY: US
---DATEOFBIRTH: 1997-09-06
---DEACTIVATION: Yes
---DEVICES: PS4[1]
---PLAYSTATION PLUS: PlayStation Plus 3-Month Subscription [04/01/2021]
---PAYMENT METHODS: [VISA 2024-10] [VISA 2022-2] [MC 2021-3]
---BALANCE: $0.00
---HAS MORE TRANSACTIONS: NO
-------------------- Transactions --------------------
Minecraft Dungeons Hero Edition [29.99$][2021-01-17]
DOOM Eternal Standard Edition [19.79$][2020-12-26]
Ghost of Tsushima [40.19$][2020-12-26]
Red Dead Redemption 2: Ultimate Edition [34.99$][2020-12-19]
Call of Duty®: Black Ops Cold War - Standard Edition [59.99$][2020-11-13]
Assassin's Creed Valhalla [59.99$][2020-11-09]
Fortnite: Save the World - Deluxe Founder's Pack [29.99$][2018-02-25]
==============================================================
==============================================================
x-x-x ACCOUNT: <EMAIL>:ogisas96
---CheckTime: 2021/02/14 03:09 AM
---ONLINE ID: ARHE-de-SKORPION
---COUNTRY: UA
---DATEOFBIRTH: 1996-12-22
---DEACTIVATION: Yes
---DEVICES: PS4[1]
---PLAYSTATION PLUS: NO
---PAYMENT METHODS: [MC 2023-3] [VISA 2022-5] [MC 2024-11]
---BALANCE: 0.00 UAH
---HAS MORE TRANSACTIONS: NO
-------------------- Transactions --------------------
Mafia III Deluxe Edition [499.0UAH][2020-04-07]
Red Dead Redemption 2: Special Edition [1349.0UAH][2019-06-28]
Mortal Kombat XL [499.0UAH][2019-06-27]
The Forest [359.0UAH][2019-06-21]
inFAMOUS Second Son™ [499.0UAH][2019-06-15]
Friday the 13th: The Game [619.0UAH][2019-06-09]
The Witcher 3: Wild Hunt – Game of the Year Edition [489.0UAH][2019-04-25]
Grand Theft Auto V: Premium Edition [499.0UAH][2019-04-20]
==============================================================
==============================================================
x-x-x ACCOUNT: <EMAIL>:Jayhawks20
---CheckTime: 2021/02/14 03:20 AM
---ONLINE ID: pwrhodes20
---COUNTRY: US
---DATEOFBIRTH: 1990-09-27
---DEACTIVATION: Yes
---DEVICES: PS4[1]
---PLAYSTATION PLUS: NO
---PAYMENT METHODS: [MC 2022-4]
---BALANCE: $0.00
---HAS MORE TRANSACTIONS: NO
-------------------- Transactions --------------------
Call of Duty®: Black Ops III - Zombies Chronicles Edition [59.99$][2020-12-28]
Call of Duty®: Black Ops III - Der Eisendrache Zombies Map [7.99$][2020-12-28]
Call of Duty® Black Ops III - Gorod Krovi Zombies Map [7.99$][2020-12-28]
Call of Duty®: Black Ops Cold War - Standard Edition [59.99$][2020-12-12]
The Elder Scrolls V: Skyrim Special Edition [15.99$][2020-11-29]
ARK: Survival Evolved [14.99$][2020-04-25]
Far Cry® 4 [19.99$][2020-03-28]
Borderlands 3: Moxxi's Heist of the Handsome Jackpot PS4™ & PS5™ [14.99$][2020-01-24]
Far Cry New Dawn [39.99$][2019-11-08]
Borderlands: Ultimate Edition [29.99$][2017-09-13]
==============================================================
==============================================================
x-x-x ACCOUNT: <EMAIL>:Yeyo040103
---CheckTime: 2021/02/14 03:24 AM
---ONLINE ID: Killervader04
---COUNTRY: CR
---DATEOFBIRTH: 1990-01-04
---DEACTIVATION: Yes
---DEVICES: PS4[1]
---PLAYSTATION PLUS: PS Plus: Suscripción de 3 Meses Month [02/14/2021]
---PAYMENT METHODS: [VISA 2024-11] [VISA 2021-7]
---BALANCE: US$0.00
---HAS MORE TRANSACTIONS: NO
-------------------- Transactions --------------------
Persona® 5 Strikers Digital Deluxe Edition [69.99US$][2021-02-13]
Assassin’s Creed® Syndicate [29.99US$][2021-02-02]
Marvel's Spider-Man: The City That Never Sleeps [24.99US$][2021-01-07]
Assassin’s Creed® Unity [8.99US$][2020-12-21]
P3D/P5D: 'Break Out Of... (OP ver.)' [0.99US$][2020-12-20]
P3D/P5D: Goro Akechi in 'Will Power' [4.99US$][2020-10-07]
Persona Dancing: Endless Night Collection [21.99US$][2020-10-07]
WORLD OF FINAL FANTASY [12.49US$][2020-10-05]
Genshin Impact-Adventurer's Starter Bundle [9.99US$][2020-09-23]
FINAL FANTASY VII REMAKE [39.59US$][2020-08-14]
SWORD ART ONLINE Alicization Lycoris Soundtrack Bundle [1.99US$][2020-07-11]
EA Family Bundle [9.99US$][2020-06-17]
Mortal Kombat X [5.99US$][2020-06-17]
Marvel vs. Capcom: Infinite - Standard Edition [9.99US$][2020-06-09]
Persona®5 Royal [59.99US$][2020-04-24]
KINGDOM HEARTS III Re Mind [29.99US$][2020-01-26]
KINGDOM HEARTS III - 'Midnight Blue' Keyblade [2.99US$][2019-12-31]
Persona 5 [19.99US$][2019-12-31]
==============================================================
==============================================================
x-x-x ACCOUNT: <EMAIL>:Boki2309
---CheckTime: 2021/02/14 03:35 AM
---ONLINE ID: Sekulo23
---COUNTRY: DK
---DATEOFBIRTH: 1987-09-23
---DEACTIVATION: Yes
---DEVICES: PS4[1]
---PLAYSTATION PLUS: PlayStation Plus 1 Month Membership [03/11/2021]
---PAYMENT METHODS: [VISA 2022-12]
---BALANCE: Kr 0,00
---HAS MORE TRANSACTIONS: NO
-------------------- Transactions --------------------
FIFA 21 Champions Edition PS4™ & PS5™ [156.58Kr][2021-02-11]
Assassin's Creed® Liberation HD [24.0Kr][2018-03-26]
Assassin's Creed® Freedom Cry [24.0Kr][2018-03-26]
Dante's Inferno™ Super Bundle [29.6Kr][2018-03-26]
Alice: Madness Returns™ [17.6Kr][2018-03-26]
Tomb Raider Digital Edition [8.8Kr][2018-03-26]
Dogfight 1942 Bundle [12.0Kr][2018-03-26]
==============================================================
==============================================================
x-x-x ACCOUNT: <EMAIL>:47t28157bt
---CheckTime: 2021/02/14 03:52 AM
---ONLINE ID: Serepano4ka
---COUNTRY: RU
---DATEOFBIRTH: 1985-08-17
---DEACTIVATION: Yes
---DEVICES: PS4[1]
---PLAYSTATION PLUS: PlayStation Plus: 12 Month [04/01/2022]
---PAYMENT METHODS: [VISA 2022-10]
---BALANCE: RUB 0
---HAS MORE TRANSACTIONS: NO
-------------------- Transactions --------------------
EA Play 1 Month Discount Offer [74.17RUB][2021-02-07]
Minecraft [1124.17RUB][2021-02-02]
Overcooked [228.33RUB][2021-01-01]
Overcooked! 2 [670.0RUB][2021-01-01]
==============================================================
by <NAME> Telegram: @AhmedoPlus
| StarcoderdataPython |
3581864 | from collections import OrderedDict
try:
from urllib.parse import urlunparse
from urllib.parse import urlparse
from urllib.parse import quote_plus
from .ezurllib import urlencode
except ImportError:
from urlparse import urlunparse
from urlparse import urlparse
from urllib import quote_plus
from .ezurllib import urlencode
class Url(object):
"""
This class allows more flexible generation of URLS.
This prevents the mindless manipulation string that occur
in projects that require generation of a wide range of urls
"""
def __init__(self, hostname, scheme="https", querydelimiter="&"):
"""
Initializes the Url object
:param hostname: The hostname of the Url
:param scheme: Optional Scheme selection. Defaults to https
:param querydelimiter: What the query delimiter is for this URL
"""
self.__safe__ = "+"
self.__scheme__ = scheme
self.__hostname__ = hostname
self.__pages__ = list()
self.__query__ = OrderedDict()
self.__fragment__ = ""
self.__querydelimiter__ = querydelimiter
def __repr__(self):
"""REPR Implementation"""
return "<url:{url}>".format(url=str(self))
@property
def url(self):
return urlparse(str(self))
@property
def safe(self):
return self.__safe__
@safe.setter
def safe(self, v):
self.__safe__ = v
@property
def schemes(self):
return self.url.scheme
@property
def netloc(self):
return self.url.netloc
@property
def pages(self):
"""Returns a list of pages"""
return self.__pages__
@property
def path(self):
"""
Returns str of the Path
"""
return self.url.path
@property
def queries_dict(self):
return self.__query__
@property
def queries(self):
return self.url.query
@property
def fragments(self):
return self.url.fragement
def __str__(self):
"""
return str object
"""
return urlunparse((self.__scheme__,
self.__hostname__,
self._page_gen(),
str(),
self._query_gen(),
self.__fragment__))
def _page_gen(self):
"""
Generates The String for pages
"""
track = ""
for page in self.__pages__:
track += "/{page}".format(page=page)
return track
def _query_gen(self):
"""Generates The String for queries"""
return urlencode(self.__query__, safe=self.safe, querydelimiter=self.__querydelimiter__)
def hostname(self, hostname):
self.__hostname__ = hostname
return self
def scheme(self, scheme):
self.__scheme__ = scheme
return self
def page(self, *args):
"""
Pages takes *args and adds pages in order
"""
for arg in args:
self.__pages__.append(arg)
return self
def query(self, listdelimiter="+", safe="", **kwargs):
"""
Url queries
:param listdelimiter: Specifies what list delimiter should be
:param safe: string that includes all the characters that should not be ignored
Kwargs (Since its a dictionary) are not ordered. You must call the
method again if you absolutely need one query
after another or vice versa.
"""
safe = safe if safe else self.safe
for arg in list(kwargs.keys()):
if (isinstance(kwargs[arg], list)
or isinstance(kwargs[arg], tuple)
or isinstance(kwargs[arg], set)):
items = [quote_plus(str(x), safe=safe) for x in kwargs[arg]]
self.__query__.update({arg: listdelimiter.join(items)})
else:
self.__query__.update({arg: kwargs.get(arg)})
return self
def fragment(self, text):
"""
Allows for fragments at the end of the url
"""
self.__fragment__ = text
return self
| StarcoderdataPython |
9693978 | <reponame>benety/mongo
"""Test hook for cleaning up data files created by the fixture."""
import os
from buildscripts.resmokelib.testing.hooks import interface
class CleanEveryN(interface.Hook):
"""Restart the fixture after it has ran 'n' tests.
On mongod-related fixtures, this will clear the dbpath.
"""
IS_BACKGROUND = False
DEFAULT_N = 20
def __init__(self, hook_logger, fixture, n=DEFAULT_N):
"""Initialize CleanEveryN."""
description = "CleanEveryN (restarts the fixture after running `n` tests)"
interface.Hook.__init__(self, hook_logger, fixture, description)
# Try to isolate what test triggers the leak by restarting the fixture each time.
if "detect_leaks=1" in os.getenv("ASAN_OPTIONS", ""):
self.logger.info(
"ASAN_OPTIONS environment variable set to detect leaks, so restarting"
" the fixture after each test instead of after every %d.", n)
n = 1
self.n = n # pylint: disable=invalid-name
self.tests_run = 0
def after_test(self, test, test_report):
"""After test cleanup."""
self.tests_run += 1
if self.tests_run < self.n:
return
hook_test_case = CleanEveryNTestCase.create_after_test(test.logger, test, self)
hook_test_case.configure(self.fixture)
hook_test_case.run_dynamic_test(test_report)
class CleanEveryNTestCase(interface.DynamicTestCase):
"""CleanEveryNTestCase class."""
def run_test(self):
"""Execute test hook."""
try:
self.logger.info("%d tests have been run against the fixture, stopping it...",
self._hook.tests_run)
self._hook.tests_run = 0
self.fixture.teardown()
self.logger.info("Starting the fixture back up again...")
self.fixture.setup()
self.fixture.await_ready()
except:
self.logger.exception("Encountered an error while restarting the fixture.")
raise
| StarcoderdataPython |
3467926 | <filename>yatube/core/context_processors/year.py
import datetime as dt
def year(request):
"""Создаём переменную, которая будет показывать текущий год."""
return {
'year': int(dt.date.today().strftime('%Y'))
}
| StarcoderdataPython |
1631254 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that contains console widgets
"""
from __future__ import print_function, division, absolute_import
import logging
from io import StringIO
from Qt.QtCore import Qt, QSize, QStringListModel
from Qt.QtWidgets import QSizePolicy, QLineEdit, QTextEdit, QCompleter, QAction
from Qt.QtGui import QFont, QTextCursor
from tpDcc.libs.python import python
class ConsoleInput(QLineEdit, object):
def __init__(self, commands=[], parent=None):
super(ConsoleInput, self).__init__(parent=parent)
self._commands = commands
self._model = QStringListModel()
self._model.setStringList(self._commands)
self._completer = QCompleter(self)
self._completer.setModel(self._model)
self._completer.setCompletionMode(QCompleter.PopupCompletion)
self._completer.setCaseSensitivity(Qt.CaseInsensitive)
self.setCompleter(self._completer)
self.setFont(QFont('Arial', 9, QFont.Bold, False))
class Console(QTextEdit, object):
def __init__(self, parent=None):
super(Console, self).__init__(parent=parent)
self._buffer = StringIO()
size_policy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum)
size_policy.setHorizontalStretch(0)
size_policy.setVerticalStretch(0)
size_policy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
self.setSizePolicy(size_policy)
self.setReadOnly(True)
self.setMaximumSize(QSize(16777215, 16777215))
self.setFocusPolicy(Qt.StrongFocus)
self.setLineWrapMode(QTextEdit.NoWrap)
self.setContextMenuPolicy(Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self._generate_context_menu)
def __getattr__(self, attr):
"""
Fall back to the buffer object if an attribute cannot be found
"""
return getattr(self._buffer, attr)
def enterEvent(self, event):
self.setFocus()
def write(self, msg):
"""
Add message to the console's output, on a new line
:param msg: str
"""
self.insertPlainText(msg + '\n')
self.moveCursor(QTextCursor.End)
self._buffer.write(unicode(msg) if python.is_python2() else str(msg))
def write_error(self, msg):
"""
Adds an error message to the console
:param msg: str
"""
msg_html = "<font color=\"Red\">ERROR: " + msg + "\n</font><br>"
msg = 'ERROR: ' + msg
self.insertHtml(msg_html)
self.moveCursor(QTextCursor.End)
self._buffer.write(unicode(msg) if python.is_python2() else str(msg))
def write_ok(self, msg):
"""
Adds an ok green message to the console
:param msg: str
"""
msg_html = "<font color=\"Lime\"> " + msg + "\n</font><br>"
self.insertHtml(msg_html)
self.moveCursor(QTextCursor.End)
self._buffer.write(unicode(msg) if python.is_python2() else str(msg))
def write_warning(self, msg):
"""
Adds a warning yellow message to the console
:param msg: str
"""
msg_html = "<font color=\"Yellow\"> " + msg + "\n</font><br>"
self.insertHtml(msg_html)
self.moveCursor(QTextCursor.End)
self._buffer.write(unicode(msg) if python.is_python2() else str(msg))
def flush(self):
self.moveCursor(QTextCursor.End, QTextCursor.MoveAnchor)
self.moveCursor(QTextCursor.Up, QTextCursor.MoveAnchor)
self.moveCursor(QTextCursor.StartOfLine, QTextCursor.MoveAnchor)
self.moveCursor(QTextCursor.End, QTextCursor.KeepAnchor)
self.textCursor().removeSelectedText()
def output_buffer_to_file(self, filepath):
pass
def _generate_context_menu(self, pos):
"""
Internal function that generates context menu of the console
:param pos: QPos
:return: QMneu
"""
menu = self.createStandardContextMenu()
clear_action = QAction('Clear', menu)
clear_action.triggered.connect(self.clear)
menu.addSeparator()
menu.addAction(clear_action)
# menu.addSeparator()
# undo_action = QAction('Undo', menu)
# undo_action.setShortcut('Ctrl+Z')
# menu.addAction(undo_action)
# redo_action = QAction('Redo', menu)
# redo_action.setShortcut('Ctrl+Y')
# menu.addAction(redo_action)
# undo_action.setEnabled(self.isUndoRedoEnabled())
# redo_action.setEnabled(self.isUndoRedoEnabled())
# undo_action.triggered.connect(self._on_undo)
# redo_action.triggered.connect(self._on_redo)
menu.popup(self.mapToGlobal(pos))
def _on_undo(self):
if self.isUndoRedoEnabled():
self.undo()
def _on_redo(self):
if self.isUndoRedoEnabled():
self.redo()
class ConsoleLoggerHandler(logging.Handler):
def __init__(self, parent):
super(ConsoleLoggerHandler, self).__init__()
self.widget = Console(parent=parent)
self.widget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
formatter = ConsoleFormatter('%(asctime)s|%(levelname)s|%(message)s|', '%d/%m/%Y %H:%M:%S')
self.setFormatter(formatter)
def emit(self, record):
msg = self.format(record)
if '|INFO|' in msg:
self.widget.write_ok(msg)
elif '|WARNING|' in msg:
self.widget.write_warning(msg)
elif '|ERROR|' in msg:
self.widget.write_error(msg)
else:
self.widget.write(msg)
class ConsoleFormatter(logging.Formatter):
def format(self, record):
s = super(ConsoleFormatter, self).format(record)
if record.exc_text:
s = s.replace('\n', '')
return s
| StarcoderdataPython |
6502179 | from copy import deepcopy
from models_old.variable import Variable
from models_old.restriction import Restriction
from models_old.linear_model import LinearModel
from models_old.base_finder import InitialBaseFinder
from models_old.internal.simplex_solver import SimplexSolver
class Simplex:
def __init__(self, linear_model: LinearModel, start_base_indexes=None, skip_standard=False):
if not linear_model.is_standard_form and not skip_standard:
print('\n[WARNING] Transforming your LinearModel in standard form. To skip, use Simplex(skip_standard = True)')
linear_model.transform_to_standard_form()
if start_base_indexes:
if not isinstance(start_base_indexes, list) or not len(start_base_indexes) == linear_model.m or not all(isinstance(i, int) for i in start_base_indexes):
raise ValueError('\n[FATAL ERROR]: Your start_base_indexes must be a list containing only numbers with m "length" of {0}'.format(linear_model.m))
self.linear_model = linear_model
self.start_base_indexes = start_base_indexes
# Solution
self.fo = None
self.variables_values = None
self.status = None
def solve(self):
initial_base = None
if not self.start_base_indexes:
tmp_linear_model = deepcopy(self.linear_model)
# Phase 1
base_finder = InitialBaseFinder(linear_model=tmp_linear_model)
base_finder.find_base()
print('\nFound an feasible initial base: {0}'.format(base_finder.solution_B_vars))
initial_base = base_finder.solution_B_vars_indexes
else:
initial_base = self.start_base_indexes
# Phase 2
solver = SimplexSolver(linear_model=self.linear_model, start_base=initial_base)
solver.solve()
self.variables_values = solver.solution
self.fo = solver.solution_fo
self.status = solver.status
return solver.solution
@property
def solution_str(self):
return '\nFound a solution:\nStatus: {0}\n\nFo(x): {1}\n\nVariables: {2}\n\n'.format(self.status, self.fo, self.variables_values)
if __name__ == '__main__':
# Declaring Variables
x1 = Variable(fo_coefficient=5)
x2 = Variable(fo_coefficient=4/9)
x3 = Variable(fo_coefficient=-3)
r1 = Restriction([(2, x1), (3, x2), (1, x3)], '<=', 5)
r2 = Restriction([(4, x1), (1, x2), (-2/3, x2)], '<=', 11)
r3 = Restriction([(4, x1), (1, x2), (-2 / 3, x2)], '<=', 91)
r4 = Restriction([(1, x1), (1, x2), (-2 / 3, x2)], '<=', 2)
r5 = Restriction([(-1, x2), (-1, x3)], '<=', 6/7)
r6 = Restriction([(-1, x1), (-1, x2)], '<=', 34)
# x1 >= 0 and x2 >= 0 are automatically assumed
# Building a LP Model
model = LinearModel()
model.build_objective_function(fo_type='max', variables=[x1, x2, x3])
model.add_restrictions([r1, r2, r3, r4, r5, r6])
model.transform_to_standard_form()
print(model)
# Simplex Algorithm
simplex = Simplex(linear_model=model)
simplex.solve()
print(simplex.solution_str) | StarcoderdataPython |
8034488 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
try:
from ._models_py3 import APIError
from ._models_py3 import Address
from ._models_py3 import Body
from ._models_py3 import BodyMetadata
from ._models_py3 import BodyModel
from ._models_py3 import Candidate
from ._models_py3 import Classification
from ._models_py3 import Content
from ._models_py3 import CreateReviewBodyItem
from ._models_py3 import CreateReviewBodyItemMetadataItem
from ._models_py3 import CreateVideoReviewsBodyItem
from ._models_py3 import CreateVideoReviewsBodyItemMetadataItem
from ._models_py3 import CreateVideoReviewsBodyItemVideoFramesItem
from ._models_py3 import CreateVideoReviewsBodyItemVideoFramesItemMetadataItem
from ._models_py3 import CreateVideoReviewsBodyItemVideoFramesItemReviewerResultTagsItem
from ._models_py3 import DetectedLanguage
from ._models_py3 import DetectedTerms
from ._models_py3 import Email
from ._models_py3 import Error
from ._models_py3 import Evaluate
from ._models_py3 import Face
from ._models_py3 import FoundFaces
from ._models_py3 import Frame
from ._models_py3 import Frames
from ._models_py3 import IPA
from ._models_py3 import Image
from ._models_py3 import ImageAdditionalInfoItem
from ._models_py3 import ImageIds
from ._models_py3 import ImageList
from ._models_py3 import ImageListMetadata
from ._models_py3 import Job
from ._models_py3 import JobExecutionReportDetails
from ._models_py3 import JobId
from ._models_py3 import JobListResult
from ._models_py3 import KeyValuePair
from ._models_py3 import Match
from ._models_py3 import MatchResponse
from ._models_py3 import OCR
from ._models_py3 import PII
from ._models_py3 import Phone
from ._models_py3 import RefreshIndex
from ._models_py3 import RefreshIndexAdvancedInfoItem
from ._models_py3 import Review
from ._models_py3 import Score
from ._models_py3 import Screen
from ._models_py3 import Status
from ._models_py3 import Tag
from ._models_py3 import TermList
from ._models_py3 import TermListMetadata
from ._models_py3 import Terms
from ._models_py3 import TermsData
from ._models_py3 import TermsInList
from ._models_py3 import TermsPaging
from ._models_py3 import TranscriptModerationBodyItem
from ._models_py3 import TranscriptModerationBodyItemTermsItem
from ._models_py3 import VideoFrameBodyItem
from ._models_py3 import VideoFrameBodyItemMetadataItem
from ._models_py3 import VideoFrameBodyItemReviewerResultTagsItem
from ._models_py3 import APIErrorException
except (SyntaxError, ImportError):
from ._models import APIError
from ._models import Address
from ._models import Body
from ._models import BodyMetadata
from ._models import BodyModel
from ._models import Candidate
from ._models import Classification
from ._models import Content
from ._models import CreateReviewBodyItem
from ._models import CreateReviewBodyItemMetadataItem
from ._models import CreateVideoReviewsBodyItem
from ._models import CreateVideoReviewsBodyItemMetadataItem
from ._models import CreateVideoReviewsBodyItemVideoFramesItem
from ._models import CreateVideoReviewsBodyItemVideoFramesItemMetadataItem
from ._models import CreateVideoReviewsBodyItemVideoFramesItemReviewerResultTagsItem
from ._models import DetectedLanguage
from ._models import DetectedTerms
from ._models import Email
from ._models import Error
from ._models import Evaluate
from ._models import Face
from ._models import FoundFaces
from ._models import Frame
from ._models import Frames
from ._models import IPA
from ._models import Image
from ._models import ImageAdditionalInfoItem
from ._models import ImageIds
from ._models import ImageList
from ._models import ImageListMetadata
from ._models import Job
from ._models import JobExecutionReportDetails
from ._models import JobId
from ._models import JobListResult
from ._models import KeyValuePair
from ._models import Match
from ._models import MatchResponse
from ._models import OCR
from ._models import PII
from ._models import Phone
from ._models import RefreshIndex
from ._models import RefreshIndexAdvancedInfoItem
from ._models import Review
from ._models import Score
from ._models import Screen
from ._models import Status
from ._models import Tag
from ._models import TermList
from ._models import TermListMetadata
from ._models import Terms
from ._models import TermsData
from ._models import TermsInList
from ._models import TermsPaging
from ._models import TranscriptModerationBodyItem
from ._models import TranscriptModerationBodyItemTermsItem
from ._models import VideoFrameBodyItem
from ._models import VideoFrameBodyItemMetadataItem
from ._models import VideoFrameBodyItemReviewerResultTagsItem
from ._models import APIErrorException
from ._content_moderator_client_enums import AzureRegionBaseUrl
__all__=[
'APIError',
'Address',
'Body',
'BodyMetadata',
'BodyModel',
'Candidate',
'Classification',
'Content',
'CreateReviewBodyItem',
'CreateReviewBodyItemMetadataItem',
'CreateVideoReviewsBodyItem',
'CreateVideoReviewsBodyItemMetadataItem',
'CreateVideoReviewsBodyItemVideoFramesItem',
'CreateVideoReviewsBodyItemVideoFramesItemMetadataItem',
'CreateVideoReviewsBodyItemVideoFramesItemReviewerResultTagsItem',
'DetectedLanguage',
'DetectedTerms',
'Email',
'Error',
'Evaluate',
'Face',
'FoundFaces',
'Frame',
'Frames',
'IPA',
'Image',
'ImageAdditionalInfoItem',
'ImageIds',
'ImageList',
'ImageListMetadata',
'Job',
'JobExecutionReportDetails',
'JobId',
'JobListResult',
'KeyValuePair',
'Match',
'MatchResponse',
'OCR',
'PII',
'Phone',
'RefreshIndex',
'RefreshIndexAdvancedInfoItem',
'Review',
'Score',
'Screen',
'Status',
'Tag',
'TermList',
'TermListMetadata',
'Terms',
'TermsData',
'TermsInList',
'TermsPaging',
'TranscriptModerationBodyItem',
'TranscriptModerationBodyItemTermsItem',
'VideoFrameBodyItem',
'VideoFrameBodyItemMetadataItem',
'VideoFrameBodyItemReviewerResultTagsItem',
'APIErrorException',
'AzureRegionBaseUrl',
]
| StarcoderdataPython |
5045036 | <gh_stars>10-100
from panini import app as panini_app
from panini.middleware.nats_timeout import NATSTimeoutMiddleware
app = panini_app.App(
service_name="async_nats_timeout_middleware",
host="127.0.0.1",
port=4222,
)
log = app.logger
message = {
"key1": "value1",
"key2": 2,
"key3": 3.0,
"key4": [1, 2, 3, 4],
"key5": {"1": 1, "2": 2, "3": 3, "4": 4, "5": 5},
"key6": {"subkey1": "1", "subkey2": 2, "3": 3, "4": 4, "5": 5},
"key7": None,
}
@app.task()
async def request_periodically():
log.info("Send request to not existing subject - expecting NATS Timeout")
response = await app.request(subject="not.existing.subject", message=message)
log.info(f"response message from periodic task: {response}")
@app.listen("handle.nats.timeout.subject")
async def handle_timeout(msg):
log.error(f"NATS timeout handled: {msg.data}")
return {"success": True, "data": "successfully handled NATS timeout"}
if __name__ == "__main__":
app.add_middleware(
NATSTimeoutMiddleware,
subject="handle.nats.timeout.subject",
send_func_type="request",
)
app.start()
| StarcoderdataPython |
1964705 | <gh_stars>10-100
from niaaml import Pipeline
from niaaml.classifiers import MultiLayerPerceptron
from niaaml.preprocessing.feature_selection import VarianceThreshold
from niaaml.preprocessing.feature_transform import Normalizer
from niaaml.data import CSVDataReader
from niaaml.preprocessing.encoding import encode_categorical_features
from niaaml.preprocessing.imputation import impute_features
import os
import numpy
import pandas
"""
This example presents how to use the Pipeline class individually. You may use this if you want to test out a specific classification pipeline.
We use a dataset that contains categorical and numerical features with missing values.
"""
# prepare data reader using csv file
data_reader = CSVDataReader(
src=os.path.dirname(os.path.abspath(__file__))
+ "/example_files/dataset_categorical_missing.csv",
has_header=False,
contains_classes=True,
)
features = data_reader.get_x()
# we use the utility method impute_features to get imputers for the features with missing values, but you may instantiate and fit
# imputers separately and pass them as a dictionary (as long as they are implemented as this framework suggests), with keys as column names or indices (if there is no header in the csv)
# there should be as many imputers as the features with missing values
# this example uses Simple Imputer
features, imputers = impute_features(features, "SimpleImputer")
# exactly the same goes for encoders
_, encoders = encode_categorical_features(features, "OneHotEncoder")
# instantiate a Pipeline object
pipeline = Pipeline(
feature_selection_algorithm=VarianceThreshold(),
feature_transform_algorithm=Normalizer(),
classifier=MultiLayerPerceptron(),
categorical_features_encoders=encoders,
imputers=imputers,
)
# run pipeline optimization process (returns fitness value, but sets the best parameters for classifier, feature selection algorithm and feature transform algorithm during the process)
pipeline.optimize(
data_reader.get_x(),
data_reader.get_y(),
10,
50,
"ParticleSwarmAlgorithm",
"Accuracy",
)
# run the pipeline using dummy data
# you could run the pipeline before the optimization process, but get wrong predictions as nothing in the pipeline is fit for the given dataset
predicted = pipeline.run(
pandas.DataFrame(
[
[
10.32440339,
3.195964543,
1.215275549,
3.741461311,
11.6736581,
6.435247906,
"a",
]
]
)
)
# pipeline variable contains a Pipeline object that can be used for further classification, exported as an object (that can later be loaded and used) or exported as text file
| StarcoderdataPython |
11321733 | <filename>detect_ai/detect_color.py
# import the necessary packages
import numpy as np
import cv2
# input image path
imagePath = '../demo_image/colordemo.png'
image = cv2.imread(imagePath)
boundaries = {'B': ([0, 0, 0], [255, 0, 0]),
'G': ([0, 0, 0], [0, 255, 0]),
'R': ([0, 0, 0], [0, 0, 255])}
# loop over the boundaries
for key in boundaries:
low, up = boundaries[key]
# create NumPy arrays from the boundaries
lower = np.array(low, dtype="uint8")
upper = np.array(up, dtype="uint8")
# find the colors within the specified boundaries and apply
# the mask
mask = cv2.inRange(image, lower, upper)
output = cv2.bitwise_and(image, image, mask=mask)
# save the images
saveImage = np.hstack([image, output])
imgBuf = cv2.cvtColor(saveImage, cv2.COLOR_BGR2RGB)
cv2.imwrite("output_" + key + ".png", imgBuf) | StarcoderdataPython |
225814 | # Copyright 2021 Spotify AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import logging
import threading
import time
from concurrent import futures
from google.cloud import pubsub as g_pubsub
from klio_core.proto import klio_pb2
ENTITY_ID_TO_ACK_ID = {}
_CACHED_THREADPOOL_EXEC = None
def _get_or_create_executor():
# We create one threadpool executor since the MessageManager does
# get initialized more than once (pretty frequently, actually). So
# let's reuse our executor rather than re-create it.
global _CACHED_THREADPOOL_EXEC
if _CACHED_THREADPOOL_EXEC is None:
# max_workers is equal to the number of threads we want to run in
# the background - 1 message maanger, and 1 heartbeat
_CACHED_THREADPOOL_EXEC = futures.ThreadPoolExecutor(
thread_name_prefix="KlioMessageManager", max_workers=2
)
return _CACHED_THREADPOOL_EXEC
class PubSubKlioMessage:
"""Contains state needed to manage ACKs for a KlioMessage"""
def __init__(self, ack_id, kmsg_id):
self.ack_id = ack_id
self.kmsg_id = kmsg_id
self.last_extended = None
self.ext_duration = None
self.event = threading.Event()
def extend(self, duration):
self.last_extended = time.monotonic()
self.ext_duration = duration
def __repr__(self):
return f"PubSubKlioMessage(kmsg_id={self.kmsg_id})"
class MessageManager:
"""Manages the ack deadline for in-progress KlioMessages.
Extends the ack deadline while the KlioMessage is still processing, and
stops extending them when the message is done.
This class is used by ``KlioPubSubReadEvaluator`` to manage message
acknowledgement.
Warning: non-KlioMessages are not (yet) supported. ``klio-job.yaml::
job_config.allow_non_klio_messages`` must be ``False``.
Usage:
.. code-block:: python
m = MessageManager("subscription-name")
m.start_threads()
"""
DEFAULT_DEADLINE_EXTENSION = 30
def __init__(self, sub_name, heartbeat_sleep=10, manager_sleep=10):
"""Initialize a MessageManager instance.
Args:
sub_name(str): PubSub subscription name to listen on.
heartbeat_sleep(float):
Seconds to sleep between heartbeat messages.
manager_sleep(float):
Seconds to sleep between deadline extension checks.
"""
self._client = g_pubsub.SubscriberClient()
self._sub_name = sub_name
self.heartbeat_sleep = heartbeat_sleep
self.manager_sleep = manager_sleep
self.messages = []
self.mgr_logger = logging.getLogger(
"klio.gke_direct_runner.message_manager"
)
self.hrt_logger = logging.getLogger("klio.gke_direct_runner.heartbeat")
self.executor = _get_or_create_executor()
def manage(self, message):
"""Continuously track in-progress messages and extends their deadlines.
Args:
to_sleep(float): Seconds to sleep between checks.
"""
while not message.event.is_set():
self._maybe_extend(message)
time.sleep(self.manager_sleep)
else:
self.remove(message)
def heartbeat(self, message):
"""Continuously log heartbeats for in-progress messages.
Args:
to_sleep(float): Second to sleep between log messages.
"""
while not message.event.is_set():
self.hrt_logger.info(
f"Job is still processing {message.kmsg_id}..."
)
time.sleep(self.heartbeat_sleep)
def _maybe_extend(self, message):
"""Check to see if message is done and extends deadline if not.
Deadline extension is only done when 80% of the message's extension
duration has passed.
Args:
message(PubSubKlioMessage): In-progress message to check.
"""
diff = 0
now = time.monotonic()
if message.last_extended is not None:
diff = now - message.last_extended
# taking 80% of the deadline extension as a
# threshold to comfortably request a message deadline
# extension before the deadline comes around
threshold = message.ext_duration * 0.8
if message.last_extended is None or diff >= threshold:
self.extend_deadline(message)
else:
self.mgr_logger.debug(
f"Skipping extending Pub/Sub ack deadline for {message}"
)
def extend_deadline(self, message, duration=None):
"""Extend deadline for a PubSubKlioMessage.
Args:
message(PubSubKlioMessage): The message to extend the deadline for.
duration(float): Seconds. If not specified, defaults to
MessageManager.DEFAULT_DEADLINE_EXTENSION.
"""
if duration is None:
duration = self.DEFAULT_DEADLINE_EXTENSION
request = {
"subscription": self._sub_name,
"ack_ids": [message.ack_id],
"ack_deadline_seconds": duration, # seconds
}
try:
# TODO: this method also has `retry` and `timeout` kwargs which
# we may be interested in using
self._client.modify_ack_deadline(**request)
except Exception as e:
self.mgr_logger.error(
f"Error encountered when trying to extend deadline for "
f"{message} with ack ID '{message.ack_id}': {e}",
exc_info=True,
)
self.mgr_logger.warning(
f"The message {message} may be re-delivered due to Klio's "
"inability to extend its deadline."
)
else:
self.mgr_logger.debug(
f"Extended Pub/Sub ack deadline for {message} by {duration}s"
)
message.extend(duration)
@staticmethod
def _convert_raw_pubsub_message(ack_id, pmessage):
# TODO: either use klio.message.serializer.to_klio_message, or
# figure out how to handle when a parsed_message can't be parsed
# into a KlioMessage (will need to somehow get the klio context)
kmsg = klio_pb2.KlioMessage()
kmsg.ParseFromString(pmessage.data)
entity_id = kmsg.data.element.decode("utf-8")
psk_msg = PubSubKlioMessage(ack_id, entity_id)
return psk_msg
def add(self, ack_id, raw_pubsub_message):
"""Add message to set of in-progress messages.
Messages added via this method will have their deadlines extended
until they are finished processing.
Args:
ack_id (str): Pub/Sub message's ack ID
raw_pubsub_message (apache_beam.io.gcp.pubsub.PubsubMessage):
Pub/Sub message to add.
"""
psk_msg = self._convert_raw_pubsub_message(ack_id, raw_pubsub_message)
self.mgr_logger.debug(f"Received {psk_msg.kmsg_id} from Pub/Sub.")
self.extend_deadline(psk_msg)
ENTITY_ID_TO_ACK_ID[psk_msg.kmsg_id] = psk_msg
self.executor.submit(self.manage, psk_msg)
self.executor.submit(self.heartbeat, psk_msg)
def remove(self, psk_msg):
"""Remove message from set of in-progress messages.
Messages removed via this method will be acknowledged.
Args:
psk_msg (PubSubKlioMessage): Message to remove.
"""
try:
# TODO: this method also has `retry`, `timeout` and metadata
# kwargs which we may be interested in using
self._client.acknowledge(self._sub_name, [psk_msg.ack_id])
except Exception as e:
# Note: we are just catching & logging any potential error we
# encounter. We will still remove the message from our message
# manager so we no longer try to extend.
self.mgr_logger.error(
f"Error encountered when trying to acknowledge {psk_msg} with "
f"ack ID '{psk_msg.ack_id}': {e}",
exc_info=True,
)
self.mgr_logger.warning(
f"The message {psk_msg} may be re-delivered due to Klio's "
"inability to acknowledge it."
)
else:
self.mgr_logger.info(
f"Acknowledged {psk_msg.kmsg_id}. Job is no longer processing "
"this message."
)
ENTITY_ID_TO_ACK_ID.pop(psk_msg.kmsg_id, None)
@staticmethod
def mark_done(kmsg_or_bytes):
"""Mark a KlioMessage as done and to be removed from handling.
This method just sets the PubSubKlioMessage.event object where then
in the next iteration in `MessageManager.manage`, it is then
acknowledged and removed from further "babysitting".
Args:
kmsg_or_bytes (klio_pb2.KlioMessage or bytes): the KlioMessage
(or a KlioMessage that has been serialzied to bytes) to be
marked as done.
"""
kmsg = kmsg_or_bytes
# TODO: either use klio.message.serializer.to_klio_message, or
# figure out how to handle when a parsed_message can't be parsed
# into a KlioMessage (will need to somehow get the klio context).
if not isinstance(kmsg_or_bytes, klio_pb2.KlioMessage):
kmsg = klio_pb2.KlioMessage()
kmsg.ParseFromString(kmsg_or_bytes)
entity_id = kmsg.data.element.decode("utf-8")
msg = ENTITY_ID_TO_ACK_ID.get(entity_id)
# This call, `set`, will tell the MessageManager that this
# message is now ready to be acknowledged and no longer being
# worked upon.
if msg:
msg.event.set()
else:
# NOTE: this logger exists as `self.mgr_logger`, but this method
# needs to be a staticmethod so we don't need to unnecessarily
# init the class in order to just mark a message as done.
mm_logger = logging.getLogger(
"klio.gke_direct_runner.message_manager"
)
mm_logger.warn(f"Unable to acknowledge {entity_id}: Not found.")
| StarcoderdataPython |
9630462 | import praw
from psaw import PushshiftAPI
import pandas as pd
import time
import datetime as dt
import json
import json
with open('data//subreddits.json') as json_file:
data = json.load(json_file)
subreddit_list=list(data.keys())
start_epoch=int(dt.datetime(2019, 4, 23).timestamp())
api = PushshiftAPI()
n_unique_commenters={}
unique_authors_subreddit={}
for index,subreddit in enumerate(subreddit_list):
authors=[]
gen = api.search_comments(subreddit=f'{subreddit}',after=start_epoch)
for x in gen:
authors.append(x.author)
authors=set(authors)
n_unique_commenters[subreddit]=len(authors)
unique_authors_subreddit[subreddit]=",".join(authors)
print(f"Done with {subreddit}, {index} of {len(subreddit_list)}")
time.sleep(1)
with open('data//unique_authors_list.json', 'w') as fp:
json.dump(unique_authors_subreddit2, fp)
with open('data//n_unique_authors.json', 'w') as fp:
json.dump(n_unique_commenters2, fp)
print("done") | StarcoderdataPython |
6567832 | import abc
import random
class Distribution(abc.ABC):
@abc.abstractmethod
def sample(self):
pass
class Uniform(Distribution):
def __init__(self, low: float, high: float):
self.low = low
self.high = high
def sample(self):
return random.uniform(self.low, self.high)
class Gaussian(Distribution):
def __init__(self, mean: float, std: float):
self.mean = mean
self.std = std
def sample(self):
return random.gauss(self.mean, self.std)
class TruncatedGaussian(Gaussian):
def __init__(self, mean: float, std: float, low: float = None, high: float = None):
super().__init__(mean, std)
self.low = low
self.high = high
def accept(self, sample):
if self.low is not None and sample < self.low:
return False
if self.high is not None and sample > self.high:
return False
return True
def sample(self):
r = super().sample()
while not self.accept(r):
r = super().sample()
return r | StarcoderdataPython |
246175 | <filename>setup.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
The setup script for the calibraxis package.
.. moduleauthor:: hbldh <<EMAIL>>
Created on 2016-04-08
'''
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import os
import sys
import re
from codecs import open
from setuptools import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py register')
os.system('python setup.py sdist upload')
os.system('python setup.py bdist_wheel upload')
sys.exit()
with open('calibraxis.py', 'r') as fd:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
def read(f):
return open(f, encoding='utf-8').read()
setup(
name='calibraxis',
version=version,
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/hbldh/calibraxis',
description='Autocalibration method for accelerometers, implemented in Python.',
long_description=read('README.rst'),
license='MIT',
keywords=['Calibration', 'Accelerometers'],
classifiers=[
'Development Status :: 4 - Beta',
'Operating System :: OS Independent',
'Intended Audience :: Science/Research',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Topic :: Software Development',
'Topic :: Scientific/Engineering',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
py_modules=['calibraxis'],
test_suite="tests",
zip_safe=False,
include_package_data=True,
install_requires=[
'numpy>=1.9.0',
'six>=1.9.0'
],
setup_requires=['pytest-runner', ],
tests_require=['pytest', ],
ext_modules=[],
entry_points={}
)
| StarcoderdataPython |
8148968 | <filename>openacademy/reports/__init__.py
from . import courses_report
| StarcoderdataPython |
6493249 | <filename>Old Releases/Windows Releases/WINDOWS v1.1.0/Source Code/Windows Development/MandarinInstaller.py
import subprocess
subprocess.call([r'INSTALLER.bat'])
| StarcoderdataPython |
1929742 | <gh_stars>0
"""A library to organize your terminal output.
https://github.com/markuskimius/screen-py
"""
import os
import sys
__copyright__ = "Copyright 2019 <NAME>"
__license__ = "Apache 2.0"
##############################################################################
# UTILITIES
class Terminal(object):
__DEFAULT_COLS = 120
__cols = None
@staticmethod
def width():
if Terminal.__cols is None:
# Memoize the terminal width
try:
Terminal.__cols = int(os.popen('tput cols', 'r').read())
except ValueError:
Terminal.__cols = Terminal.__DEFAULT_COLS
# Some terminals line wrap if you try to write to the last column
# so don't use that column
Terminal.__cols -= 1
return Terminal.__cols
class WidgetFormatter(object):
def __call__(self, lines, width=0, height=0):
return lines
class LeftFormatter(WidgetFormatter):
def __init__(self, parent_formatter=WidgetFormatter(), padding_char=' '):
self.__padding_char = padding_char
self.__parent_formatter = parent_formatter
def __call__(self, lines, width=0, height=0):
lines = self.__parent_formatter(lines, width, height)
for i, li in enumerate(lines):
slack = width - len(li)
padding = self.__padding_char * slack
lines[i] += padding[0:slack]
return lines
class RightFormatter(WidgetFormatter):
def __init__(self, parent_formatter=WidgetFormatter(), padding_char=' '):
self.__padding_char = padding_char
self.__parent_formatter = parent_formatter
def __call__(self, lines, width=0, height=0):
lines = self.__parent_formatter(lines, width, height)
for i, li in enumerate(lines):
slack = width - len(li)
padding = self.__padding_char * slack
lines[i] = padding[0:slack] + li
return lines
class CenterFormatter(WidgetFormatter):
def __init__(self, parent_formatter=WidgetFormatter(), padding_char=' '):
self.__padding_char = padding_char
self.__parent_formatter = parent_formatter
def __call__(self, lines, width=0, height=0):
lines = self.__parent_formatter(lines, width, height)
for i, li in enumerate(lines):
slack = width - len(li)
lslack = int(slack / 2)
rslack = width - (lslack + len(li))
lpadding = self.__padding_char * lslack
rpadding = self.__padding_char * rslack
lines[i] = lpadding[0:lslack] + li + rpadding[0:rslack]
return lines
class TopFormatter(WidgetFormatter):
def __init__(self, parent_formatter=WidgetFormatter(), padding_char=' '):
self.__padding_char = padding_char
self.__parent_formatter = parent_formatter
def __call__(self, lines, width=0, height=0):
lines = self.__parent_formatter(lines, width, height)
blank = self.__padding_char * width
blank = blank[0:width] # Just in case len(padding_char) > 1
for i in range(len(lines), height):
lines.append(blank)
return lines
class BottomFormatter(WidgetFormatter):
def __init__(self, parent_formatter=WidgetFormatter(), padding_char=' '):
self.__padding_char = padding_char
self.__parent_formatter = parent_formatter
def __call__(self, lines, width=0, height=0):
tlines = []
blines = self.__parent_formatter(lines, width, height)
blank = self.__padding_char * width
blank = blank[0:width] # Just in case len(padding_char) > 1
for i in range(len(blines), height):
tlines.append(blank)
return tlines + blines
class MiddleFormatter(WidgetFormatter):
def __init__(self, parent_formatter=WidgetFormatter(), padding_char=' '):
self.__padding_char = padding_char
self.__parent_formatter = parent_formatter
def __call__(self, lines, width=0, height=0):
tlines = []
clines = self.__parent_formatter(lines, width, height)
blines = []
blank = self.__padding_char * width
blank = blank[0:width] # Just in case len(padding_char) > 1
vslack = int((height - len(clines)) / 2)
for i in range(vslack):
tlines.append(blank)
for i in range(vslack + len(clines), height):
blines.append(blank)
return tlines + clines + blines
class ParagraphFormatter(WidgetFormatter):
def __init__(self, parent_formatter=WidgetFormatter()):
self.__parent_formatter = parent_formatter
def __call__(self, lines, width=0, height=0):
width = min(width, Terminal.width()) if width else Terminal.width()
lines = self.__parent_formatter(lines, width, height)
wrapped = []
for i, li in enumerate(lines):
while len(li):
wrapped.append(li[0:width])
li = li[width:]
# Paragraphs have at least an empty text
if len(wrapped) == 0:
wrapped.append('')
return wrapped
NON_FORMATTER = WidgetFormatter()
PARAGRAPH_FORMATTER = ParagraphFormatter()
TOP_LEFT_FORMATTER = TopFormatter(LeftFormatter())
TOP_RIGHT_FORMATTER = TopFormatter(RightFormatter())
TOP_CENTER_FORMATTER = TopFormatter(CenterFormatter())
##############################################################################
# WIDGETS
#
# Widgets go in boxes.
class Widget(object):
def width(self): return 0
def height(self): return 0
def format(self, width=None, height=None): pass
class StringWidget(Widget):
def __init__(self, string, formatter=PARAGRAPH_FORMATTER):
self.__string = str(string)
self.__formatter = formatter
def width(self):
lines = self.__string.split('\n')
return self.__width(lines)
def height(self):
lines = self.__string.split('\n')
return self.__height(lines)
def __width(self, lines):
lines = self.__formatter(lines)
width = 0
for li in lines:
width = max(width, len(li))
return width
def __height(self, lines):
lines = self.__formatter(lines)
return len(lines)
def format(self, width=None, height=None):
lines = self.__string.split('\n')
if width is None: width = self.__width(lines)
if height is None: height = self.__height(lines)
return self.__formatter(self.__string.split('\n'), width, height)
class ControlWidget(Widget):
def format(self, width=None, height=None): return []
class BreakWidget(ControlWidget): pass
class SoftBreak(BreakWidget): pass
class HardBreak(BreakWidget): pass
class FillWidget(Widget):
def __init__(self, fill_char='*'):
formatter = LeftFormatter(padding_char=fill_char)
formatter = TopFormatter(formatter, padding_char=fill_char)
self.__formatter = formatter
def format(self, width=None, height=None):
if width is None: width = self.width()
if height is None: height = self.height()
return self.__formatter([], width, height)
class HorizontalRule(FillWidget):
def __init__(self, rule_char='-'):
self.__rule_char = rule_char
super(HorizontalRule, self).__init__(rule_char)
def height(self):
return len(self.__rule_char.split('\n'))
class VerticalRule(FillWidget):
def __init__(self, rule_char='|'):
self.__rule_char = rule_char
super(VerticalRule, self).__init__(rule_char)
def width(self):
return len(self.__rule_char)
##############################################################################
# BOXES
#
# Boxes contain widgets or other boxes.
class Box(Widget):
class BoxLockedException(Exception): pass
def __init__(self):
self.__widgets = []
self.__locked = False
def close(self):
self.__locked = True
def add(self, widget):
if self.__locked: raise BoxLockedException()
self.__widgets.append(widget)
return widget
def remove(self, widget):
if self.__locked: raise BoxLockedException()
self.__widgets.remove(widget)
def __len__(self):
return len(self.__widgets)
def __iter__(self):
for widget in self.__widgets:
yield widget
def __getitem__(self, i):
return self.__widgets[i]
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
def softbreak(self):
self.add(SoftBreak())
def hardbreak(self):
self.add(HardBreak())
def hrule(self, rule_char='-'):
self.add(HorizontalRule(rule_char))
def vrule(self, rule_char='|'):
self.add(VerticalRule(rule_char))
def draw(self, WidgetType=None, *args, **kwargs):
if WidgetType is None:
WidgetType = TextBox
widget = WidgetType(*args, **kwargs)
self.__widgets.append(widget)
return widget
class WritableBox(Box):
def __init__(self):
super(WritableBox, self).__init__()
self.__buffer = ''
def write(self, *args, **kwargs):
for string in args:
self.__buffer += str(string)
lines = self.__buffer.split('\n')
for li in lines[0:-1]:
self.add(StringWidget(li))
self.__buffer = lines[-1]
def writeln(self, *args, **kwargs):
for string in args:
self.write('%s\n' % string, **kwargs)
if len(args) == 0:
self.write('\n')
def close(self):
if len(self.__buffer): self.write('\n')
super(WritableBox, self).close()
class HorizontalBox(WritableBox):
def __init__(self, num_padding=1, formatter=TOP_LEFT_FORMATTER):
super(HorizontalBox, self).__init__()
self.__num_padding = num_padding
self.__formatter = formatter
def width(self):
return self.__width()
def height(self):
return self.__height()
def __width(self):
iterator = super(HorizontalBox, self).__iter__()
width = 0
for i, widget in enumerate(iterator):
width += widget.width()
# Adjust for spacing between non-control widgets
if i > 0 and not isinstance(widget, ControlWidget):
width += self.__num_padding
return width
def __height(self):
iterator = super(HorizontalBox, self).__iter__()
height = 0
for i, widget in enumerate(iterator):
height = max(height, widget.height())
return max(height, super(HorizontalBox, self).height())
def format(self, width=None, height=None):
if height is None: height = self.__height()
if width is None: width = self.__width()
justified_widths = self.__justified_widths(width)
iterator = super(HorizontalBox, self).__iter__()
padding = ' ' * self.__num_padding
lines = [''] * height
for i, widget in enumerate(iterator):
jw = justified_widths[i]
if i > 0 and not isinstance(widget, ControlWidget):
for j in range(height):
lines[j] += padding
for j, li in enumerate(widget.format(jw, height)):
lines[j] += li
return self.__formatter(lines, width, height)
def __justified_widths(self, box_width):
adj_width = [None] * super(HorizontalBox, self).__len__()
nat_width = self.__width()
slack = box_width - nat_width
pos = 0
# Don't justify if there is nothing to justify
if len(adj_width) == 0:
return adj_width
# Don't justify if the row ends in a hard break
last_widget = super(HorizontalBox, self).__getitem__(-1)
if isinstance(last_widget, HardBreak):
return adj_width
# Justify the widgets
iterator = super(HorizontalBox, self).__iter__()
for i, widget in enumerate(iterator):
# No resizing of control widgets
if isinstance(widget, ControlWidget): continue
# Update the position for the padding
if i > 0: pos += self.__num_padding
# Magic calculation for perfectly resizing the boxes
width = widget.width()
remaining = nat_width - pos
adjustment = int(round(slack * width / remaining)) if remaining else 0
adj_width[i] = width + adjustment
# Update the running numbers
slack -= adjustment
pos += width
return adj_width
class VerticalBox(WritableBox):
def __init__(self, num_padding=1, formatter=TOP_LEFT_FORMATTER):
self.__num_padding = num_padding
self.__formatter = formatter
super(VerticalBox, self).__init__()
def width(self):
return self.__width()
def height(self):
return self.__height()
def __width(self):
iterator = super(VerticalBox, self).__iter__()
width = 0
for i, widget in enumerate(iterator):
width = max(width, widget.width())
return width
def __height(self):
iterator = super(VerticalBox, self).__iter__()
height = 0
for i, widget in enumerate(iterator):
# Adjust for spacing before non-control widgets
if (i > 0) and not isinstance(widget, ControlWidget):
height += self.__num_padding
height += widget.height()
return height
def format(self, width=None, height=None):
iterator = super(VerticalBox, self).__iter__()
lines = []
if width is None: width = self.__width()
if height is None: height = self.__height()
padding = [' ' * width] * self.__num_padding
for i, widget in enumerate(iterator):
# Adjust for spacing before non-control widgets
if (i > 0) and not isinstance(widget, ControlWidget):
lines += padding
for li in widget.format(width):
lines.append(li)
return self.__formatter(lines, width, height)
##############################################################################
# DERIVED BOXES
class TabularBox(HorizontalBox):
class InvalidAlignment(Exception): pass
def __init__(self, format, num_padding=1, formatter=TOP_CENTER_FORMATTER):
super(TabularBox, self).__init__(num_padding, formatter)
self.__columns = []
for f in format:
if f == '|': box = VerticalRule()
elif f == 'l': box = TextBox(TOP_LEFT_FORMATTER)
elif f == 'r': box = TextBox(TOP_RIGHT_FORMATTER)
elif f == 'c': box = TextBox(TOP_CENTER_FORMATTER)
else: raise TabularBox.InvalidAlignment('%s: Invalid alignment code' % f)
if isinstance(box, Box):
self.__columns.append(box)
super(TabularBox, self).add(box)
def write(self, *args, **kwargs):
for i, string in enumerate(args):
self.__columns[i].write(string, **kwargs)
def writeln(self, *args, **kwargs):
for i, string in enumerate(args):
self.__columns[i].writeln(string, **kwargs)
def hrule(self, *args, **kwargs):
for col in self.__columns:
col.hrule(*args, **kwargs)
def close(self):
for col in self.__columns:
col.close()
class TextBox(VerticalBox):
def __init__(self, formatter=TOP_LEFT_FORMATTER):
super(TextBox, self).__init__(num_padding=0, formatter=formatter)
class FlexBox(WritableBox):
def __init__(self, max_width=Terminal.width(), formatter=TOP_LEFT_FORMATTER, num_hpadding=1, num_vpadding=1):
self.__num_hpadding = num_hpadding
self.__num_vpadding = num_vpadding
self.__max_width = max_width
self.__formatter = formatter
self.__vbox = Box()
super(FlexBox, self).__init__()
def width(self):
return self.__vbox.width()
def height(self):
return self.__vbox.height()
def close(self):
iterator = super(FlexBox, self).__iter__()
maxwidth = self.__max_width
vbox = VerticalBox(self.__num_vpadding, self.__formatter)
hbox = HorizontalBox(self.__num_hpadding, self.__formatter)
# Arrange our widgets so widgets do not go past the terminal width
for i, widget in enumerate(iterator):
hbox.add(widget)
# If we added too much, break
if hbox.width() > maxwidth:
hbox.remove(widget) # Remove the last widget
vbox.add(hbox)
hbox = HorizontalBox(self.__num_hpadding, self.__formatter)
hbox.add(widget) # Add it back to the new hbox
# If requested, break
elif isinstance(widget, BreakWidget):
vbox.add(hbox)
hbox = HorizontalBox(self.__num_hpadding, self.__formatter)
# Last hbox
if len(hbox):
hbox.hardbreak()
vbox.add(hbox)
# Commit
self.__vbox = vbox
super(FlexBox, self).close()
def format(self, width=None, height=None):
return self.__vbox.format(width, height)
##############################################################################
# BOX DECORATORS
class TitledBox(VerticalBox):
def __init__(self, title, box, hrule='-', hrule_min=2):
decorated_title = '%s %s %s' % (hrule * hrule_min, title, hrule * hrule_min)
self.__title = StringWidget(decorated_title, CenterFormatter(padding_char=hrule))
self.__content = box
super(TitledBox, self).__init__(num_padding=0)
super(TitledBox, self).add(self.__title)
super(TitledBox, self).add(self.__content)
def close(self):
self.__content.close()
def add(self, widget):
self.__content.add(widget)
return widget
def remove(self, widget):
self.__content.remove(widget)
def __len__(self):
return len(self.__content)
def __iter__(self):
for widget in self.__content.__iter__():
yield widget
def __getitem__(self, i):
return self.__content[i]
def write(self, *args, **kwargs):
self.__content.write(*args, **kwargs)
def writeln(self, *args, **kwargs):
self.__content.writeln(*args, **kwargs)
def softbreak(self):
self.__content.softbreak()
def hardbreak(self):
self.__content.hardbreak()
def hrule(self, *args, **kwargs):
self.__content.hrule(*args, **kwargs)
def vrule(self, *args, **kwargs):
self.__content.vrule(*args, **kwargs)
def draw(self, WidgetType=TextBox, *args, **kwargs):
return self.__content.draw(WidgetType, *args, **kwargs)
##############################################################################
# SCREEN
class Screen(TitledBox):
def __init__(self, title, fp=sys.stdout, hrule='='):
self.__top_area = VerticalBox() # Top area
self.__console = None # Console in the top area
self.__fp = fp # We'll use this at __exit__
super(Screen, self).__init__(title, FlexBox(), hrule=hrule) # I am a FlexBox with a title!
super(Screen, self).add(self.__top_area) # Add the top area to the screen
super(Screen, self).hardbreak() # Other boxes go below the top area
def __get_console(self):
if self.__console == None:
self.__console = TextBox()
self.__top_area.add(self.__console)
return self.__console
def write(self, *args, **kwargs):
# Writing to the screen writes to the console area.
self.__get_console().write(*args, **kwargs)
def writeln(self, *args, **kwargs):
# Writing to the screen writes to the console area.
self.__get_console().writeln(*args, **kwargs)
def writebox(self, BoxType=TextBox, *args, **kwargs):
box = BoxType(*args, **kwargs) # Create the box
self.__top_area.add(box) # Add the box to the top area
self.__console = None # Add any new text to the next console widget
return box
def add(self, title, box):
# All boxes added to the Screen get a title
box = TitledBox(title, box) # Add a title
super(Screen, self).add(box) # Add the box to myself
return box
def draw(self, title, BoxType=TextBox, *args, **kwargs):
# All boxes added to the Screen get a title
box = BoxType(*args, **kwargs) # Create the box
box = TitledBox(title, box) # Add a title
super(Screen, self).add(box) # Add the box to myself
return box
def close(self):
super(Screen, self).close()
# Write it out to fp (sys.stdout by default)
for line in super(Screen, self).format():
self.__fp.write(str(line))
self.__fp.write('\n')
# Add an empty row at the end
self.__fp.write('\n')
| StarcoderdataPython |
8011478 | """
Modules that implement a Cape Explanation
"""
| StarcoderdataPython |
1765364 | <filename>pyxform/tests_v1/test_warnings.py
from pyxform.tests_v1.pyxform_test_case import PyxformTestCase
class TestWarnings(PyxformTestCase):
def test_l1(self):
self.assertPyxformXform(
name="test_l1",
md="""
| survey | | | |
| | type | name | hint |
| | text | some_text | a hint |
""",
instance__contains=[
'<some_text/>',
],
model__contains=[
'<bind nodeset="/test_l1/some_text" type="string"/>',
],
xml__contains=[
'<input ref="/test_l1/some_text">',
'<hint>a hint</hint>', # nopep8
'</input>',
],
)
def test_l2(self):
self.assertPyxformXform(
name="img_test",
md="""
| survey | | | |
| | type | name | image |
| | note | display_img_test | img_test.jpg |
""",
model__contains=[
'<bind nodeset="/img_test/display_img_test" readonly="true()" type="string"/>', # nopep8
],
instance__contains=[
'<display_img_test/>',
],
xml__contains=[
'<translation default="true()" lang="default">',
# and further down...
"""<label ref="jr:itext('/img_test/display_img_test:label')"/>""" # nopep8
],
)
| StarcoderdataPython |
8094848 | import discord
from discord.ext import commands
from characterRecord import *
class Sheets(commands.Cog):
"""Commands related to character sheets"""
def __init__(self, bot):
self.bot = bot
@commands.command(brief = "Create new sheet", description = "Create an empty character sheet")
async def newsheet(self, ctx, name):
sheet = CreateSheet()
sheet.new_sheet(name)
await ctx.send("`Created new charcter sheet with name {0}`".format(name))
@commands.command(brief = "Add to sheet", description = "Add line of data to charcter sheet")
async def addto(self, ctx, name, data):
sheet = WriteToSheet()
sheet.add_line(name, data)
if(sheet.add_line(name, data)):
await ctx.send("`Added line \"{0}\" to {1}`".format(data, name))
else:
await ctx.send("`Didn't add line to sheet`")
@commands.command(brief = "Print entire sheet", description = "Print entire character sheet")
async def showsheet(self, ctx, name):
sheet = ReadFromSheet()
await ctx.send("```{0}```".format(sheet.read_sheet(name)))
@commands.command(brief = "Read specific line", description = "Print specific data line from charcter sheet")
async def showline(self, ctx, name, data):
sheet = ReadFromSheet()
await ctx.send("```{0}```".format(sheet.read_sheet_data(name, data)))
| StarcoderdataPython |
293994 | <gh_stars>10-100
import pandas as pd
from yellowbrick.classifier import ThreshViz
from sklearn.linear_model import LogisticRegression
if __name__ == '__main__':
# Load the data set
data = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/spambase/spambase.data', header=None)
data.rename(columns={57:'is_spam'}, inplace=True)
features = [col for col in data.columns if col != 'is_spam']
# Extract the numpy arrays from the data frame
X = data[features].as_matrix()
y = data.is_spam.as_matrix()
# Instantiate the classification model and visualizer
logistic = LogisticRegression()
visualizer = ThreshViz(logistic)
visualizer.fit(X, y) # Fit the training data to the visualizer
g = visualizer.poof(outpath="images/thresholdviz.png") # Draw/show/poof the data
| StarcoderdataPython |
1943742 | <filename>lambda_functions/analyzer/binary_info.py
"""Keeps track of all information associated with and computed about a binary."""
import os
import subprocess
import tempfile
import time
from typing import Any, Dict, List, Set
import uuid
from lambda_functions.analyzer import analyzer_aws_lib, file_hash
from lambda_functions.analyzer.common import LOGGER
from lambda_functions.analyzer.yara_analyzer import YaraAnalyzer, YaraMatch
class BinaryInfo:
"""Organizes the analysis of a single binary blob in S3."""
def __init__(self, bucket_name: str, object_key: str, yara_analyzer: YaraAnalyzer) -> None:
"""Create a new BinaryInfo.
Args:
bucket_name: S3 bucket name.
object_key: S3 object key.
yara_analyzer: Analyzer built from a compiled rules file.
"""
self.bucket_name = bucket_name
self.object_key = object_key
self.s3_identifier = 'S3:{}:{}'.format(bucket_name, object_key)
self.download_path = os.path.join(
tempfile.gettempdir(), 'binaryalert_{}'.format(uuid.uuid4()))
self.yara_analyzer = yara_analyzer
# Computed after file download and analysis.
self.download_time_ms = 0.0
self.s3_last_modified = ''
self.s3_metadata: Dict[str, str] = dict()
self.computed_md5 = ''
self.computed_sha = ''
self.yara_matches: List[YaraMatch] = list()
def __str__(self) -> str:
"""Use the S3 identifier as the string representation of the binary."""
return self.s3_identifier
def _download_from_s3(self) -> None:
"""Download binary from S3 and measure elapsed time."""
LOGGER.debug('Downloading %s to %s', self.object_key, self.download_path)
start_time = time.time()
self.s3_last_modified, self.s3_metadata = analyzer_aws_lib.download_from_s3(
self.bucket_name, self.object_key, self.download_path)
self.download_time_ms = (time.time() - start_time) * 1000
def __enter__(self) -> Any: # mypy/typing doesn't support recursive type yet
"""Download the binary from S3 and run YARA analysis."""
self._download_from_s3()
self.computed_sha, self.computed_md5 = file_hash.compute_hashes(self.download_path)
LOGGER.debug('Running YARA analysis')
self.yara_matches = self.yara_analyzer.analyze(
self.download_path, original_target_path=self.filepath
)
return self
def __exit__(self, exception_type: Any, exception_value: Any, traceback: Any) -> None:
"""Shred and delete all /tmp files (including the downloaded binary)."""
# Note: This runs even during exception handling (it is the "with" context).
# The only temp file we explicitly create is self.download_path, but others can be left
# behind by subprocesses (e.g. pdftotext).
for root, dirs, files in os.walk(tempfile.gettempdir(), topdown=False):
for name in files:
subprocess.check_call(['shred', '--force', '--remove', os.path.join(root, name)])
for name in dirs:
os.rmdir(os.path.join(root, name))
@property
def matched_rule_ids(self) -> Set[str]:
"""A set of 'yara_file:rule_name' for each YARA match."""
return set('{}:{}'.format(match.rule_namespace, match.rule_name)
for match in self.yara_matches)
@property
def filepath(self) -> str:
"""The filepath from the S3 metadata, if present."""
return self.s3_metadata.get('filepath', '')
def save_matches_and_alert(
self, analyzer_version: int, dynamo_table_name: str, sns_topic_arn: str,
sns_enabled: bool = True) -> None:
"""Save match results to Dynamo and publish an alert to SNS if appropriate.
Args:
analyzer_version: The currently executing version of the Lambda function.
dynamo_table_name: Save YARA match results to this Dynamo table.
sns_topic_arn: Publish match alerts to this SNS topic ARN.
sns_enabled: If True, match alerts are sent to SNS when applicable.
"""
table = analyzer_aws_lib.DynamoMatchTable(dynamo_table_name)
needs_alert = table.save_matches(self, analyzer_version)
# Send alert if appropriate.
if needs_alert and sns_enabled:
LOGGER.info('Publishing a YARA match alert to %s', sns_topic_arn)
subject = '[BinaryAlert] {} matches a YARA rule'.format(
self.filepath or self.computed_sha)
analyzer_aws_lib.publish_to_sns(self, sns_topic_arn, subject)
def publish_negative_match_result(self, sns_topic_arn: str) -> None:
"""Publish a negative match result (no YARA matches found).
Args:
sns_topic_arn: Target topic ARN for negative match alerts.
"""
LOGGER.info('Publishing a negative match result to %s', sns_topic_arn)
subject = '[BinaryAlert] {} did not match any YARA rules'.format(
self.filepath or self.computed_sha)
analyzer_aws_lib.publish_to_sns(self, sns_topic_arn, subject)
def summary(self) -> Dict[str, Any]:
"""Generate a summary dictionary of binary attributes."""
matched_rules = {
'Rule{}'.format(index): {
'MatchedData': list(sorted(match.matched_data)), # E.g. "HelloWorld"
'MatchedStrings': list(sorted(match.matched_strings)), # E.g. "$string1"
'Meta': match.rule_metadata,
'RuleFile': match.rule_namespace,
'RuleName': match.rule_name
}
for index, match in enumerate(self.yara_matches, start=1)
}
return {
'FileInfo': {
# TODO: Include archive structure from yextend
'MD5': self.computed_md5,
'S3LastModified': self.s3_last_modified,
'S3Location': self.s3_identifier,
'S3Metadata': self.s3_metadata,
'SHA256': self.computed_sha
},
'MatchedRules': matched_rules,
'NumMatchedRules': len(self.yara_matches)
}
| StarcoderdataPython |
8031970 | from baseDatabaseManager import BaseDatabaseManager
class ProductManager():
@staticmethod
def deleteProductFromBasket(productId, customerId):
BaseDatabaseManager.databaseType.deleteProductFromBasket(productId, customerId)
@staticmethod
def getProductDetails(productId):
productDetails=BaseDatabaseManager.databaseType.getProductDetails(productId)
return productDetails
@staticmethod
def getFavoriteProducts(customerId):
favoriteProducts=BaseDatabaseManager.databaseType.getFavoriteProducts(customerId)
return favoriteProducts
@staticmethod
def addProductToCart(productId, customerId):
BaseDatabaseManager.databaseType.addProductToCart(productId, customerId)
@staticmethod
def addFavoriteToFavorites(productId, customerId):
isFavorite=BaseDatabaseManager.databaseType.addFavoriteToFavorites(productId, customerId)
return isFavorite
@staticmethod
def getAllProducts():
productsList=BaseDatabaseManager.databaseType.getAllProducts()
return productsList
@staticmethod
def getProductsWithCatId(catId):
productsList=BaseDatabaseManager.databaseType.getProductsWithCatId(catId)
return productsList
@staticmethod
def updateProductFromBasket(customerId, productId, proccess):
BaseDatabaseManager.databaseType.updateProductFromBasket(customerId, productId, proccess)
@staticmethod
def deleteProductFromBasket(productId, customerId):
BaseDatabaseManager.databaseType.deleteProductFromBasket(productId, customerId)
@staticmethod
def getBasket(customerId):
dataOfBasket=BaseDatabaseManager.databaseType.getBasket(customerId)
return dataOfBasket
| StarcoderdataPython |
1799574 | <gh_stars>1-10
"""
Copyright 2017 Neural Networks and Deep Learning lab, MIPT
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
"""
Here is an abstract class for neural network models based on Tensorflow.
If you use something different, ex. Pytorch, then write similar to this class, inherit it from
Trainable and Inferable interfaces and make a pull-request to deeppavlov.
"""
from abc import abstractmethod
from warnings import warn
import tensorflow as tf
from overrides import overrides
from deeppavlov.core.models.trainable import Trainable
from deeppavlov.core.models.inferable import Inferable
from deeppavlov.core.common.attributes import check_attr_true
from .tf_backend import TfModelMeta
class TFModel(Trainable, Inferable, metaclass=TfModelMeta):
def __init__(self, **kwargs):
self._saver = tf.train.Saver
super().__init__(**kwargs)
@abstractmethod
def _add_placeholders(self):
"""
Add all needed placeholders for a computational graph.
"""
pass
@abstractmethod
def run_sess(self, *args, **kwargs):
"""
1. Call _build_graph()
2. Define all comuptations.
3. Run tf.sess.
3. Reset state if needed.
:return:
"""
pass
@abstractmethod
def _train_step(self, features, *args):
"""
Define a single training step. Feed dict to tf session.
:param features: input features
:param args: any other inputs, including target vector, you need to pass for training
:return: metric to return, usually loss
"""
pass
@abstractmethod
def _forward(self, features, *args):
"""
Pass an instance to get a prediction.
:param features: input features
:param args: any other inputs you need to pass for training
:return: prediction
"""
pass
@check_attr_true('train_now')
def train(self, features, *args, **kwargs):
"""
Just a wrapper for a private method.
"""
return self._train_step(features, *args, **kwargs)
def infer(self, instance, *args):
"""
Just a wrapper for a private method.
"""
return self._forward(instance, *args)
def save(self):
save_path = str(self.save_path)
saver = tf.train.Saver()
print('\n:: saving model to {}'.format(save_path))
saver.save(self.sess, save_path)
print('model saved')
def get_checkpoint_state(self):
if self.load_path:
if self.load_path.parent.is_dir():
return tf.train.get_checkpoint_state(self.load_path.parent)
else:
warn('Provided `load_path` is incorrect!')
else:
warn('No `load_path` is provided for {}".format(self.__class__.__name__)')
@overrides
def load(self):
"""
Load session from checkpoint
"""
ckpt = self.get_checkpoint_state()
if ckpt and ckpt.model_checkpoint_path:
print('\n:: restoring checkpoint from', ckpt.model_checkpoint_path, '\n')
self._saver().restore(self.sess, ckpt.model_checkpoint_path)
print('session restored')
else:
print('\n:: <ERR> checkpoint not found! \n')
class SimpleTFModel(Trainable, Inferable, metaclass=TfModelMeta):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
| StarcoderdataPython |
11224635 | <reponame>Kelos-Zhu/pyleecan
# -*- coding: utf-8 -*-
from os import remove, getcwd
from os.path import isfile, join
import pytest
from unittest.mock import patch # for unittest of input
from numpy import ones, pi, array
from pyleecan.Classes.LamSlotMag import LamSlotMag
from pyleecan.Classes.LamSlotWind import LamSlotWind
from pyleecan.Classes.MachineSIPMSM import MachineSIPMSM
from pyleecan.Classes.MagnetType11 import MagnetType11
from pyleecan.Classes.SlotMPolar import SlotMPolar
from pyleecan.Classes.SlotW10 import SlotW10
from pyleecan.Classes.WindingDW1L import WindingDW1L
from pyleecan.Classes.Shaft import Shaft
from pyleecan.Functions.load import load
from pyleecan.Classes.InputCurrent import InputCurrent
from pyleecan.Classes.ImportGenVectLin import ImportGenVectLin
from pyleecan.Classes.ImportMatrixVal import ImportMatrixVal
from pyleecan.Classes.MagFEMM import MagFEMM
from pyleecan.Classes.Output import Output
from pyleecan.Classes.Simu1 import Simu1
from Tests.Validation.Machine.CEFC_Lam import CEFC_Lam
from Tests import DATA_DIR, save_load_path as save_path, x as logger
from pyleecan.Functions.load import (
load,
load_list,
load_dict,
LoadWrongDictClassError,
LoadWrongTypeError,
LoadSwitchError,
)
from pyleecan.Functions.Save.save_json import save_json
from pyleecan.Functions.Load.load_json import LoadMissingFileError
load_file_1 = join(DATA_DIR, "test_wrong_slot_load_1.json")
load_file_2 = join(DATA_DIR, "test_wrong_slot_load_2.json")
load_file_3 = join(DATA_DIR, "test_wrong_slot_load_3.json")
logger.info(save_path)
"""test for save and load fonctions"""
def test_save_load_machine():
"""Check that you can save and load a machine object
"""
# SetUp
test_obj = MachineSIPMSM(name="test", desc="test\non\nseveral lines")
test_obj.stator = LamSlotWind(L1=0.45)
test_obj.stator.slot = SlotW10(Zs=10, H0=0.21, W0=0.23)
test_obj.stator.winding = WindingDW1L(qs=5)
test_obj.rotor = LamSlotMag(L1=0.55)
test_obj.rotor.slot = SlotMPolar(W0=pi / 4)
test_obj.rotor.slot.magnet = [MagnetType11(Wmag=pi / 4, Hmag=3)]
test_obj.shaft = Shaft(Lshaft=0.65)
test_obj.frame = None
# Save Test
file_path = join(save_path, "test_machine.json")
if isfile(file_path):
remove(file_path)
assert isfile(file_path) == False
test_obj.save(file_path)
assert isfile(file_path)
# Load Test
result = load(file_path)
assert type(result) is MachineSIPMSM
assert result.name == "test"
assert result.desc == "test\non\nseveral lines"
assert type(result.stator) is LamSlotWind
assert result.stator.L1 == 0.45
assert type(result.stator.slot) is SlotW10
assert result.stator.slot.Zs == 10
assert result.stator.slot.H0 == 0.21
assert result.stator.slot.W0 == 0.23
assert type(result.stator.winding) is WindingDW1L
assert result.stator.winding.qs == 5
assert type(result.rotor) is LamSlotMag
assert result.rotor.L1 == 0.55
assert type(result.rotor.slot) is SlotMPolar
assert result.rotor.slot.W0 == pi / 4
assert type(result.rotor.slot.magnet) is list
assert type(result.rotor.slot.magnet[0]) is MagnetType11
assert len(result.rotor.slot.magnet) == 1
assert result.rotor.slot.magnet[0].Wmag == pi / 4
assert result.rotor.slot.magnet[0].Hmag == 3
assert type(result.shaft) is Shaft
assert result.shaft.Lshaft == 0.65
assert result.frame == None
def test_save_load_folder_path():
"""Save with a folder path
"""
simu = Simu1(name="SM_CEFC_001", machine=CEFC_Lam, struct=None)
# Definition of the enforced output of the electrical module
Nr = ImportMatrixVal(value=ones(1) * 3000)
Is = ImportMatrixVal(value=array([[2.25353053e02, 2.25353053e02, 2.25353053e02]]))
time = ImportGenVectLin(start=0, stop=1, num=1, endpoint=True)
angle = ImportGenVectLin(start=0, stop=2 * pi, num=1024, endpoint=False)
simu.input = InputCurrent(
Is=Is,
Ir=None, # No winding on the rotor
Nr=Nr,
angle_rotor=None, # Will be computed
time=time,
angle=angle,
)
# Definition of the magnetic simulation (no symmetry)
simu.mag = MagFEMM(type_BH_stator=2, type_BH_rotor=0, is_sliding_band=False)
simu.force = None
simu.struct = None
test_obj = Output(simu=simu)
test_obj.post.legend_name = "Slotless lamination"
loc_save_path = join(save_path, "FolderSaved")
file_path = join(loc_save_path, "FolderSaved.json")
logger.debug(loc_save_path)
logger.debug(file_path)
if isfile(file_path):
remove(file_path)
assert isfile(file_path) == False
test_obj.save(loc_save_path, is_folder=True)
assert isfile(file_path)
assert isfile(join(loc_save_path, "Material.json"))
assert isfile(join(loc_save_path, "M400-50A.json"))
assert isfile(join(loc_save_path, "CEFC_Lam.json"))
assert isfile(join(loc_save_path, "SM_CEFC_001.json"))
test_obj2 = load(loc_save_path)
assert test_obj == test_obj2
def test_save_load_just_name():
"""Save in a file and load
"""
test_obj = SlotW10(Zs=10)
file_path = join(getcwd(), "test_slot.json")
if isfile(file_path):
remove(file_path)
assert isfile(file_path) == False
test_obj.save("test_slot")
assert isfile(file_path)
result = load("test_slot")
assert type(result) is SlotW10
assert result.Zs == 10
# remove(file_path)
def test_load_error_missing():
"""Test that the load function can detect missing file
"""
with pytest.raises(LoadMissingFileError):
load(save_path)
def test_load_error_wrong_type():
"""Test that the load function can detect wrong type
"""
with pytest.raises(LoadWrongTypeError):
load(load_file_3)
with pytest.raises(LoadWrongTypeError):
load_list(load_file_2)
with pytest.raises(LoadWrongTypeError):
load_dict(load_file_3)
def test_load_error_missing_class():
"""Test that the load function can detect missing __class__
"""
with pytest.raises(
LoadWrongDictClassError, match='Key "__class__" missing in loaded file'
):
load(load_file_1)
def test_load_error_wrong_class():
"""Test that the load function can detect wrong __class__
"""
with pytest.raises(
LoadWrongDictClassError, match="SlotDoesntExist is not a pyleecan class"
):
load(load_file_2)
@patch.dict("pyleecan.Functions.load_switch.load_switch", {"list": None})
def test_load_switch():
"""Test that the load function can detect wrong load_switch dict
"""
with pytest.raises(LoadSwitchError):
load_list(load_file_3)
def test_save_load_list():
"""Test the save and load function of data structures
"""
# SetUp
test_obj_1 = MachineSIPMSM(name="test", desc="test\non\nseveral lines")
test_obj_1.stator = LamSlotWind(L1=0.45)
test_obj_1.stator.slot = SlotW10(Zs=10, H0=0.21, W0=0.23)
test_obj_1.stator.winding = WindingDW1L(qs=5)
test_obj_1.rotor = LamSlotMag(L1=0.55)
test_obj_1.rotor.slot = SlotMPolar(W0=pi / 4)
test_obj_1.rotor.slot.magnet = [MagnetType11(Wmag=pi / 4, Hmag=3)]
test_obj_1.shaft = Shaft(Lshaft=0.65)
test_obj_1.frame = None
test_obj_2 = LamSlotWind(L1=0.45)
test_obj_3 = {"H0": 0.001, "Zs": 10, "__class__": "ClassDoesntExist"}
test_obj_4 = tuple([1, 2, 3])
test_list = [
test_obj_4,
[test_obj_1, None],
{"test_obj_2": test_obj_2, "test_obj_list": [test_obj_3, None]},
]
# Save Test
file_path = join(save_path, "test_list.json")
if isfile(file_path):
remove(file_path)
assert isfile(file_path) == False
save_json(test_list, file_path)
assert isfile(file_path)
# Load Test
result_list = load_list(file_path)
# set tuple to None as save will do
test_list[0] = None
assert result_list == test_list
def test_save_load_dict():
"""Test the save and load function of data structures
"""
# SetUp
test_obj_1 = MachineSIPMSM(name="test", desc="test\non\nseveral lines")
test_obj_1.stator = LamSlotWind(L1=0.45)
test_obj_1.stator.slot = SlotW10(Zs=10, H0=0.21, W0=0.23)
test_obj_1.stator.winding = WindingDW1L(qs=5)
test_obj_1.rotor = LamSlotMag(L1=0.55)
test_obj_1.rotor.slot = SlotMPolar(W0=pi / 4)
test_obj_1.rotor.slot.magnet = [MagnetType11(Wmag=pi / 4, Hmag=3)]
test_obj_1.shaft = Shaft(Lshaft=0.65)
test_obj_1.frame = None
test_obj_2 = LamSlotWind(L1=0.45)
test_obj_3 = {"H0": 0.001, "Zs": 10, "__class__": "ClassDoesntExist"}
test_obj_4 = tuple([1, 2, 3])
test_dict = {
"tuple": test_obj_4,
"list": [test_obj_1, None],
"dict": {"test_obj_2": test_obj_2, "test_obj_list": [test_obj_3, None]},
}
# Save Test
file_path = join(save_path, "test_dict.json")
if isfile(file_path):
remove(file_path)
assert isfile(file_path) == False
save_json(test_dict, file_path)
assert isfile(file_path)
# Load Test
result_dict = load_dict(file_path)
# set tuple to None as save will do
test_dict["tuple"] = None
assert result_dict == test_dict
@pytest.mark.long
@pytest.mark.FEMM
def test_save_hdf5():
"""Save in hdf5 file
"""
simu = Simu1(name="SM_CEFC_001", machine=CEFC_Lam, struct=None)
# Definition of the enforced output of the electrical module
Nr = ImportMatrixVal(value=ones(1) * 3000)
Is = ImportMatrixVal(value=array([[2.25353053e02, 2.25353053e02, 2.25353053e02]]))
time = ImportGenVectLin(start=0, stop=1, num=1, endpoint=True)
angle = ImportGenVectLin(start=0, stop=2 * pi, num=1024, endpoint=False)
simu.input = InputCurrent(
Is=Is,
Ir=None, # No winding on the rotor
Nr=Nr,
angle_rotor=None, # Will be computed
time=time,
angle=angle,
)
# Definition of the magnetic simulation (no symmetry)
simu.mag = MagFEMM(type_BH_stator=2, type_BH_rotor=0, is_sliding_band=False)
simu.force = None
simu.struct = None
test_obj = Output(simu=simu)
test_obj.simu.run()
test_obj.post.legend_name = "Slotless lamination"
file_path = join(save_path, "test_save_h5.h5")
logger.debug(file_path)
if isfile(file_path):
remove(file_path)
assert isfile(file_path) == False
test_obj.save(file_path)
assert isfile(file_path)
test_obj2 = load(file_path)
assert test_obj == test_obj2
@pytest.mark.long
@pytest.mark.FEMM
def test_save_json():
"""Save in json file
"""
simu = Simu1(name="SM_CEFC_001", machine=CEFC_Lam, struct=None)
# Definition of the enforced output of the electrical module
Nr = ImportMatrixVal(value=ones(1) * 3000)
Is = ImportMatrixVal(value=array([[2.25353053e02, 2.25353053e02, 2.25353053e02]]))
time = ImportGenVectLin(start=0, stop=1, num=1, endpoint=True)
angle = ImportGenVectLin(start=0, stop=2 * pi, num=1024, endpoint=False)
simu.input = InputCurrent(
Is=Is,
Ir=None, # No winding on the rotor
Nr=Nr,
angle_rotor=None, # Will be computed
time=time,
angle=angle,
)
# Definition of the magnetic simulation (no symmetry)
simu.mag = MagFEMM(type_BH_stator=2, type_BH_rotor=0, is_sliding_band=False)
simu.force = None
simu.struct = None
test_obj = Output(simu=simu)
test_obj.simu.run()
test_obj.post.legend_name = "Slotless lamination"
file_path = join(save_path, "test_save_json.json")
logger.debug(file_path)
if isfile(file_path):
remove(file_path)
assert isfile(file_path) == False
test_obj.save(file_path)
assert isfile(file_path)
test_obj2 = load(file_path)
assert test_obj == test_obj2
| StarcoderdataPython |
1986770 | import streamlit as st
import amplitude
import utils
import loader
import bisect
import random
import plotly as plt
import plotly.express as px
import plotly.graph_objects as go
import numpy as np
import math
import os
import pandas as pd
import session
import urllib.parse
DO_IT_BY_RANGE = (
True # DEFINES IF WE SHOULD RUN OUR CODE BY METHOD 1 (TRUE) OR 2 (FALSE)
)
# METHOD 1 IS DIVIDING THE RANGE OF VALUES IN 4 EQUAL PARTS IN SCORE VALUE
# METHOD 2 IS DIVIDING OUR ACTIVITIES IN GROUPS OF ROUGHLY EQUAL SIZE AFTER RANKING THEM
# INITIAL DATA PROCESSING
def get_score_groups(config, session_state, slider_value):
""" Takes our data and splits it into 4 sectors for use by our diagram generator """
# uf_num = utils.get_place_id_by_names(session_state.state)
if (
session_state.city_name != "Todos"
or session_state.health_region_name != "Todos"
):
endpoint = "health_region"
col = "health_region_id"
value = session_state.health_region_id
place_name = session_state.health_region_name + " (Região de Saúde)"
else:
endpoint = "state"
col = "state_num_id"
value = session_state.state_num_id
place_name = session_state.state_name + " (Estado)"
economic_data = loader.read_data(
"br",
config,
config["br"]["api"]["endpoints"]["safereopen"]["economic_data"][endpoint],
).query(f"{col} == {value}")
CNAE_sectors = loader.read_data(
"br", config, config["br"]["api"]["endpoints"]["safereopen"]["cnae_sectors"]
)
CNAE_sectors = dict(zip(CNAE_sectors.cnae, CNAE_sectors.activity))
economic_data["activity_name"] = economic_data.apply(
lambda row: CNAE_sectors[row["cnae"]], axis=1
)
return (
gen_sorted_sectors(economic_data, slider_value, DO_IT_BY_RANGE,),
economic_data,
place_name,
)
def gen_sorted_sectors(sectors_data, slider_value, by_range=True):
""" Cleans the data and separates in those 4 groups for later use by the table generator """
column_name = "cd_id_" + "%02d" % (int(slider_value / 10))
kept_columns = [
"cnae",
"n_employee",
"security_index",
"total_wage_bill",
"sector",
column_name,
"activity_name",
]
data_for_objects = sectors_data[kept_columns]
data_for_objects = data_for_objects.rename(columns={column_name: "score"})
sectors = data_for_objects.to_dict(orient="records")
sectors.sort(key=lambda x: x["score"])
for i in range(len(sectors)):
sectors[i]["index"] = len(sectors) - i
if by_range:
sector_groups = chunks_by_range(sectors, "score", 4)
else:
sector_groups = list(chunks(sectors, 4))
return sector_groups
def chunks_by_range(target_list, key, n):
""" Divides a list of dictionaries by a given key through the method 1 group division method"""
# For use in a list of dicts and to sort them by a specific key
split_indexes = range_separators_indexes(
[element[key] for element in target_list], n
)
chunks = []
last = 0
for i in range(n - 1):
chunks.append(target_list[last : split_indexes[i]])
last = split_indexes[i]
chunks.append(target_list[last::])
return chunks
def range_separators_indexes(values, n):
""" Given a list of values separates them into n chunks by the method 1 and returns the index of cutting"""
# Values must be ordered from lowest to highest
separations = [
(((values[-1] - values[0]) / (n)) * (order + 1)) + values[0]
for order in range(n - 1)
]
return [
bisect.bisect_right(values, separationvalue) for separationvalue in separations
]
def chunks(l, n):
"""
Yields n sequential chunks of l. Used for our sector splitting protocol in method2
"""
# Values should be sorted
d, r = divmod(len(l), n)
for i in range(n):
si = (d + 1) * (i if i < r else r) + d * (0 if i < r else i - r)
yield l[si : si + (d + 1 if i < r else d)]
# SEÇÃO DE INTRODUÇÃO
def gen_intro(alert):
if alert == "baixo":
st.write(
"""
<div class="base-wrapper">
<div class="section-header primary-span">VEJA OS SETORES MAIS SEGUROS PARA REABRIR</div><br>
<div class="ambassador-question"><b>Legal, seu município/regional/estado está em risco <span style="color:#02B529;">BAIXO</span>! Isso significa que já é adequado pensar em retomar as atividades econômicas gradualmente.</b> Nós compilamos aqui dados econômicos do seu estado para retomada segura de atividades econômicas, ordenadas com critérios objetivos.</div>
</div>""",
unsafe_allow_html=True,
)
else:
st.write(
"""
<div class="base-wrapper">
<div class="section-header primary-span">VEJA OS SETORES MAIS SEGUROS PARA REABRIR</div><br>
<div class="ambassador-question"><b>Opa, seu município/regional/estado ainda não está verde! Isso significa que <span style="color:#dd2c00;">não é o momento</span> de retomar as atividades econômicas.</b> No entanto, para fins de planejamento a ser implementado quando a doença for controlada, compilamos aqui dados econômicos do seu estado para retomada segura de atividades econômicas, ordenadas com critérios objetivos.</div>
</div>""",
unsafe_allow_html=True,
)
def gen_illustrative_plot(sectors_data, session_state, place_name):
""" Generates our illustrative sector diagram Version saude v2 """
text = f"""
<div class="saude-alert-banner saude-blue-bg mb" style="margin-bottom: 0px;">
<div class="base-wrapper flex flex-column" style="margin-top: 0px;">
<div class="flex flex-row flex-space-between flex-align-items-center">
<span class="white-span header p1"> Ordem de Retomada dos Setores | {place_name}</span>
</div>
<span class="white-span p3">Sugerimos uma retomada <b>em fases</b>, a começar pelos <b>setores mais seguros</b> e com <b>maior contribuição econômica.</b></span>
<div class="flex flex-row flex-m-column">"""
names_in_order = list(reversed(["d", "c", "b", "a"]))
for index, sector_dict in enumerate(reversed(sectors_data)):
text += gen_sector_plot_card(names_in_order[index], sector_dict, size_sectors=3)
text += """
</div>
</div>
<div class="saude-white-banner-pt0"></div>
</div>
<div class="saude-white-banner-pt2">
<div class="base-wrapper flex flex-column" style="margin-top: 0px;">
<div class="saude-banner-arrow-body"></div>
<div class="saude-banner-arrow-tip">
<i class="saude-arrow right"></i>
</div>
<div class="saude-banner-button high-security">Seguro</div>
<div class="saude-banner-button high-economy">Forte</div>
<div class="saude-banner-desc">
<b>Segurança Sanitária</b> mede o risco de exposição à Covid-19 dos trabalhadores de cada atividade econômica.
</div>
<div class="saude-banner-desc">
<b>Contribuição Econômica</b> é medida da massa salarial dos setores formais e informais de cada atividade econômica.<br>(Veja mais em Metodologia)
</div>
<div class="saude-banner-button low-security">Inseguro</div>
<div class="saude-banner-button low-economy">Fraca</div>
</div>
</div>"""
text += gen_slider_header()
st.write(text, unsafe_allow_html=True)
# Invert the order
st.write(
f"""<iframe src="resources/saude-inverter.html?obj1=Caso queira, altere abaixo o peso dado à Segurança Sanitária&obj2=Ordem de Retomada dos Setores |" height="0" width="0"></iframe>""",
unsafe_allow_html=True,
)
def gen_sector_plot_card(sector_name, sector_data, size_sectors=5):
""" Generates One specific card from the sector diagram version saude v2"""
titles = {"a": "Fase 1 ✅", "b": "Fase 2 🙌", "c": "Fase 3 ‼", "d": "Fase 4 ⚠"}
redirect_id_conversion = {"a": 3, "b": 2, "c": 1, "d": 0}
redirect_id = "saude-table-" + str(redirect_id_conversion[sector_name])
top_n_sectors = sector_data[-size_sectors::]
size_rest = max(0, len(sector_data) - size_sectors)
continuation_text = f"<b>+ {size_rest} setor{['','es'][int(size_rest >= 2)]} do grupo<br> <a href='#{redirect_id}' style='color:#00003d;'>(clique aqui para acessar)</a></b>"
# The last 5 are the best
item_list = "<br>".join(["- " + i["activity_name"] for i in top_n_sectors])
average_wage = int(
sum([float(i["total_wage_bill"]) for i in top_n_sectors]) / size_sectors
)
num_people = sum([int(i["n_employee"]) for i in top_n_sectors])
text = f"""
<div class="saude-indicator-card flex flex-column mr" style="z-index:1;display:inline-block;position:relative;">
<span class="saude-card-header-v2">{titles[sector_name]}</span>
<span class="saude-card-list-v2">
{item_list}
</span>
<div class="flex flex-row flex-justify-space-between mt" style="width:250px;">
</div>
<div class="saude-card-redirect">
{continuation_text}
</div>
<div class="saude-card-display-text-v2 sdcardtext-left">
<span class="lighter"><NAME>:<br></span>
<span class="bold">R$ {convert_money(average_wage)}</span>
</div>
<div class="saude-card-display-text-v2 sdcardtext-right">
<span class="lighter">Número de Trabalhadores:<br></span>
<span class="bold">{convert_money(num_people)}</span>
</div>
</div>"""
return text
def convert_money(money):
""" Can be used later to make money look like whatever we want, but a of
now just adding the decimal separator should be enough
"""
return f"{int(money):,}".replace(",", ".")
# SEÇÃO DE SELEÇÃO DE PESOS
def gen_slider(session_state):
""" Generates the weight slider we see after the initial sector diagram and saves it to session_state"""
radio_label = "Caso queira, altere abaixo o peso dado à Segurança Sanitária:"
# Code in order to horizontalize the radio buttons
radio_horizontalization_html = utils.get_radio_horizontalization_html(radio_label)
session_state.saude_ordem_data["slider_value"] = st.radio(
radio_label, [70, 80, 90, 100]
)
# print("VALOR SELECIONADO:", session_state.saude_ordem_data["slider_value"])
st.write(
f"""
<div class="base-wrapper">
{radio_horizontalization_html}
<div class="saude-slider-value-display"><b>Peso selecionado (Segurança): {session_state.saude_ordem_data["slider_value"]}%</b> | Peso restante para Economia: {100 - session_state.saude_ordem_data["slider_value"]}%</div>
</div>""",
unsafe_allow_html=True,
)
amplitude.gen_user(utils.get_server_session()).safe_log_event(
"chose saude_slider_value",
session_state,
event_args={"slider_value": session_state.saude_ordem_data["slider_value"]},
)
# st.write(radio_horizontalization_html,unsafe_allow_html=True)
def gen_slider_header():
return f"""<div class="base-wrapper">
<div class="saude-slider-wrapper">
<span class="section-header primary-span">ESCOLHA O PESO PARA A SEGURANÇA SANITÁRIA</span><p>
<span class="ambassador-question" style="width:80%;max-width:1000px;"><br><b>O peso determina em qual fase classificamos cada setor econômico.</b> O peso padrão utilizado é de <b>70% para Segurança Sanitária e 30% para Contribuição Econômica</b> - a partir desse valor você pode atribuir mais peso para Segurança (mais detalhes na Metodologia).
Este parâmetro pode ser alterado abaixo; entre em contato conosco para mais detalhes.</span><p>
</div>
</div>"""
# SEÇÃO DE DETALHES (INCLUDES THE DETAILED PLOT AND THE FULL DATA DOWNLOAD BUTTON)
def gen_detailed_vision(economic_data, session_state, config):
""" Uses session_state to decided wheter to hide or show the plot """
st.write(
f"""
<div class="base-wrapper">
<span style="width: 80%; max-width: 1000px; margin-top: -50px;">
<i><b>Clique em "Visão Detalhada" para ver o gráfico completo com todas as informações.</b></i>
</span><br>""",
unsafe_allow_html=True,
)
if st.button(
"Visão Detalhada"
): # If the button is clicked just alternate the opened flag and plot it
amplitude.gen_user(utils.get_server_session()).safe_log_event( # Logs the event
"picked saude_em_ordem_detailed_view",
session_state,
event_args={
"state": session_state.state_name,
"city": session_state.city_name,
},
)
session_state.saude_ordem_data[
"opened_detailed_view"
] = not session_state.saude_ordem_data["opened_detailed_view"]
if session_state.saude_ordem_data["opened_detailed_view"] is True:
display_detailed_plot(economic_data, session_state)
else: # If the button is not clicked plot it as well but do not alter the flag
if session_state.saude_ordem_data["opened_detailed_view"] is True:
display_detailed_plot(economic_data, session_state)
utils.stylizeButton(
name="Visão Detalhada",
style_string="""border: 1px solid var(--main-white);box-sizing: border-box;border-radius: 15px; width: auto;padding: 0.5em;text-transform: uppercase;font-family: var(--main-header-font-family);color: var(--main-white);background-color: var(--main-primary);font-weight: bold;text-align: center;text-decoration: none;font-size: 18px;animation-name: fadein;animation-duration: 3s;margin-top: 1em;""",
session_state=session_state)
def get_clean_data(in_econ_data):
cols = in_econ_data.columns.tolist()
cols.insert(2, "activity_name")
cols = cols[:-1]
economic_data = in_econ_data[cols]
to_drop_columns = [
i
for i in list(economic_data.columns)
if ("cd_id" in i and (i.split("_")[-1] not in ["07", "08", "09", "10"]))
]
economic_data = economic_data.drop(to_drop_columns, axis=1)
return economic_data
def convert_dataframe_to_html(df, name="dados"):
uri = urllib.parse.quote(df.to_csv(index=False))
file_name = "saude_em_ordem_" + name.replace(" ", "_") + ".csv"
return f'<a href="data:application/octet-stream,{uri}" download="{file_name}" class="btn-ambassador">Baixar Dados Completos</a>'
def display_detailed_plot(economic_data, session_state):
fig = plot_cnae(
economic_data, session_state.saude_ordem_data["slider_value"], DO_IT_BY_RANGE,
)
st.write(
"""
<div class="base-wrapper">
<span class="ambassador-question" style="width: 80%; max-width: 1000px;">
<b>Passe o mouse sobre cada bolinha para ver todos os detalhes daquela atividade econômica.</b><br>
Se você está no celular é só clicar na bolinha. Além disso talvez seja necessário rolar a tela para ver o gráfico inteiro.
</span>
</div>""",
unsafe_allow_html=True,
)
st.plotly_chart(fig, use_container_width=True)
def plot_cnae(economic_data, slider_value, by_range=True):
""" Will generate the colored plot seen in the detailed view section """
fig = go.Figure()
column_name = "cd_id_" + "%02d" % (int(slider_value / 10))
numpy_econ_version = economic_data[
["activity_name", column_name, "total_wage_bill"]
].to_numpy()
fig.add_trace(
go.Scatter(
x=economic_data["total_wage_bill"],
y=economic_data["security_index"],
name="Atividade Econômica",
mode="markers",
customdata=numpy_econ_version,
text=economic_data["sector"],
hovertemplate="<b>%{customdata[0]}</b><br><br>"
+ "Pontuação: %{customdata[1]}<br>"
+ "índice de Segurança: %{y:,.2f}<br>"
+ "Massa Salarial: R$%{customdata[2]:.0}<br>"
+ "Setor: %{text}"
+ "<extra></extra>",
)
)
fig.update_layout(
xaxis_type="log",
xaxis_title="Contribuição Econômica",
yaxis_title="Índice de Segurança",
font=dict(family="Oswald", size=12, color="#000000"),
)
wage_range = [
int(np.amin(economic_data["total_wage_bill"].values)),
int(np.amax(economic_data["total_wage_bill"].values)),
]
safety_range = [
int(np.amin(economic_data["security_index"].values)),
int(np.amax(economic_data["security_index"].values)),
]
sorted_score = sorted(economic_data[column_name])
if by_range:
score_group_limits = (
[0]
+ [
sorted_score[index]
for index in range_separators_indexes(sorted_score, 4)
]
+ [200]
)
else:
score_group_limits = (
[0] + [sorted_score[i] for i in chunk_indexes(len(sorted_score), 4)] + [200]
)
gen_isoscore_lines(fig, score_group_limits, wage_range, slider_value / 100)
fig.update_layout( # The 0.85 and 1.15 factors are to add some margin to the plot
xaxis=dict(
range=[
math.log(wage_range[0] * 0.85, 10),
math.log(wage_range[1] * 1.15, 10),
]
),
yaxis=dict(
range=[safety_range[0] * 0.95, safety_range[1] * 1.05]
), # Same reason for 0.95 and 1.05
height=540,
width=900,
)
return fig
def chunk_indexes(size, n):
"""
Similar to the chunks() method but it gives us the splitting indexes
"""
last = 0
while n > 1:
new_index = last + math.ceil(size / n)
yield new_index
size = size - math.ceil(size / n)
last = new_index
n = n - 1
def gen_isoscore_lines(fig, score_parts, wage_range, weight):
"""
Goes through each value defining a iso-score line and draws it on the plot with a colored area.
Must also include the minimum limit and the maximum limit in score_parts if we want 4 shaded areas we include 5 lines
and the plot will be colored between line 1 and 2, 2 and 3, 3 and 4 and 4 and 5 totalling 4 parts
"""
# x is wage_range
x_data = np.logspace(
np.log(wage_range[0] * 0.85), np.log(wage_range[1] * 1.15), 50, base=np.e
)
names = ["Nan", "Fase 4", "Fase 3", "Fase 2", "Fase 1"]
area_colors = [
"#FFFFFF",
"rgba(252,40,3,0.2)",
"rgba(252,190,3,0.2)",
"rgba(227,252,3,0.2)",
"rgba(3,252,23,0.2)",
]
legend_visibility = [False, True, True, True, True]
for index, score in enumerate(score_parts):
y_data = np.power(
np.divide(score, np.power(np.log(x_data), 1 - weight)), 1 / weight
)
fig.add_trace(
go.Scatter(
x=x_data,
y=y_data,
fill="tonexty",
mode="none",
name=names[index],
line_color=area_colors[index],
fillcolor=area_colors[index],
visible=True,
showlegend=legend_visibility[index],
)
)
# SEÇÃO DE TABELAS DE SETORES
def gen_sector_tables(
session_state,
score_groups,
config,
default_size=5,
download=False,
econ_data=None,
download_name="dados",
):
"""
Major function that will generate all the tables from all the sectors.
Uses session_state to decided if the table is open or closed
"""
text = ""
if download:
clean_econ_data = get_clean_data(econ_data)
download_text = convert_dataframe_to_html(clean_econ_data, name=download_name)
else:
# download_text = f"""
# <a href="" download="dados_estado.csv" class="btn-ambassador disabled">
# Baixar dados (Desativado)
# </a>"""
download_text = " "
st.write(
f"""
<div class="base-wrapper">
<span class="section-header primary-span">TABELAS DE CONTRIBUIÇÃO DOS SETORES</span><p><br>
<span class="ambassador-question">Abaixo você pode conferir todos os setores de cada grupo de apresentados, ordenados pelo <b>índice de priorização de reabertura Saúde em Ordem.</b></span>
<div><br>
<div class="saude-download-clean-data-button-div">{download_text}
</div>""",
unsafe_allow_html=True,
)
for table_index in reversed(range(4)):
number = str(4 - table_index)
# We create it all under a button but the table will be shown either way
# The button is merely to alternate the state between open and closed
if st.button("Mostrar/Ocultar mais da Fase " + number):
session_state.saude_ordem_data["opened_tables"][
table_index
] = not session_state.saude_ordem_data["opened_tables"][table_index]
gen_single_table(session_state, score_groups, table_index, default_size)
else:
gen_single_table(session_state, score_groups, table_index, default_size)
utils.stylizeButton(
name="Mostrar/Ocultar mais da Fase " + number,
style_string="""border: 1px solid var(--main-white);box-sizing: border-box;border-radius: 15px; width: auto;padding: 0.5em;text-transform: uppercase;font-family: var(--main-header-font-family);color: var(--main-white);background-color: var(--main-primary);font-weight: bold;text-align: center;text-decoration: none;font-size: 18px;animation-name: fadein;animation-duration: 3s;margin-top: 1em;""",
session_state=session_state,
)
def gen_single_table(session_state, score_groups, data_index, n=5):
""" Generates an entire table for one sector given the data we have and the index of such sector from D to A """
text = "" # Our HTML will be stored here
# Constants
titles = ["Fase 4 ⚠", "Fase 3 ‼", "Fase 2 🙌", "Fase 1 ✅"]
safety_statuses = [
[["Inseguro", "#FF5F6B"], ["Fraco", "#FF5F6B"]],
[["Inseguro", "#FF5F6B"], ["Forte", "#02BC17"]],
[["Seguro", "#02BC17"], ["Fraco", "#FF5F6B"]],
[["Seguro", "#02BC17"], ["Forte", "#02BC17"]],
]
safety_display = safety_statuses[data_index]
# If the user chose to open the table we extende the amount of rows to the full size of the group
if session_state.saude_ordem_data["opened_tables"][data_index] is True:
n = len(score_groups[data_index])
else:
n = min(n, len(score_groups[data_index])) # goes to a max of n
table_id = "saude-table-" + str(data_index)
# print("Quantos itens selecionamos?", n)
working_data = list(reversed(score_groups[data_index][-n:]))
proportion = (
str((n + 1) * 5) + "vw"
) # The height of our table so we can draw the lines
total_workers = sum([sec_data["n_employee"] for sec_data in working_data])
total_wages = sum([sec_data["total_wage_bill"] for sec_data in working_data])
text += f"""<div class="saude-table" id="{table_id}">
<div class="saude-table-title-box">
<div class="saude-table-title">{titles[data_index]}</div>
<div class="saude-table-title-security-label">Segurança Sanitária</div>
<div class="saude-table-title-economy-label">Contribuição Econômica</div>
<div class="saude-table-title-button tbsecurity" style="background: {safety_display[0][1]};">{safety_display[0][0]}</div>
<div class="saude-table-title-button tbeconomy" style="background: {safety_display[1][1]};">{safety_display[1][0]}</div>
</div>
<div class="saude-table-head-box">
<div class="saude-table-line tl0" style="height: {proportion};"></div>
<div class="saude-table-line tl1" style="height: {proportion};"></div>
<div class="saude-table-line tl2" style="height: {proportion};"></div>
<div class="saude-table-line tl3" style="height: {proportion};"></div>
<div class="saude-table-field tt0">Ranking</div>
<div class="saude-table-field tt1">Nome do setor</div>
<div class="saude-table-field tt2">Índice de Segurança Sanitária</div>
<div class="saude-table-field tt3">N°de Trabalhadores</div>
<div class="saude-table-field tt4">Massa Salarial</div>
</div>"""
for index, sector_data in enumerate(working_data):
text += gen_sector_table_row(sector_data, index)
text += f"""<div class="saude-table-total-box">
<div class="saude-table-field te1">Total</div>
<div class="saude-table-field te3">{convert_money(total_workers)}</div>
<div class="saude-table-field te4">R$ {convert_money(total_wages)}</div>
</div>
<div class="saude-table-endspacer">
</div>
</div>"""
st.write(text, unsafe_allow_html=True)
return text
def gen_sector_table_row(sector_data, row_index):
""" Generates a row of a table given the necessary information coming from a sector data row """
return f"""<div class="saude-table-row {["tlblue","tlwhite"][row_index % 2]}">
<div class="saude-table-field tf0">{sector_data["index"]}</div>
<div class="saude-table-field tf1">{sector_data["activity_name"]}</div>
<div class="saude-table-field tf2">{"%0.2f"%sector_data["security_index"]}</div>
<div class="saude-table-field tf3">{convert_money(sector_data["n_employee"])}</div>
<div class="saude-table-field tf4">R$ {convert_money(sector_data["total_wage_bill"])}</div>
</div>"""
# SEÇÃO DE PROTOCOLOS
def gen_protocols_section():
st.write(
"""
<div class="base-wrapper">
<span class="section-header primary-span">
DIRETRIZES PARA A ELABORAÇÃO DE PROTOCOLOS DE REABERTURA
</span><br><br>
<span class="ambassador-question"><br>
<b>Eliminação</b> – contempla a transferência para o trabalho remoto, ou seja, elimina riscos ocupacionais. Mesmo que a residência do funcionário não tenha a infraestrutura necessária, a transferência de computadores ou melhorias de acesso à internet são medidas possíveis e de baixo custo, com fácil implementação.
<br><br>
<b>Substituição</b> – consiste em substituir riscos onde eles são inevitáveis, por um de menor magnitude. Vale assinalar os times que são ou não essenciais no trabalho presencial e segmentar a força de trabalho, mantendo somente o mínimo necessário de operação presencial e reduzindo o contato próximo entre times diferentes.
<br><br>
<b>Controles de engenharia</b> – fala de aspectos estruturais do ambiente de trabalho. No caso do coronavírus, podem ser citados como exemplos o controle de ventilação e purificação de ar, reduzindo o risco da fonte e não no nível individual. São fatores altamente ligados ao contexto, seja da atividade, seja do espaço físico onde ocorrem.
<br><br>
<b>Controles administrativos</b> – consiste nos controles de fluxo e quantidade de pessoas no ambiente de trabalho (de-densificação do ambiente) e sobre protocolos e regras a serem seguidos, como periodicidade e métodos de limpeza, montagem de plantões e/ou escala, organização de filas para elevadores e uso de áreas comuns, proibição de reuniões presenciais, reorganização das estações de trabalho para aumentar distância entre pessoas para 2m ou mais, etc.
<br><br>
<b>EPIs</b> – definição de qual é o EPI necessário para cada função, levando em conta o risco de cada atividade e também o ambiente. Trabalhos mais fisicamente exaustivos geralmente requerem troca de EPI mais constante ou especificações diferentes de outras atividades. É preciso garantir o correto uso desses equipamentos. No caso de máscaras simples, convém que a empresa distribua para os funcionários, garantindo certas especificações. Por exemplo,
<br><br>
<i>OBSERVAÇÃO:</i> quanto mais alto na hierarquia, menos capacidade de supervisão e execução é exigida do empregador. Por isso, a primeira pergunta é sempre “quem pode ficar em casa?”. Treinar supervisores, garantir alinhamento institucional e cumprimento impecável de protocolos, etc. tem um custo e são medidas de difícil controle.
<br><br>
<b>Materiais de Referência:</b><br>
<a href="http://www.pe.sesi.org.br/Documents/Guia_SESI_de_prevencao_2805_2%20(1).pdf" style="color: blue;">[1] Guia SESI de prevenção da Covid-19 nas empresas (atualizado em 26/5/2020).</a><br>
<a href="https://www.osha.gov/shpguidelines/hazard-prevention.html" style="color: blue;">[2] Recommended Practices for Safety and Health Programs - United States Department of Labor</a></br>
<br><br>
</span>
<figure>
<img class="saude-reopening-protocol-img-1" alt="Fonte: HIERARCHY OF CONTROLS -The National Institute for Occupational Safety and Health (NIOSH); disponível em https://www.cdc.gov/niosh/topics/hierarchy/default.html" src="https://i.imgur.com/St9fAMB.png"><br>
<figcaption><i>Fonte: HIERARCHY OF CONTROLS -The National Institute for Occupational Safety and Health (NIOSH); disponível em https://www.cdc.gov/niosh/topics/hierarchy/default.html</i></figcaption>
</figure>
</div>""",
unsafe_allow_html=True,
)
def gen_partners_section():
st.write(
"""
<div class="base-wrapper">
<span class="section-header primary-span">
APOIO TÉCNICO
</span><br><br>
<figure>
<img class="saude-reopening-protocol-img-1" alt="Vital Strategies - Resolve to Save Lives" src="https://i.imgur.com/iY7X2Qb.jpg"><br>
</figure>
</div>""",
unsafe_allow_html=True,
)
# MAIN
def main(user_input, indicators, data, config, session_state):
# TODO:o que isso faz??
st.write(
'<meta name="viewport" content="width=device-width, initial-scale=1.0">',
unsafe_allow_html=True,
)
if (
session_state.saude_ordem_data == None
): # If not loaded, load the data we are going to use in the user database
session_state.saude_ordem_data = {
"slider_value": 70,
"opened_tables": [True, True, True, True],
"opened_detailed_view": False,
}
utils.genHeroSection(
title1="Saúde",
title2="Em Ordem",
subtitle="Contribuindo para uma retomada segura da economia.",
logo="https://i.imgur.com/FiNi6fy.png",
header=False
)
gen_intro(alert=data["overall_alert"].values[0])
gen_slider(session_state)
score_groups, economic_data, place_name = get_score_groups(
config, session_state, session_state.saude_ordem_data["slider_value"]
)
gen_illustrative_plot(score_groups, session_state, place_name)
gen_detailed_vision(economic_data, session_state, config)
gen_sector_tables(
session_state,
score_groups,
config,
default_size=5,
download=True,
econ_data=economic_data,
download_name=place_name,
)
gen_protocols_section()
gen_partners_section()
| StarcoderdataPython |
1855950 | <reponame>SamuelMarks/enforce
import typing
import unittest
from enforce import runtime_validation, config
from enforce.exceptions import RuntimeTypeError
class DictTypesTests(unittest.TestCase):
"""
Tests for the dictionary types
"""
def test_simple_dict(self):
"""
Verifies that unrestricted Dictionary type is correctly checked
"""
d = {"a": 12, "b": "b"}
@runtime_validation
def foo(a: typing.Dict, b: typing.Any = None) -> typing.Dict:
return b
foo(d, d)
with self.assertRaises(RuntimeTypeError):
foo(3)
with self.assertRaises(RuntimeTypeError):
foo(d, 2)
def test_empty_dict(self):
"""
Verifies that empty dictionary is treated correctly
"""
@runtime_validation
def foo(a: typing.Any) -> typing.Dict:
return dict()
foo(12)
def test_dict_is_mapping(self):
"""
Verifies that dictionary is treated like a Mapping
"""
config({"mode": "covariant"})
@runtime_validation
def returns_dict() -> typing.Mapping:
return dict()
returns_dict()
config(reset=True)
def test_restricted_dict(self):
"""
Verifies that restricted dictionaries are type checked correctly
"""
TypeAlias = typing.Dict[str, typing.Union[int, str, None]]
@runtime_validation
def foo(a: TypeAlias, b: typing.Any = None) -> TypeAlias:
return b
good_dict = {"hello": "world", "name": None, "id": 1234}
bad_dict = {"hello": 123.5}
foo(good_dict, good_dict)
with self.assertRaises(RuntimeTypeError):
foo(bad_dict)
with self.assertRaises(RuntimeTypeError):
foo(good_dict, bad_dict)
foo({}, {})
def test_nested_dicts(self):
"""
Verifies that the type containing nested dictionaries can be successfully verified
"""
TypeAlias = typing.Dict[str, typing.Dict[str, typing.Optional[int]]]
@runtime_validation
def foo(a: TypeAlias, b: typing.Any = None) -> TypeAlias:
return b
good_dict = {"hello": {"world": 12, "me": None}}
bad_dict = {12: None}
bad_dict_2 = {
"hello": {"world": 12, "everyone": None, "me": {1, 3}, 2: {"a": "a"}}
}
foo(good_dict, good_dict)
with self.assertRaises(RuntimeTypeError):
foo(bad_dict)
with self.assertRaises(RuntimeTypeError):
foo(good_dict, bad_dict)
with self.assertRaises(RuntimeTypeError):
foo(bad_dict_2)
with self.assertRaises(RuntimeTypeError):
foo(good_dict, bad_dict_2)
if __name__ == "__name__":
unittest.main()
| StarcoderdataPython |
9654005 | import argparse
import json
import re
import operator
from datetime import datetime
import dateutil
import colorama
import difflib
from . import exceptions
from . logger import logger
from . safe_print import safe_print
from . import aws as aws_lib
from collections import OrderedDict
from difflib import SequenceMatcher
VALID_CREDENTIAL_SOURCES = [ None, 'Environment', 'Ec2InstanceMetadata', 'EcsContainer' ]
try:
import Levenshtein
except:
Levenshtein = False
def parse_time(date_time: datetime):
date_time.replace(tzinfo=dateutil.tz.tzlocal())
return date_time.strftime('%Y-%m-%d %H:%M:%S')
def profile_to_credentials(profile: dict) -> dict:
if profile:
return {
'AccessKeyId': profile.get('aws_access_key_id'),
'SecretAccessKey': profile.get('aws_secret_access_key'),
'SessionToken': profile.get('aws_session_token'),
'Region': profile.get('region'),
}
return {}
def credentials_to_profile(credentials: dict) -> dict:
result = {}
if credentials.get('AccessKeyId'):
result['aws_access_key_id'] = credentials['AccessKeyId']
if credentials.get('SecretAccessKey'):
result['aws_secret_access_key'] = credentials['SecretAccessKey']
if credentials.get('SessionToken'):
result['aws_session_token'] = credentials['SessionToken']
if credentials.get('Region'):
result['region'] = credentials['Region']
return result
def validate_profile(config: dict, arguments: argparse.Namespace, profiles: dict, target_profile_name: str) -> bool:
logger.debug('Validating profile')
profile = profiles.get(target_profile_name)
if arguments.output_profile and not is_mutable_profile(profiles, arguments.output_profile):
raise exceptions.ImmutableProfileError(arguments.output_profile, 'not awsume-managed')
if not profile:
raise exceptions.ProfileNotFoundError(profile_name=target_profile_name)
# validate role profiles
if 'role_arn' in profile:
if profile.get('credential_process'):
raise exceptions.InvalidProfileError(target_profile_name, message='awsume does not support the credential_process profile option: {}')
if profile.get('credential_source') and profile.get('source_profile'):
raise exceptions.InvalidProfileError(target_profile_name, message='credential_source and source_profile are mutually exclusive profile options')
if not profile.get('credential_source') and not profile.get('source_profile') and not profile.get('principal_arn'):
raise exceptions.InvalidProfileError(target_profile_name, message='role profiles must contain one of credential_source or source_profile')
if profile.get('credential_source') not in VALID_CREDENTIAL_SOURCES:
raise exceptions.InvalidProfileError(target_profile_name, message='unsupported awsume credential_source profile option: {}'.format(profile.get('credential_source')))
source_profile_name = profile.get('source_profile')
source_profile = get_source_profile(profiles, target_profile_name)
if source_profile_name and not source_profile:
raise exceptions.ProfileNotFoundError(profile_name=source_profile_name)
if source_profile and not source_profile.get('role_arn'):
user_profile = source_profile
user_profile_name = source_profile_name
else:
user_profile = None
user_profile_name = None
else:
user_profile = profile
user_profile_name = target_profile_name
# validate user profile
if user_profile:
missing_keys = []
if 'credential_source' in profile:
if profile.get('credential_source') not in VALID_CREDENTIAL_SOURCES:
raise exceptions.InvalidProfileError(user_profile_name, message='unsupported awsume credential_source profile option: {}'.format(profile.get('credential_source')))
else:
if 'aws_access_key_id' not in user_profile:
missing_keys.append('aws_access_key_id')
if 'aws_secret_access_key' not in user_profile:
missing_keys.append('aws_secret_access_key')
if missing_keys:
raise exceptions.InvalidProfileError(user_profile_name, message='Missing keys {}, or credential_source'.format(', '.join(missing_keys)))
# validate arguments with profile
if 'role_arn' not in profile and arguments.auto_refresh:
raise exceptions.ValidationException('Cannot use autoawsume with non-role profile')
return True
def is_mutable_profile(profiles: dict, profile_name: str) -> dict:
profile = profiles.get(profile_name)
if not profile:
return True
if profile.get('manager') == 'awsume':
return True
return False
def get_source_profile(profiles: dict, target_profile_name: str) -> dict:
target_profile = profiles.get(target_profile_name)
if target_profile:
source_profile_name = target_profile.get('source_profile', 'default')
return profiles.get(source_profile_name)
return None
def get_role_chain(profiles: dict, target_profile_name: str) -> list:
target_profile = profiles.get(target_profile_name)
if not target_profile or not target_profile.get('role_arn'):
return [target_profile_name]
role_chain = []
while target_profile:
if target_profile.get('role_arn'):
if target_profile_name in role_chain:
raise exceptions.InvalidProfileError(','.join(role_chain), 'cannot have circular role-chains')
role_chain.append(target_profile_name)
target_profile_name = target_profile.get('source_profile')
target_profile = profiles.get(target_profile_name)
role_chain.reverse()
return role_chain
def get_region(profiles: dict, arguments: argparse.Namespace, config: dict, ignore_config: bool = False, ignore_default: bool = False) -> str:
if arguments.region:
return arguments.region
if arguments.role_arn and arguments.source_profile and profiles.get(arguments.source_profile, {}).get('region'):
return profiles[arguments.source_profile]['region']
target_profile = profiles.get(arguments.target_profile_name, {})
if target_profile.get('region'):
return target_profile['region']
source_profile = get_source_profile(profiles, arguments.target_profile_name)
if source_profile and source_profile.get('region'):
return source_profile['region']
if not ignore_default and profiles.get('default', {}).get('region'):
return profiles['default']['region']
if not ignore_config and config.get('region'):
return config['region']
return None
def get_external_id(arguments: argparse.Namespace, target_profile: dict):
if arguments.external_id:
return arguments.external_id
return target_profile.get('external_id')
def get_role_duration(config: dict, arguments: argparse.Namespace, target_profile: dict):
if arguments.role_duration:
return int(arguments.role_duration)
if target_profile.get('duration_seconds'):
return int(target_profile.get('duration_seconds'))
if config.get('role-duration'):
return int(config.get('role-duration'))
return 0
def get_mfa_serial(profiles: dict, target_profile_name: str) -> dict:
target_profile = profiles.get(target_profile_name)
mfa_serial = target_profile.get('mfa_serial')
if not mfa_serial:
source_profile_name = target_profile.get('source_profile')
mfa_serial = profiles.get(source_profile_name, {}).get('mfa_serial')
return mfa_serial
def get_mfa_token() -> str:
token_pattern = re.compile('^[0-9]{6}$')
safe_print('Enter MFA token: ', colorama.Fore.CYAN, end='')
while True:
mfa_token = input()
if token_pattern.match(mfa_token):
return mfa_token
else:
safe_print('Please enter a valid MFA token: ', colorama.Fore.CYAN, end='')
def aggregate_profiles(result: list) -> dict:
return_profiles = {}
for profiles in result:
for profile_name, profile in profiles.items():
if profile_name not in return_profiles:
return_profiles[profile_name] = profile
else:
return_profiles[profile_name].update(profile)
return return_profiles
def format_aws_profiles(profiles: dict, get_extra_data: bool) -> list: # pragma: no cover
sorted_profiles = OrderedDict(sorted(profiles.items()))
# List headers
list_headers = ['PROFILE', 'TYPE', 'SOURCE', 'MFA?', 'REGION', 'ACCOUNT']
profile_list = []
profile_list.append([])
profile_list[0].extend(list_headers)
# now fill the tables with the appropriate data
for name in sorted_profiles:
#don't add any autoawsume profiles
if 'auto-refresh-' not in name:
profile = sorted_profiles[name]
is_role_profile = 'role_arn' in profile
profile_type = 'Role' if is_role_profile else 'User'
# Assume source_profile is None unless we find otherwise afterwards.
if is_role_profile:
if 'source_profile' in profile.keys():
source_profile = profile['source_profile']
elif 'principal_arn' in profile.keys():
source_profile = profile['principal_arn'].split(':')[-1]
else:
source_profile = 'None'
else:
source_profile = 'None'
mfa_needed = 'Yes' if 'mfa_serial' in profile else 'No'
profile_region = str(profile.get('region'))
profile_account_id = get_account_id(profile, get_extra_data)
list_row = [name, profile_type, source_profile, mfa_needed, profile_region, profile_account_id]
profile_list.append(list_row)
return profile_list
def print_formatted_data(profile_data: list): # pragma: no cover
print('Listing...\n')
widths = [max(map(len, col)) for col in zip(*profile_data)]
print('AWS Profiles'.center(sum(widths) + 10, '='))
for row in profile_data:
print(' '.join((val.ljust(width) for val, width in zip(row, widths))))
def list_profile_data(profiles: dict, get_extra_data: bool): # pragma: no cover
profiles = {k: v for k, v in profiles.items() if not v.get('autoawsume')}
formatted_profiles = format_aws_profiles(profiles, get_extra_data)
print_formatted_data(formatted_profiles)
def get_account_id(profile: dict, call_aws: bool = False) -> str:
logger.info('Getting account ID from profile: %s', json.dumps(profile, indent=2))
if profile.get('role_arn'):
return profile['role_arn'].replace('arn:aws:iam::', '').split(':')[0]
if profile.get('mfa_serial'):
return profile['mfa_serial'].replace('arn:aws:iam::', '').split(':')[0]
if call_aws and profile.get('aws_access_key_id') and profile.get('aws_secret_access_key'):
return aws_lib.get_account_id(profile_to_credentials(profile))
return 'Unavailable'
def get_profile_name(config: dict, profiles: dict, target_profile_name: str, log=True) -> str:
if target_profile_name in profiles or not config.get('fuzzy-match'):
return target_profile_name
profile_names = list(profiles.keys())
matched_prefix_profile = match_prefix(profile_names, target_profile_name)
if matched_prefix_profile:
if log:
safe_print('Using profile ' + matched_prefix_profile, color=colorama.Fore.YELLOW)
return matched_prefix_profile
matched_contains_profile = match_contains(profile_names, target_profile_name)
if matched_contains_profile:
if log:
safe_print('Using profile ' + matched_contains_profile, color=colorama.Fore.YELLOW)
return matched_contains_profile
matched_levenshtein_profile = match_levenshtein(profile_names, target_profile_name)
if matched_levenshtein_profile:
if log:
safe_print('Using profile ' + matched_levenshtein_profile, color=colorama.Fore.YELLOW)
return matched_levenshtein_profile
return target_profile_name
def match_prefix(profile_names: list, profile_name: str) -> str:
prefix_words = [_ for _ in profile_names if _.startswith(profile_name)]
if len(prefix_words) == 1:
return prefix_words[0]
return None
def match_contains(profile_names: list, profile_name: str) -> str:
def longest_contains(str1, str2):
sequence_match = SequenceMatcher(None,str1,str2)
match = sequence_match.find_longest_match(0, len(str1), 0, len(str2))
return match.size
matches = {profile: longest_contains(profile_name, profile) for profile in profile_names}
biggest_match = max(matches.values())
result = [k for k in matches.keys() if matches[k] == biggest_match]
if len(result) == 1:
return result[0]
return None
def match_levenshtein(profile_names: list, profile_name: str) -> str:
if not Levenshtein:
logger.debug('Levenshtein not installed, try installing awsume[fuzzy]')
return None
matches = {profile: Levenshtein.distance(profile_name, profile) for profile in profile_names}
closest_match = min(matches.values())
result = [k for k in matches.keys() if matches[k] == closest_match]
if len(result) == 1:
return result[0]
return None
| StarcoderdataPython |
9669512 | <filename>src/epivizquindex/sample.py
import QuadTree
import EpivizQuindex
genome = {
"chr1": 249250621,
"chr10": 135534747,
"chr11": 135006516,
"chr12": 133851895,
"chr13": 115169878,
"chr14": 107349540,
"chr15": 102531392,
"chr16": 90354753,
"chr17": 81195210,
"chr18": 78077248,
"chr19": 59128983,
"chr2": 243199373,
"chr20": 63025520,
"chr21": 48129895,
"chr22": 51304566,
"chr3": 198022430,
"chr4": 191154276,
"chr5": 180915260,
"chr6": 171115067,
"chr7": 159138663,
"chr8": 146364022,
"chr9": 141213431,
"chrM": 16571,
"chrX": 155270560,
"chrY": 59373566
}
index = EpivizQuindex.EpivizQuindex(genome)
f1 = "../testData/39033.bigwig"
f2 = "../testData/39031.bigwig"
# adding file to index
index.add_to_index(f1)
index.add_to_index(f2)
# storing the precomputed index to cwd
index.to_disk()
# reading a precomputed set of indecies from cwq
index = EpivizQuindex.EpivizQuindex(genome)
index.from_disk()
# querying a range in 1 file
f1 = "../testData/39033.bigwig"
print(index.query("chr2", 0, 900000, file = f1))
# querying for a range in all files
print(index.query("chr2", 0, 900000))
# linking a precomputed set of indecies from cwq
# note that using load = False, EpvizQuindex does not
# read the index into memory.
memory = False
index = EpivizQuindex.EpivizQuindex(genome)
index.from_disk(load = memory)
# querying a range in 1 file without loading it to memory
# here, the in_memory parameter must be set to false
f1 = "../testData/39033.bigwig"
print(index.query("chr2", 0, 900000, file = f1, in_memory = memory))
# querying for a range in all files without loading it to memory
# again, the in_memory parameter must be set to false
print(index.query("chr2", 0, 900000, in_memory = memory))
# and I guess we can add a option for querying for a set of files later | StarcoderdataPython |
1836502 | # Interface for The Number Graph.
# Initial IDs:
# Thread: 2dwxho
# Comment: cju11n6
import praw
# PRAW Initialisation
r = praw.Reddit(user_agent='the-number-graph by /u/glider97')
f1 = open("latest.txt", 'r') # latest.txt stores the ids of the last comment and thread used.
latest = f1.read().split('\n') # They are stored in a list called 'latest'
f1.close() # 'details.txt' stores a log of all the comments "approved".
f2 = open("details.txt", "a+") #
# latest.txt Legend:
# 0 - curThreadID
# 1 - curComID
curThreadID=latest[0] # ID of the Number Thread
curComID=latest[1] # First comment's ID in the Number Thread.
comms=[] # List of comments saved.
f2.write("========================================================\n")
f2.write(str(curThreadID)+'\n') # Log ID of thread about to be used. Buggy.
def main():
# Begin.
start()
def migrate():
# The function of migrate() is to change the thread ID
# (and consequently the comment ID) on which the work is to be done.
# See: last comment of The Mona Lisa Thread.
global curThreadID
global curComID
global comms
curThreadID=raw_input("Enter the Thread ID (ex: 2dwxho):")
curComID=raw_input("Enter the Comment ID (ex: cju11n6):")
try:
thread = r.get_submission('http://www.reddit.com/r/explainlikeimfive/comments/' + curThreadID + "/_/" + curComID)
except Exception,e:
print "Error! Please try again."
print e
else:
curComID = thread.comments[0] # Make comment ID variable as comment object.
postTime = datetime.fromtimestamp(int(curComID.created_utc)).strftime('%Y-%m-%d %H:%M:%S')
comms.append([curComID.id, curComID.author, postTime, curComID.body]) # Append a list of data of the comment.
if type(curComID)==str: # If thread or comment not found.... Maybe useless?
curComID, curThreadID=''
comms=[]
print "Comment not found. Please try again."
main() # Reset and try again.
def start():
# The core of the script. Gives an interface to 'store', 'discard', or
# 'save' a comment, and to 'migrate' to another thread.
global curThreadID
global curComID
global comms
char = ''
temp = [] # Store the comment data. Later add to comms list.
if curComID=='' or curThreadID=='': # If thread or comment ID not found in latest.txt....
migrate() # go to migrate() and get it.
elif type(curComID)==str:
thread = r.get_submission('http://www.reddit.com/r/explainlikeimfive/comments/' + curThreadID + "/_/" + curComID)
curComID = thread.comments[0]
postTime = datetime.fromtimestamp(int(curComID.created_utc)).strftime('%Y-%m-%d %H:%M:%S')
comms.append([curComID.id, curComID.author, postTime, curComID.body]) # Append a list of data of the comment.
if len(curComID.replies)==0:
print "This is the latest comment yet."
else:
# Interface begins.
char = 0
x = 0
while x < len(curComID.replies):
y = curComID.replies[x]
if type(y)==praw.objects.MoreComments: # "load more comments"
y = y.comments()[0]
postTime = datetime.fromtimestamp(int(y.created_utc)).strftime('%Y-%m-%d %H:%M:%S')
print "Comment made by", y.author, 'at', postTime
print '"' + y.body + '"'
char = raw_input("1)Store 2)Discard 3)Store, Save and Migrate 4)Save 5)Exit\n")
if char=='1':
temp.append([y.id, y.author, postTime, y.body]) # "Approve" the comment. 'Save' later.
curComID = y
x=0
elif char=='2':
x+=1 # Disapprove/Discard the current comment.
elif char=='3':
for i in temp:
comms.append(i)
temp=[]
x=0
migrate() # "Approve", 'save' and move on to another thread.
elif char=='4':
for i in temp: # A code snippet....
comms.append(i) # to 'save' the comments "approved".
temp=[]
elif char=='5':
break
if char != '3' and char!='5': # Bugs???
print "The thread has come to an end. This was the latest comment."
char = raw_input("Progress Saved!\nDo you want to (m)igrate to a new thread, or (s)top?")
for i in temp:
comms.append(i) # 'Save'
if char=='m':
migrate()
main()
# Interface ends.
for i in comms:
if i == ['','','','']: # Remove empty comment data, if any. Maybe useless?
comms.remove(i)
f1 = open("latest.txt", 'w') # Write the last thread and comment
f1.write(str(curThreadID)+'\n'+str(curComID.id)+'\n') # IDs operated upon.
f1.close()
for i in comms:
f2.write(str(i[0])+'\n') # Log the comment IDs "approved".
f2.close()
# Placeholder to either return list to 'plot' script....
# or call the script itself by parameters.
if __name__=='__main__':
main()
| StarcoderdataPython |
1864469 | <reponame>adoublebarrel/curriculum-vitae
import base
import json
import logging
from google.appengine.ext import ndb
from server.models.skill import Skill
class TechSkillsHandler(base.BaseHandler):
def get(self):
self.data['content'] = 'Technical Skills'
template = base.template_engine.get_template('skills.html')
self.data['skills'] = Skill.query(Skill.category == 'tech').order(-Skill.months, Skill.name_lower)
self.response.write(template.render(self.data))
class MethodSkillsHandler(base.BaseHandler):
def get(self):
template = base.template_engine.get_template('list-with-content.html')
self.data['title'] = "Development Methods"
self.data['list'] = Skill.query(Skill.category == 'method').order(-Skill.months, Skill.name_lower)
self.response.write(template.render(self.data))
class LeadershipSkillsHandler(base.BaseHandler):
def get(self):
template = base.template_engine.get_template('list-with-content.html')
self.data['title'] = 'Leadership Skills'
self.data['list'] = Skill.query(Skill.category == 'leadership').order(-Skill.months, Skill.name_lower)
self.response.write(template.render(self.data))
class SkillsListHandler(base.BaseHandler):
def get(self):
skills = Skill.query().order(-Skill.months, Skill.name_lower).fetch()
self.response.headers['Content-Type'] = 'application/json'
for skill in skills:
self.response.write(json.dumps(skill.to_dict(exclude=['created','updated']),ensure_ascii=False,skipkeys=True))
class SkillHandler(base.BaseHandler):
def get(self, skillKey):
skill_key = ndb.Key(urlsafe=skillKey)
skill = skill_key.get()
self.response.headers['Content-Type'] = 'application/json'
self.response.write(json.dumps(skill.to_dict(exclude=['created','updated']),ensure_ascii=False,skipkeys=True))
| StarcoderdataPython |
1819046 | <filename>UServer/database/db9.py
import redis
from config import RedisHost, RedisPasswd, RedisPort
class ConstDB9:
released_addr = 'RELEASED_ADDR'
current_block = 'CUR_BLOCK'
current_num = 'CUR_NUM'
block = 'BLOCK:'
db9 = redis.StrictRedis(host=RedisHost, port=RedisPort, db=9, password=<PASSWORD>) | StarcoderdataPython |
8136127 | <filename>pandoctools/pandoctools_resolve/resolve.py
import sys
import os
import os.path as p
import click
from ..shared_vars import (pandoctools_user, pandoctools_user_data, pandoctools_core,
PandotoolsError, bash_cygpath)
def main(basename: str, fallback_basename: str=None) -> str:
"""
Returns Unix style absolute path to the file by its basename (given with extension).
First searches in $HOME/.pandoc/pandoctools (or %APPDATA%\\pandoc\\pandoctools),
Then in Pandoctools module directory (<...>/site-packages/pandoctools/sh).
Fallback basename is used if the first one wasn't found.
On Windows conversion to POSIX paths is done via cygpath that at first is read from
$cygpath env var then seached in the current python environment, near bash executable,
in the $PATH
:param basename:
:param fallback_basename:
:return: absolute path (or empty string if it wasn't found)
"""
for abs_path in (p.join(dir_, name)
for name in (basename, fallback_basename)
for dir_ in (pandoctools_user, pandoctools_core)
if name):
if p.isfile(abs_path):
if os.name == 'nt':
from subprocess import run, PIPE
cygpath = os.environ.get('cygpath')
cygpath = bash_cygpath()[1] if not cygpath else cygpath
return run([cygpath, abs_path], stdout=PIPE, encoding='utf-8').stdout
else:
return abs_path
raise PandotoolsError(f"'{basename}' or fallback '{fallback_basename}'" +
f" wasn't found in '{pandoctools_user}' and '{pandoctools_core}'.")
@click.command(help=f"""
Inside Pandoctools shell scripts use alias: $resolve
Resolves and echoes Unix style absolute path to the file by its basename (given with extension).
First searches in {pandoctools_user_data}, then in Pandoctools module directory:
{pandoctools_core}
On Windows conversion to POSIX paths is done via cygpath that at first is read from
$cygpath env var then seached in the current python environment, near bash executable,
in the $PATH
""")
@click.argument('file_basename', type=str)
@click.option('--else', 'fallback', type=str, default=None,
help="Fallback file basename that is used if the first one wasn't found.")
def cli(file_basename, fallback):
sys.stdout.write(main(file_basename, fallback))
| StarcoderdataPython |
5050690 | <reponame>fanteastick/ML-SKI
# importing
from sklearn import linear_model
from sklearn.linear_model import LinearRegression
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from statistics import mean
#the plan:
#read the master data file as a csv w/pandas
#target the variable
#use techniques to preprocess data
#use scikit larn to randomize splitting into testing and training data
#train the model
#graph the thing
def readFile(file):
df = pd.read_csv(file, sep='\t')
return df
def printDF(datfra):
print("getting the info:")
print(".head")
print(datfra.head())
print(".info")
print (datfra.info())
print(".tail")
print(datfra.tail())
def linReg(X_train, y_train, X_test, y_test):
regr = linear_model.LinearRegression()
regr.fit(X_train, y_train)
y_pred = regr.predict(X_test)
print ("The thing has been trained")
#print('Coefficients: \n', regr.coef_)
print("Mean squared error: %.2f"
% mean_squared_error(y_test, y_pred))
print("OTHER Mean squared error:", mean_squared_error(y_test, y_pred))
return (y_pred)
def barplot(x_val, y_val, xaxis, yaxis, title):
plt.bar(x_val, y_val, align='center', alpha=0.5, width = .02)
#how do I do xticks and yticks
plt.ylabel(xaxis)
plt.xlabel(yaxis)
plt.title(title)
plt.show()
def scatterplot(x_val, y_val, xaxis, yaxis, title):
plt.scatter(x_val, y_val)
plt.xlabel(xaxis)
plt.ylabel(yaxis)
plt.title(title)
plt.xlim(xmin = 0, xmax =6) #setting the same axes scaling for both sides
plt.ylim(ymin=0, ymax=6)
plt.show()
def sidebysideplot(df): #takes the DF and the index that you want to set it to, then sorts it and plots the two things together.
df.sort_index(inplace=True)
df.plot.bar()
plt.legend()
plt.show()
return df
def errorpercentline(df):
df.sort_index(inplace=True)
df.reset_index(inplace=True)
early = {}
currentindex =1
total_predicted = 0
total_actual = 0
a = np.zeros(shape = (len(df), 1))
for index, row in df.iterrows():
item =abs((row['predicted'] - row['actual'])/row['actual'])*100
a[index, 0] = item
df['error'] = a
print ('mean error percent', mean(df['error']))
df.set_index('yid', inplace=True)
df['error'].plot.bar()
plt.legend()
plt.show()
return df
def smalldf(df): #takes the df with the multiple indexes n stuff and avges the values so it's easier to graph
df.sort_index(inplace=True)
a = np.zeros(shape = (38, 2))
for i in range(38):
#print (df.loc[i])
#print ('predicted mean', mean(df.loc[i, 'predicted']))
mean_pred = mean(df.loc[i, 'predicted'])
#print ('actual mean', mean(df.loc[i, 'actual']))
mean_actual = mean(df.loc[i, 'actual'])
a[i, 0] = mean_pred
a[i, 1] = mean_actual
newdf = pd.DataFrame(a)
newnames = {0:'predicted pwr', 1:'actual pwr'}
newdf.rename(columns=newnames, inplace=True)
return newdf
def datatodictionary(df): #for the purpose of renaming the workload id to names
namesdict = df[0:39]['Workload_Name']
namesdict = namesdict.to_dict()
print (type(namesdict))
return namesdict
def allthegraphs(graph1, graph2, graph3, graph4): #put the graphs together, gotta b 4
print ("This function shall be made someday")
df = readFile('entiredataset.csv')
df_target = df['Power_A15'] #, 'Power_A7' took out power a7 for now
#printDF(df)
df_train = df.drop(['Unnamed: 0','Unnamed:_0', 'Workload_Name','Core_Mask',
'Power_A7','Power_A15','Status','Power_A7',
'Core_4_Predicted_Dynamic_Power','Core_5_Predicted_Dynamic_Power',
'Core_6_Predicted_Dynamic_Power','Core_7_Predicted_Dynamic_Power',
'Summed_A15_Cores_Dynamic_Power', 'Switching_Dynamic_Power_A15',
'Total_Static_Power_A15','Total_Power_Summed_A15',
'Core_4_Static_Power', 'Core_5_Static_Power', 'Core_6_Static_Power',
'Core_7_Static_Power','L2_and_Background_Static_Power',
'Core_4_Static_Power_CC','Core_7_Static_Power_CC',
'Total_Static_Power_A15_CC'], axis=1)
X_train, X_test, y_train, y_test= train_test_split(df_train, df_target, test_size=0.25, random_state=42)
y_pred = linReg(X_train, y_train, X_test, y_test)
barplot(y_pred, y_test, 'y_pred', 'y_test', 'the graph')
scatterplot(y_pred, y_test, 'y_pred', 'y_test', 'second graph')
newdf = pd.DataFrame({'actual':y_test.values, 'predicted':y_pred, 'yid':X_test['Workload_ID']})
newdf.set_index('yid', inplace=True)
sidebysideplot(newdf)
errorpercentline(newdf)
shortdf = smalldf(newdf)
namesdict = datatodictionary(df)
shortdf.reset_index(inplace=True)
shortdf.replace(namesdict, inplace = True)
print (shortdf)
#shortdf.replace(namesdict, inplace = True)
#print (shortdf)
shortdf.plot.bar(x='index')
plt.title('Predicted vs Actual: Power A15')
plt.show()
'''
'zipped to make a bar graph'
zippy = dict(zip(y_pred[0:6], y_test[0:6]))
plt.xticks(range(len(zippy)), zippy.keys())
plt.bar(range(len(zippy)), zippy.values(), align='center', width = 0.2)
plt.show()
'''
'''
data = pd.DataFrame(df_main)
print (data['Core Count Both'])
#print (data.iloc[4])
plt.plot(data['EPH_0x14'])
plt.title('Core Count Both data')
plt.xlabel('rows?')
plt.ylabel('value')
plt.legend()
plt.show()
D = {'Label0':26, 'Label1': 17, 'Label2':30}
plt.xticks(range(len(D)), D.keys())
plt.bar(range(len(D)), D.values(), align='center')
plt.show()
ax = plt.subplot(111)
x = [1, 2, 3, 4]
ax.bar(x-0.2, y_pred,width=0.2,color='b',align='center')
ax.bar(x, y_test,width=0.2,color='g',align='center')
plt.show()
''' | StarcoderdataPython |
11325888 | # Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is govered by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
"""Constants that define the Monorail URL space."""
# URLs of site-wide Monorail pages
HOSTING_HOME = '/hosting/' # the big search box w/ popular labels
PROJECT_CREATE = '/hosting/createProject'
USER_SETTINGS = '/hosting/settings'
PROJECT_MOVED = '/hosting/moved'
CHECK_PROJECT_NAME_JSON = '/hosting/createProject/checkProjectName'
GROUP_LIST = '/g/'
GROUP_CREATE = '/hosting/createGroup'
GROUP_DELETE = '/hosting/deleteGroup'
ADD_ISSUES_TO_HOTLIST = '/hosting/addToHotlist'
# URLs of project pages
SUMMARY = '/' # Now just a redirect to /issues/list
UPDATES_LIST = '/updates/list'
PEOPLE_LIST = '/people/list'
PEOPLE_DETAIL = '/people/detail'
PEOPLE_DETAIL_PREFS_JSON = '/people/detailPrefs'
ADMIN_META = '/admin'
ADMIN_ADVANCED = '/adminAdvanced'
# URLs for stars
STARS_JSON = '/hosting/stars'
# URLs for cue cards (dismissible on-page help)
CUES_JSON = '/hosting/cues'
# URLs of user pages, relative to either /u/userid or /u/username
# TODO(jrobbins): Add /u/userid as the canonical URL in metadata.
USER_PROFILE = '/'
USER_CLEAR_BOUNCING = '/clearBouncing'
BAN_USER = '/ban'
BAN_SPAMMER = '/banSpammer'
# URLs for User Updates pages
USER_UPDATES_PROJECTS = '/updates/projects'
USER_UPDATES_DEVELOPERS = '/updates/developers'
USER_UPDATES_MINE = '/updates'
# URLs of user group pages, relative to /g/groupname.
GROUP_DETAIL = '/'
GROUP_ADMIN = '/groupadmin'
# URL of JSON feed for the "My projects" menu
USER_PROJECTS_JSON = '/hosting/projects'
# URLs of issue tracker backend request handlers. Called from the frontends.
BACKEND_SEARCH = '/_backend/search'
BACKEND_NONVIEWABLE = '/_backend/nonviewable'
# URLs of task queue request handlers. Called asynchronously from frontends.
RECOMPUTE_DERIVED_FIELDS_TASK = '/_task/recomputeDerivedFields'
NOTIFY_ISSUE_CHANGE_TASK = '/_task/notifyIssueChange'
NOTIFY_BLOCKING_CHANGE_TASK = '/_task/notifyBlockingChange'
NOTIFY_BULK_CHANGE_TASK = '/_task/notifyBulkEdit'
OUTBOUND_EMAIL_TASK = '/_task/outboundEmail'
SPAM_DATA_EXPORT_TASK = '/_task/spamDataExport'
BAN_SPAMMER_TASK = '/_task/banSpammer'
ISSUE_DATE_ACTION_TASK = '/_task/issueDateAction'
# URLs of cron job request handlers. Called from GAE via cron.yaml.
REINDEX_QUEUE_CRON = '/_cron/reindexQueue'
RAMCACHE_CONSOLIDATE_CRON = '/_cron/ramCacheConsolidate'
REAP_CRON = '/_cron/reap'
SPAM_DATA_EXPORT_CRON = '/_cron/spamDataExport'
LOAD_API_CLIENT_CONFIGS_CRON = '/_cron/loadApiClientConfigs'
TRIM_VISITED_PAGES_CRON = '/_cron/trimVisitedPages'
DATE_ACTION_CRON = '/_cron/dateAction'
# URLs of User pages
SAVED_QUERIES = '/queries'
DASHBOARD = '/dashboard'
HOTLISTS = '/hotlists'
# URLS of User hotlist pages
HOTLIST_ISSUES = ''
HOTLIST_ISSUES_CSV = '/csv'
HOTLIST_PEOPLE = '/people'
HOTLIST_DETAIL = '/details'
HOTLIST_RERANK_JSON = '/rerank'
HOTLIST_NEW_NOTES_JSON = '/updatenote'
# URL of JSON feed for the "My hotlists" menu
USER_HOTLISTS_JSON = '/hosting/hotlists'
# URLs of issue tracker project pages
ISSUE_LIST = '/issues/list'
ISSUE_DETAIL = '/issues/detail'
ISSUE_PEEK = '/issues/peek' # not served, only used in issuepeek.py
ISSUE_COMMENT_DELETION_JSON = '/issues/delComment'
ISSUE_ATTACHMENT_DELETION_JSON = '/issues/delAttachment'
ISSUE_FLAGSPAM_JSON = '/issues/flagspam'
ISSUE_SETSTAR_JSON = '/issues/setstar'
ISSUE_DELETE_JSON = '/issues/delete'
ISSUE_PRESUBMIT_JSON = '/issues/presubmit'
ISSUE_ENTRY = '/issues/entry'
ISSUE_ENTRY_AFTER_LOGIN = '/issues/entryafterlogin'
ISSUE_OPTIONS_JSON = '/feeds/issueOptions'
ISSUE_BULK_EDIT = '/issues/bulkedit'
ISSUE_ADVSEARCH = '/issues/advsearch'
ISSUE_TIPS = '/issues/searchtips'
ISSUE_ATTACHMENT = '/issues/attachment'
ISSUE_ATTACHMENT_TEXT = '/issues/attachmentText'
ISSUE_LIST_CSV = '/issues/csv'
COMPONENT_CHECKNAME_JSON = '/components/checkName'
COMPONENT_CREATE = '/components/create'
COMPONENT_DETAIL = '/components/detail'
FIELD_CHECKNAME_JSON = '/fields/checkName'
FIELD_CREATE = '/fields/create'
FIELD_DETAIL = '/fields/detail'
WIKI_LIST = '/w/list' # Wiki urls are just redirects to project.docs_url
WIKI_PAGE = '/wiki/<wiki_page:.*>'
SOURCE_PAGE = '/source/<source_page:.*>'
ADMIN_INTRO = '/adminIntro'
# TODO(jrbbins): move some editing from /admin to /adminIntro.
ADMIN_COMPONENTS = '/adminComponents'
ADMIN_LABELS = '/adminLabels'
ADMIN_RULES = '/adminRules'
ADMIN_TEMPLATES = '/adminTemplates'
ADMIN_STATUSES = '/adminStatuses'
ADMIN_VIEWS = '/adminViews'
ADMIN_EXPORT = '/projectExport'
ADMIN_EXPORT_JSON = '/projectExport/json'
ISSUE_ORIGINAL = '/issues/original'
ISSUE_REINDEX = '/issues/reindex'
ISSUE_EXPORT = '/issues/export'
ISSUE_EXPORT_JSON = '/issues/export/json'
ISSUE_IMPORT = '/issues/import'
ISSUE_RERANK_BLOCKED_ON = '/issues/rerankBlockedOn'
# URLs for hotlist features
HOTLIST_CREATE = '/hosting/createHotlist'
# URLs of site-wide pages referenced from the framework directory.
CAPTCHA_QUESTION = '/hosting/captcha'
EXCESSIVE_ACTIVITY = '/hosting/excessiveActivity'
BANNED = '/hosting/noAccess'
NONPROJECT_COLLISION = '/hosting/collision'
# This is for collisions that happen within a project, based at /p/projectname
ARTIFACT_COLLISION = '/collision'
CLIENT_MON = '/_/clientmon'
CSP_REPORT = '/csp'
TOKEN_REFRESH = '/hosting/tokenRefresh'
SPAM_MODERATION_QUEUE = '/spamqueue'
| StarcoderdataPython |
3250064 | <gh_stars>1-10
from typing import List
import click
import inject
from mycloud.commands.shared import async_click, authenticated
from mycloud.drive import DriveNotFoundException, FsDriveClient
@click.command(name='download')
@click.argument('remote')
@click.argument('local')
@authenticated
@inject.params(client=FsDriveClient)
@async_click
async def download_command(client: FsDriveClient, remote: str, local: str):
try:
await client.download(remote, local)
except DriveNotFoundException:
raise click.ClickException(f'{remote} not found')
| StarcoderdataPython |
11211254 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def calculateABCsaving(p: float, q: float, D_parts: pd.DataFrame):
"""
Calculate the saving based on re-assignment with classes ABC, compared with a random assignment scenario
Args:
p (float): warehouse front length in meters.
q (float): warehouse depth in meters.
D_parts (pd.DataFrame): dataframe containing SKUs with columns POP_IN_TOT and POP_OUT_TOT.
Returns:
list: list of threshold of class A.
list: list of threshold of class B.
list: optimal saving inbound.
list: optimal saving inbound.
float: best threshold A class.
float: best threshold B class.
float: best total saving (IN + OUT).
"""
# Check the input columns of the dataframe
checkColumns = ['POP_IN_TOT', 'POP_OUT_TOT']
for col in checkColumns:
if col not in D_parts.columns:
print(f"Column {col} not in dataframe D_parts")
return [], [], [], [], [], [], []
# ############################ SCENARIO RANDOM #################################
if (~np.isnan(p) or ~np.isnan(q)):
# count pick in and out
pickIN = sum(D_parts['POP_IN_TOT'])
pickOUT = sum(D_parts['POP_OUT_TOT'])
D_parts['POP_TOT'] = D_parts['POP_IN_TOT'] + D_parts['POP_OUT_TOT']
# Random scenario
# I/O distributed on the front
r_cicloSemplice = (q / 2 + p / 3) * 2
KmIn_rand = pickIN * r_cicloSemplice
KmOut_rand = pickOUT * r_cicloSemplice
SAVING_IN = []
SAVING_OUT = []
soglieA = []
soglieB = []
# ############################ SCENARIO ABC ###################################
for i in range(0, 100, 10):
for j in range(i + 1, 100, 10):
sogliaA = i / 100
sogliaB = j / 100
D_pop_totale = D_parts.groupby('ITEMCODE')['POP_TOT'].sum().reset_index()
D_pop_totale = D_pop_totale.sort_values(by='POP_TOT', ascending=False)
sogliaClasseA = int(np.round(sogliaA * len(D_pop_totale)))
sogliaClasseB = int(np.round(sogliaB * len(D_pop_totale)))
ITEM_A = D_pop_totale['ITEMCODE'].iloc[0: sogliaClasseA].reset_index()
ITEM_B = D_pop_totale['ITEMCODE'].iloc[sogliaClasseA: sogliaClasseB].reset_index()
ITEM_C = D_pop_totale['ITEMCODE'].iloc[sogliaClasseB: len(D_pop_totale)].reset_index()
# Count pickIn
num_pickin_A = sum(D_parts[D_parts['ITEMCODE'].isin(ITEM_A['ITEMCODE'])]['POP_IN_TOT'])
num_pickin_B = sum(D_parts[D_parts['ITEMCODE'].isin(ITEM_B['ITEMCODE'])]['POP_IN_TOT'])
num_pickin_C = sum(D_parts[D_parts['ITEMCODE'].isin(ITEM_C['ITEMCODE'])]['POP_IN_TOT'])
# Count le pickOUT
num_pickout_A = sum(D_parts[D_parts['ITEMCODE'].isin(ITEM_A['ITEMCODE'])]['POP_OUT_TOT'])
num_pickout_B = sum(D_parts[D_parts['ITEMCODE'].isin(ITEM_B['ITEMCODE'])]['POP_OUT_TOT'])
num_pickout_C = sum(D_parts[D_parts['ITEMCODE'].isin(ITEM_C['ITEMCODE'])]['POP_OUT_TOT'])
len_q_A = len(ITEM_A) / (len(ITEM_A) + len(ITEM_B) + len(ITEM_C))
len_q_B = len(ITEM_B) / (len(ITEM_A) + len(ITEM_B) + len(ITEM_C))
len_q_C = len(ITEM_C) / (len(ITEM_A) + len(ITEM_B) + len(ITEM_C))
# Calculate the km
# check OK number picks
if((num_pickin_A + num_pickin_B + num_pickin_C) == pickIN) & ((num_pickout_A + num_pickout_B + num_pickout_C) == pickOUT):
# I/O distributed on the front
dist_A = (q * len_q_A / 2 + p / 3) * 2
dist_B = (q * (len_q_A + len_q_B / 2) + p / 3) * 2
dist_C = (q * (len_q_A + len_q_B + len_q_C / 2) + p / 3) * 2
KmIn_ABC = (num_pickin_A * dist_A + num_pickin_B * dist_B + num_pickin_C * dist_C)
KmOut_ABC = (num_pickout_A * dist_A + num_pickout_B * dist_B + num_pickout_C * dist_C)
if (KmIn_rand == 0): # avoid division by zero
sav_IN = 0
else:
sav_IN = 1 - float(KmIn_ABC / KmIn_rand)
if (KmOut_rand == 0): # avoid division by zero
sav_OUT = 0
else:
sav_OUT = 1 - float(KmOut_ABC / KmOut_rand)
SAVING_IN.append(sav_IN)
SAVING_OUT.append(sav_OUT)
soglieA.append(sogliaA)
soglieB.append(sogliaB)
# calculate best saving scenario
SAV_TOT = np.asarray(SAVING_IN) + np.asarray(SAVING_OUT)
idx = np.nanargmax(SAV_TOT)
best_A = np.round(soglieA[idx], 1)
best_B = np.round(soglieB[idx], 1)
else:
print("Error: num pick scenario ABC does not match num pick scenario random")
return soglieA, soglieB, SAVING_IN, SAVING_OUT, best_A, best_B, SAV_TOT[idx]
else:
return [], [], [], [], [], [], []
def defineABCclassesOfStorageLocations(D_nodes: pd.DataFrame, AclassPerc: float = .2, BclassPerc: float = .5) -> pd.DataFrame:
"""
Define the classes A, B, C for each storage location (nodes of the warehouse).
Args:
D_nodes (pd.DataFrame): pandas dataframe with storage locations and INPUT_DISTANCE and OUTPUT_DISTANCE .
AclassPerc (float, optional): class A threshold. Defaults to .2.
BclassPerc (float, optional): class B threshold. Defaults to .5.
Returns:
TYPE: input dataframe with the column CLASS (A,B,C) for each storage location.
"""
# Check the input columns of the dataframe
checkColumns = ['INPUT_DISTANCE', 'OUTPUT_DISTANCE']
for col in checkColumns:
if col not in D_nodes.columns:
print(f"Column {col} not in dataframe D_parts")
return []
# calculate total distance
D_nodes['WEIGHT'] = D_nodes['INPUT_DISTANCE'] + D_nodes['OUTPUT_DISTANCE']
D_nodes = D_nodes.sort_values(by='WEIGHT', ascending=False)
D_nodes['WEIGHT'] = D_nodes['WEIGHT'] / sum(D_nodes['WEIGHT'])
D_nodes['WEIGHT_cum'] = D_nodes['WEIGHT'].cumsum()
# assign classes
D_nodes['CLASS'] = np.nan
for i in range(0, len(D_nodes)):
if D_nodes.iloc[i]['WEIGHT_cum'] < AclassPerc:
D_nodes.iloc[i, D_nodes.columns.get_loc('CLASS')] = 'A'
elif (D_nodes.iloc[i]['WEIGHT_cum'] >= AclassPerc) & (D_nodes.iloc[i]['WEIGHT_cum'] < BclassPerc):
D_nodes.iloc[i, D_nodes.columns.get_loc('CLASS')] = 'B'
else:
D_nodes.iloc[i, D_nodes.columns.get_loc('CLASS')] = 'C'
return D_nodes
def defineABCclassesOfParts(D_parts: pd.DataFrame, columnWeightList: list,
AclassPerc: float = .2, BclassPerc: float = .5) -> pd.DataFrame:
"""
Assign classes A, B, C to the SKUs of the master files.
Args:
D_parts (pd.DataFrame): dataframe of parts.
columnWeightList (list): list of column of D_parts with the weights to consider to define ABC classes.
AclassPerc (float, optional): cut percentile of class A. Defaults to .2.
BclassPerc (float, optional): cut percentile of class B. Defaults to .5.
Returns:
D_parts (pd.DataFrame): Output DataFrame with classes for each SKU.
"""
D_parts['WEIGHT'] = 0
# calculate total distance
for col in columnWeightList:
if col in D_parts.columns:
D_parts['WEIGHT'] = D_parts['WEIGHT'] + D_parts[col]
else:
print(f"Column {col} not in index, column ignored")
D_parts = D_parts.sort_values(by='WEIGHT', ascending=False)
D_parts['WEIGHT'] = D_parts['WEIGHT'] / sum(D_parts['WEIGHT'])
D_parts['WEIGHT_cum'] = D_parts['WEIGHT'].cumsum()
# assign classes
D_parts['CLASS'] = np.nan
for i in range(0, len(D_parts)):
if D_parts.iloc[i]['WEIGHT_cum'] < AclassPerc:
D_parts.iloc[i, D_parts.columns.get_loc('CLASS')] = 'A'
elif (D_parts.iloc[i]['WEIGHT_cum'] >= AclassPerc) & (D_parts.iloc[i]['WEIGHT_cum'] < BclassPerc):
D_parts.iloc[i, D_parts.columns.get_loc('CLASS')] = 'B'
else:
D_parts.iloc[i, D_parts.columns.get_loc('CLASS')] = 'C'
return D_parts
def plotSavingABCclass(p: float, q: float, D_SKUs: pd.DataFrame) -> dict:
"""
Plot the 3d graph with saving given different values of a, b, c thresholds
Args:
p (float): warehouse front length in meters.
q (float): warehouse depth in meters.
D_SKUs (pd.DataFrame): DataFrame of the Sku master file.
Returns:
dict: output dictionary containing figures.
"""
figure_output = {}
# calculate saving
soglieA, soglieB, SAVING_IN, SAVING_OUT, best_A, best_B, SAV_TOT = calculateABCsaving(p, q, D_SKUs)
# inbound saving
fig1 = plt.figure()
ax = fig1.add_subplot(111, projection='3d')
ax.scatter(soglieA,
soglieB,
SAVING_IN,
color='orange'
)
plt.xlabel("A class threshold")
plt.ylabel("B class threshold")
plt.title("Inbound saving ")
figure_output["IN_saving_ABC_inbound"] = fig1
# outbound saving
fig1 = plt.figure()
ax = fig1.add_subplot(111, projection='3d')
ax.scatter(soglieA,
soglieB,
SAVING_OUT,
color='orange'
)
plt.xlabel("A class threshold")
plt.ylabel("B class threshold")
plt.title("Outbound saving ")
figure_output["IN_saving_ABC_outbound"] = fig1
return figure_output
| StarcoderdataPython |
6606134 | #!/usr/bin/env python
import sys
import cv2
import numpy as np
import matplotlib.pyplot as plt
import copy
import sift
class Circle_Detect:
def __init__(self, image):
self.image = image
self.dp = 1
self.minDist = 20
self.param1 = 50
self.param2 = 30
self.minRadius = 0
self.maxRadius = 0
def dp_update(self, level):
self.dp = level
self.detect_circles(self.image.copy())
def minDist_update(self, level):
self.minDist = level
self.detect_circles(self.image.copy())
def param1_update(self, level):
self.param1 = level
self.detect_circles(self.image.copy())
def param2_update(self, level):
self.param2 = level
self.detect_circles(self.image.copy())
def minRadius_update(self, level):
self.minRadius = level
self.detect_circles(self.image.copy())
def maxRadius_update(self, level):
self.maxRadius = level
self.detect_circles(self.image.copy())
def main(self, img):
# sift.feat_detection(img)
self.detect_circles(img)
cv2.namedWindow('image', cv2.WINDOW_AUTOSIZE)
cv2.createTrackbar( "DP", "image", 1, 1000, self.dp_update)
cv2.createTrackbar( "Min Dist", "image", 1, 50, self.minDist_update)
cv2.createTrackbar( "Param 1", "image", 1, 100, self.param1_update)
cv2.createTrackbar( "Param 2", "image", 1, 100, self.param2_update)
cv2.createTrackbar( "Min Radius", "image", 0, 100, self.minRadius_update)
cv2.createTrackbar( "Max Radius", "image", 0, 100, self.maxRadius_update)
cv2.imshow('image', img)
0xFF & cv2.waitKey()
cv2.destroyAllWindows()
def detect_circles(self, img):
# img = cv2.medianBlur(img, 5)
# grayImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
circles = cv2.HoughCircles(img, cv2.cv.CV_HOUGH_GRADIENT, self.dp, self.minDist, param1=self.param1, param2=self.param2, minRadius=self.minRadius, maxRadius=self.maxRadius)
# circles = cv2.HoughCircles(img, cv2.cv.CV_HOUGH_GRADIENT, 1.2, 75)
# circles = np.uint(np.around(circles, decimals=2))
if circles is not None:
# circles = np.uint(circles, decimals=2)
circles = np.round(circles[0, :]).astype("int")
for (x, y, r) in circles:
# outer circle
cv2.circle(img, (x, y), r, (100,100,10), 4)
# center of circle
# cv2.circle(grayImg, ], i[1]), 2, (0,0,255), 3)
#
cv2.imshow('image', np.hstack([img]))
# plt.imshow(np.hstack([img]))
# plt.title("Circles")
# plt.show()
else:
cv2.imshow('image', img)
# plt.imshow(img)
# plt.title("Circles")
# plt.show()
# cv2.waitKey()
if __name__ == '__main__':
# img = cv2.imread("masked.jpg", 0)
img = cv2.imread("images/trial.cup_ring.jpg", 0)
img = cv2.resize(img, (0,0), fx = 5, fy = 5)
img = cv2.GaussianBlur(img,(5,5),0)
cd = Circle_Detect(img)
cd.main(img) | StarcoderdataPython |
6516373 | <reponame>abosoar/camel_tools
# -*- coding: utf-8 -*-
# MIT License
#
# Copyright 2018-2020 New York University <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""The morphological analyzer component of CAMeL Tools.
"""
from __future__ import absolute_import
from collections import deque, namedtuple
import copy
import itertools
import re
from threading import RLock
from cachetools import LFUCache, cached
from camel_tools.utils.charsets import UNICODE_PUNCT_SYMBOL_CHARSET
from camel_tools.utils.charsets import AR_CHARSET, AR_DIAC_CHARSET
from camel_tools.utils.charmap import CharMapper
from camel_tools.morphology.database import MorphologyDB
from camel_tools.morphology.errors import AnalyzerError
from camel_tools.morphology.utils import merge_features
from camel_tools.morphology.utils import simple_ar_to_caphi
from camel_tools.utils.dediac import dediac_ar
_ALL_PUNC = u''.join(UNICODE_PUNCT_SYMBOL_CHARSET)
_DIAC_RE = re.compile(u'[' + re.escape(u''.join(AR_DIAC_CHARSET)) + u']')
_IS_DIGIT_RE = re.compile(u'^.*[0-9\u0660-\u0669]+.*$')
_IS_STRICT_DIGIT_RE = re.compile(u'^[0-9\u0660-\u0669]+$')
_IS_PUNC_RE = re.compile(u'^[' + re.escape(_ALL_PUNC) + u']+$')
_HAS_PUNC_RE = re.compile(u'[' + re.escape(_ALL_PUNC) + u']')
_IS_AR_RE = re.compile(u'^[' + re.escape(u''.join(AR_CHARSET)) + u']+$')
# Identify No Analysis marker
_NOAN_RE = re.compile(u'NOAN')
_COPY_FEATS = frozenset(['gloss', 'atbtok', 'atbseg', 'd1tok', 'd1seg',
'd2tok', 'd2seg', 'd3tok', 'd3seg', 'bwtok'])
_UNDEFINED_LEX_FEATS = frozenset(['root', 'pattern', 'caphi'])
DEFAULT_NORMALIZE_MAP = CharMapper({
u'\u0625': u'\u0627',
u'\u0623': u'\u0627',
u'\u0622': u'\u0627',
u'\u0671': u'\u0627',
u'\u0649': u'\u064a',
u'\u0629': u'\u0647',
u'\u0640': u''
})
""":obj:`~camel_tools.utils.charmap.CharMapper`: The default character map used
for normalization by :obj:`Analyzer`.
Removes the tatweel/kashida character and does the following conversions:
- 'إ' to 'ا'
- 'أ' to 'ا'
- 'آ' to 'ا'
- 'ٱ' to 'ا'
- 'ى' to 'ي'
- 'ة' to 'ه'
"""
_BACKOFF_TYPES = frozenset(['NONE', 'NOAN_ALL', 'NOAN_PROP', 'ADD_ALL',
'ADD_PROP'])
class AnalyzedWord(namedtuple('AnalyzedWord', ['word', 'analyses'])):
"""A named tuple containing a word and its analyses.
Attributes:
word (:obj:`str`): The analyzed word.
analyses (:obj:`list` of :obj:`dict`): List of analyses for **word**.
See :doc:`/reference/camel_morphology_features` for more
information on features and their values.
"""
def _is_digit(word):
return _IS_DIGIT_RE.match(word) is not None
def _is_strict_digit(word):
return _IS_STRICT_DIGIT_RE.match(word) is not None
def _is_punc(word):
return _IS_PUNC_RE.match(word) is not None
def _has_punc(word):
return _HAS_PUNC_RE.search(word) is not None
def _is_ar(word):
return _IS_AR_RE.match(word) is not None
def _segments_gen(word, max_prefix=1, max_suffix=1):
w = len(word)
for p in range(0, min(max_prefix, w - 1) + 1):
prefix = word[:p]
for s in range(max(1, w - p - max_suffix), w - p + 1):
stem = word[p:p+s]
suffix = word[p+s:]
yield (prefix, stem, suffix)
class Analyzer:
"""Morphological analyzer component.
Args:
db (:obj:`~camel_tools.morphology.database.MorphologyDB`): Database to
use for analysis. Must be opened in analysis or reinflection mode.
backoff (:obj:`str`, optional): Backoff mode. Can be one of the
following: 'NONE', 'NOAN_ALL', 'NOAN_PROP', 'ADD_ALL', or
'ADD_PROP'. Defaults to 'NONE'.
norm_map (:obj:`~camel_tools.utils.charmap.CharMapper`, optional):
Character map for normalizing input words. If set to None, then
:const:`DEFAULT_NORMALIZE_MAP` is used.
Defaults to None.
strict_digit (:obj:`bool`, optional): If set to `True`, then only words
completely comprised of digits are considered numbers, otherwise,
all words containing a digit are considered numbers. Defaults to
`False`.
cache_size (:obj:`int`, optional): If greater than zero, then the
analyzer will cache the analyses for the **cache_Size** most
frequent words, otherwise no analyses will be cached.
Raises:
:obj:`~camel_tools.morphology.errors.AnalyzerError`: If database is
not an instance of
(:obj:`~camel_tools.morphology.database.MorphologyDB`), if **db**
does not support analysis, or if **backoff** is not a valid backoff
mode.
"""
def __init__(self, db, backoff='NONE',
norm_map=None,
strict_digit=False,
cache_size=0):
if not isinstance(db, MorphologyDB):
raise AnalyzerError('DB is not an instance of MorphologyDB')
if not db.flags.analysis:
raise AnalyzerError('DB does not support analysis')
self._db = db
self._backoff = backoff
self._strict_digit = strict_digit
if norm_map is None:
self._norm_map = DEFAULT_NORMALIZE_MAP
else:
self._norm_map = norm_map
if backoff in _BACKOFF_TYPES:
if backoff == 'NONE':
self._backoff_condition = None
self._backoff_action = None
else:
backoff_toks = backoff.split('_')
self._backoff_condition = backoff_toks[0]
self._backoff_action = backoff_toks[1]
else:
raise AnalyzerError('Invalid backoff mode {}'.format(
repr(backoff)))
if isinstance(cache_size, int):
if cache_size > 0:
cache = LFUCache(cache_size)
self.analyze = cached(cache, lock=RLock())(self.analyze)
else:
raise AnalyzerError('Invalid cache size {}'.format(
repr(cache_size)))
def _normalize(self, word):
if self._norm_map is None:
return word
return self._norm_map.map_string(word)
def _combined_analyses(self,
word_dediac,
prefix_analyses,
stem_analyses,
suffix_analyses):
combined = deque()
for p in itertools.product(prefix_analyses, stem_analyses):
prefix_cat = p[0][0]
prefix_feats = p[0][1]
stem_cat = p[1][0]
stem_feats = p[1][1]
if stem_cat in self._db.prefix_stem_compat[prefix_cat]:
for suffix_cat, suffix_feats in suffix_analyses:
if ((stem_cat not in self._db.stem_suffix_compat) or
(prefix_cat not in self._db.prefix_suffix_compat) or
(suffix_cat not in
self._db.stem_suffix_compat[stem_cat]) or
(suffix_cat not in
self._db.prefix_suffix_compat[prefix_cat])):
continue
merged = merge_features(self._db, prefix_feats, stem_feats,
suffix_feats)
merged['stem'] = stem_feats['diac']
merged['stemcat'] = stem_cat
merged_dediac = dediac_ar(merged['diac'])
if word_dediac.replace(u'\u0640', '') != merged_dediac:
merged['source'] = 'spvar'
combined.append(merged)
return combined
def _combined_backoff_analyses(self,
stem,
word_dediac,
prefix_analyses,
stem_analyses,
suffix_analyses):
combined = deque()
for p in itertools.product(prefix_analyses, stem_analyses):
prefix_cat = p[0][0]
prefix_feats = p[0][1]
stem_cat = p[1][0]
stem_feats = copy.copy(p[1][1])
if stem_cat in self._db.prefix_stem_compat[prefix_cat]:
for suffix_cat, suffix_feats in suffix_analyses:
if ((suffix_cat not in
self._db.stem_suffix_compat[stem_cat]) or
(prefix_cat not in self._db.prefix_suffix_compat or
suffix_cat not in
self._db.prefix_suffix_compat[prefix_cat])):
continue
if (self._backoff_action == 'PROP' and
'NOUN_PROP' not in stem_feats['bw']):
continue
stem_feats['bw'] = _NOAN_RE.sub(stem, stem_feats['bw'])
stem_feats['diac'] = _NOAN_RE.sub(stem, stem_feats['diac'])
stem_feats['lex'] = _NOAN_RE.sub(stem, stem_feats['lex'])
stem_feats['caphi'] = simple_ar_to_caphi(stem)
merged = merge_features(self._db, prefix_feats, stem_feats,
suffix_feats)
merged['stem'] = stem_feats['diac']
merged['stemcat'] = stem_cat
merged['source'] = 'backoff'
merged['gloss'] = stem_feats['gloss']
combined.append(merged)
return combined
# pylint: disable=E0202
def analyze(self, word):
"""Analyze a given word.
Args:
word (:py:obj:`str`): Word to analyze.
Returns:
:obj:`list` of :obj:`dict`: The list of analyses for **word**.
See :doc:`/reference/camel_morphology_features` for more
information on features and their values.
"""
word = word.strip()
if word == '':
return []
analyses = deque()
word_dediac = dediac_ar(word)
word_normal = self._normalize(word_dediac)
if ((self._strict_digit and _is_strict_digit(word)) or
(not self._strict_digit and _is_digit(word))):
result = copy.copy(self._db.defaults['digit'])
result['diac'] = word
result['stem'] = word
result['stemgloss'] = word
result['stemcat'] = None
result['lex'] = word + '_0'
result['bw'] = word + '/NOUN_NUM'
result['source'] = 'digit'
for feat in _COPY_FEATS:
if feat in self._db.defines:
result[feat] = word
for feat in _UNDEFINED_LEX_FEATS:
if feat in self._db.defines:
result[feat] = 'DIGIT'
if 'catib6' in self._db.defines:
result['catib6'] = 'NOM'
if 'ud' in self._db.defines:
result['ud'] = 'NUM'
result['pos_logprob'] = -99.0
result['lex_logprob'] = -99.0
result['pos_lex_logprob'] = -99.0
return [result]
elif _is_punc(word):
result = copy.copy(self._db.defaults['punc'])
result['diac'] = word
result['stem'] = word
result['stemgloss'] = word
result['stemcat'] = None
result['lex'] = word + '_0'
result['bw'] = word + '/PUNC'
result['source'] = 'punc'
for feat in _COPY_FEATS:
if feat in self._db.defines:
result[feat] = word
for feat in _UNDEFINED_LEX_FEATS:
if feat in self._db.defines:
result[feat] = 'PUNC'
if 'catib6' in self._db.defines:
result['catib6'] = 'PNX'
if 'ud' in self._db.defines:
result['ud'] = 'PUNCT'
result['pos_logprob'] = -99.0
result['lex_logprob'] = -99.0
result['pos_lex_logprob'] = -99.0
return [result]
elif _has_punc(word):
pass
elif not _is_ar(word):
result = copy.copy(self._db.defaults['noun'])
result['diac'] = word
result['stem'] = word
result['stemgloss'] = word
result['stemcat'] = None
result['lex'] = word + '_0'
result['bw'] = word + '/FOREIGN'
result['source'] = 'foreign'
for feat in _COPY_FEATS:
if feat in self._db.defines:
result[feat] = word
for feat in _UNDEFINED_LEX_FEATS:
if feat in self._db.defines:
result[feat] = 'FOREIGN'
if 'catib6' in self._db.defines:
result['catib6'] = 'FOREIGN'
if 'ud' in self._db.defines:
result['ud'] = 'X'
result['pos_logprob'] = -99.0
result['lex_logprob'] = -99.0
result['pos_lex_logprob'] = -99.0
return [result]
else:
segments_gen = _segments_gen(word_normal, self._db.max_prefix_size,
self._db.max_suffix_size)
for segmentation in segments_gen:
prefix = segmentation[0]
stem = segmentation[1]
suffix = segmentation[2]
prefix_analyses = self._db.prefix_hash.get(prefix, None)
suffix_analyses = self._db.suffix_hash.get(suffix, None)
if prefix_analyses is None or suffix_analyses is None:
continue
stem_analyses = self._db.stem_hash.get(stem, None)
if stem_analyses is not None:
combined = self._combined_analyses(word_dediac,
prefix_analyses,
stem_analyses,
suffix_analyses)
analyses.extend(combined)
if ((self._backoff_condition == 'NOAN' and len(analyses) == 0) or
(self._backoff_condition == 'ADD')):
segments_gen = _segments_gen(word_normal,
self._db.max_prefix_size,
self._db.max_suffix_size)
backoff_cats = self._db.stem_backoffs[self._backoff_action]
stem_analyses = [(cat, analysis)
for cat, analysis in self._db.stem_hash['NOAN']
if cat in backoff_cats]
for segmentation in segments_gen:
prefix = segmentation[0]
stem = segmentation[1]
suffix = segmentation[2]
prefix_analyses = self._db.prefix_hash.get(prefix, None)
suffix_analyses = self._db.suffix_hash.get(suffix, None)
if prefix_analyses is None or suffix_analyses is None:
continue
combined = self._combined_backoff_analyses(stem,
word_dediac,
prefix_analyses,
stem_analyses,
suffix_analyses)
analyses.extend(combined)
result = list(analyses)
return result
def analyze_words(self, words):
'''Analyze a list of words.
Args:
words (:py:obj:`list` of :py:obj:`str`): List of words to analyze.
Returns:
:obj:`list` of :obj:`AnalyzedWord`: The list of analyses for each
word in **words**.
'''
return list(map(lambda w: AnalyzedWord(w, self.analyze(w)), words))
| StarcoderdataPython |
12826153 | <gh_stars>10-100
# pyflyby/test_modules.py
# License for THIS FILE ONLY: CC0 Public Domain Dedication
# http://creativecommons.org/publicdomain/zero/1.0/
from __future__ import (absolute_import, division, print_function,
with_statement)
import logging.handlers
from pyflyby._file import Filename
from pyflyby._idents import DottedIdentifier
from pyflyby._modules import ModuleHandle
import re
import subprocess
import sys
from textwrap import dedent
import pytest
def test_ModuleHandle_1():
m = ModuleHandle("sys")
assert m.name == DottedIdentifier("sys")
def test_ModuleHandle_dotted_1():
m = ModuleHandle("logging.handlers")
assert m.name == DottedIdentifier("logging.handlers")
def test_ModuleHandle_from_module_1():
m = ModuleHandle(logging.handlers)
assert m == ModuleHandle("logging.handlers")
assert m.name == DottedIdentifier("logging.handlers")
def test_eqne_1():
m1a = ModuleHandle("foo.bar")
m1b = ModuleHandle("foo.bar")
m2 = ModuleHandle("foo.baz")
assert (m1a == m1b)
assert not (m1a != m1b)
assert not (m1a == m2)
assert (m1a != m2)
def test_filename_1():
fn = logging.handlers.__file__
fn = Filename(re.sub("[.]pyc$", ".py", fn)).real
m = ModuleHandle("logging.handlers")
assert m.filename.real == fn
assert m.filename.base == "handlers.py"
def test_filename_init_1():
fn = logging.__file__
fn = Filename(re.sub("[.]pyc$", ".py", fn)).real
m = ModuleHandle("logging")
assert m.filename.real == fn
assert m.filename.base == "__init__.py"
def test_module_1():
m = ModuleHandle("logging")
assert m.module is logging
@pytest.mark.xfail(reason="Fails on CI not locally")
def test_filename_noload_1():
# ensure there is no problem with sys.exit itself.
retcode = subprocess.call([sys.executable, '-c', dedent('''
import sys
sys.exit(0)
''')])
assert retcode == 0
# Ensure there is no error with byflyby itself
retcode = subprocess.call([sys.executable, '-c', dedent('''
from pyflyby._modules import ModuleHandle
import sys
ModuleHandle("multiprocessing").filename
sys.exit(0)
''')])
assert retcode == 0
# don't exit with 1, as something else may exit with 1.
retcode = subprocess.call([sys.executable, '-c', dedent('''
from pyflyby._modules import ModuleHandle
import sys
ModuleHandle("multiprocessing").filename
if "multiprocessing" in sys.modules:
sys.exit(123)
else:
sys.exit(0)
''')])
assert retcode == 0
| StarcoderdataPython |
1671507 | from django.db import models
class DatabaseMaintenanceTaskManager(models.Manager):
use_for_related_fields = True
def need_retry(self, **kwargs):
""" This method checks wheather a maintenance task needs retry or not.
It returns the task itself or False when there's no task that have
failed. This implementation only works for models composed by a
database(type Database) attribute."""
database = kwargs.get('database', None)
last_task = self.filter(database=database).last()
if (last_task and last_task.status == self.model.ERROR and
last_task.can_do_retry):
return last_task
return False
| StarcoderdataPython |
11283463 | <filename>FaceMaskDetection/facemaskdetection.py
# -*- coding: utf-8 -*-
"""FaceMaskDetection.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1lDfb32EUzTnnK_57UtD5l3Q_tEF3ITpg
"""
# Commented out IPython magic to ensure Python compatibility.
"""
import all required libraries
"""
import cv2
import matplotlib.pyplot as plt
import numpy as np
import glob
import os
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, MaxPooling2D, Activation, Dropout,Flatten,Conv2D
from tensorflow.keras.preprocessing import image
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow import keras
from PIL import Image
import os
import pandas as pd
"""
store path for all train, validation and test data
"""
train_real_face_image_directory='/content/drive/MyDrive/Colab Notebooks/Datasets/RFMD/train/'
validation_real_face_image_directory='/content/drive/MyDrive/Colab Notebooks/Datasets/RFMD/validation/'
test_real_face_image_directory='/content/drive/MyDrive/Colab Notebooks/Datasets/RFMD/test/'
train_real_simulated_combined_image_directory='/content/drive/MyDrive/Colab Notebooks/Datasets/combined/train/'
validation_real_simulated_combined_image_directory='/content/drive/MyDrive/Colab Notebooks/Datasets/combined/validation/'
test_real_simulated_combined_image_directory='/content/drive/MyDrive/Colab Notebooks/Datasets/combined/test/'
train_simulated_image_directory='/content/drive/MyDrive/Colab Notebooks/Datasets/SFMD/train/'
validation_simulated_image_directory='/content/drive/MyDrive/Colab Notebooks/Datasets/SFMD/validation/'
test_simulated_image_directory='/content/drive/MyDrive/Colab Notebooks/Datasets/SFMD/test/'
train_simulated_roi_image_directory='/content/drive/MyDrive/Colab Notebooks/Datasets/ROI/SFMD/train/'
validation_simulated_roi_image_directory='/content/drive/MyDrive/Colab Notebooks/Datasets/ROI/SFMD/validation/'
test_simulated_roi_image_directory='/content/drive/MyDrive/Colab Notebooks/Datasets/ROI/SFMD/test/'
train_real_face_roi_image_directory='/content/drive/MyDrive/Colab Notebooks/Datasets/ROI/RFMD/train/'
validation_real_face_roi_image_directory='/content/drive/MyDrive/Colab Notebooks/Datasets/ROI/RFMD/validation/'
test_real_face_roi_image_directory='/content/drive/MyDrive/Colab Notebooks/Datasets/ROI/RFMD/test/'
train_real_roi_combined_directory='/content/drive/MyDrive/Colab Notebooks/RFMD/train/'
test_real_roi_combined_directory='/content/drive/MyDrive/Colab Notebooks/RFMD/test/'
validation_real_roi_combined_directory='/content/drive/MyDrive/Colab Notebooks/RFMD/validation/'
train_simulated_face_roi_combined_directory='/content/drive/MyDrive/Colab Notebooks/SFMD/train/'
test_simulated_face_roi_combined_directory='/content/drive/MyDrive/Colab Notebooks/SFMD/test/'
validation_simulated_face_roi_combined_directory='/content/drive/MyDrive/Colab Notebooks/SFMD/validation/'
train_all_combined_directory='/content/drive/MyDrive/Colab Notebooks/all/train/'
test_all_combined_directory='/content/drive/MyDrive/Colab Notebooks/all/test/'
validation_all_combined_directory='/content/drive/MyDrive/Colab Notebooks/all/validation/'
train_real_simulated_roi_image_directory='content/drive/MyDrive/Colab Notebooks/ROI/real_simuluated/train/'
validation_real_simulated_roi_image_directory='content/drive/MyDrive/Colab Notebooks/ROI/real_simuluated/validation/'
test_real_simulated_roi_image_directory='content/drive/MyDrive/Colab Notebooks/ROI/real_simuluated/test/'
"""
image generator method returns newly classified image after rescaling
"""
def image_genarator():
image_gen=ImageDataGenerator(
zoom_range=0.2,
shear_range=0.2,
rescale=1/255,
horizontal_flip=False
)
return image_gen
"""
fixed input shape for model
"""
input_shape = (150,150,3)
"""
this method prepare our model and return
"""
def prepare_model():
model = Sequential()
model.add(Conv2D(filters=32, kernel_size=(3,3),input_shape=input_shape, activation='relu',))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(filters=32, kernel_size=(3,3),input_shape=input_shape, activation='relu',))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(filters=64, kernel_size=(3,3),input_shape=input_shape, activation='relu',))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
return model
"""
create model object
"""
real_face_model=prepare_model()
"""
observe the model summary
"""
real_face_model.summary()
"""
create image generator object
"""
image_generator=image_genarator()
"""
this method take image directory as argument and prepare image generator and return
"""
def prepare_images(imageDirectory):
batch_size=16
images_genarator=image_generator.flow_from_directory(imageDirectory,target_size=input_shape[:2],batch_size=batch_size,class_mode='binary')
return images_genarator
"""
prepare all train, validation and test image generator for real human face with mask and without mask
"""
train_real_face_image_generator=prepare_images(train_real_face_image_directory)
validation_real_face_image_generator=prepare_images(validation_real_face_image_directory)
test_real_face_image_generator=prepare_images(test_real_face_image_directory)
"""
fit the model with train data and validation data
"""
real_face_model_results= real_face_model.fit(train_real_face_image_generator,epochs=6,steps_per_epoch=200,validation_data=validation_real_face_image_generator,validation_steps=20)
"""
save the model
"""
real_face_model.save('/content/drive/MyDrive/Colab Notebooks/MaskDetectionData/final_model/real_face_model.h5')
"""
evaluate the model performance with test data
"""
real_face_evaluation=real_face_model.evaluate(test_real_face_image_generator,batch_size=2,verbose=1)
"""
prepare all train, validation and test image generator for simulated human face with mask and without mask
"""
train_simulated_image_generator=prepare_images(train_simulated_image_directory)
validation_simulated_image_generator=prepare_images(validation_simulated_image_directory)
test_simulated_image_generator=prepare_images(test_simulated_image_directory)
"""
create simulated model object and fit the model with train and valudation data
"""
simulated_face_model=prepare_model()
simulated_results= simulated_face_model.fit(train_simulated_image_generator,epochs=6,steps_per_epoch=91,validation_data=validation_simulated_image_generator,validation_steps=20)
"""
evaluated the simulated model and save it
"""
simulated_evaluation=simulated_face_model.evaluate(test_simulated_image_generator,batch_size=2,verbose=1)
simulated_face_model.save('/content/drive/MyDrive/Colab Notebooks/MaskDetectionData/final_model/simulated_face_model.h5')
"""
prepare all train, validation and test image generator for real and simulated
human face with mask and without mask
"""
train_real_simulated_combined_image_generator=prepare_images(train_real_simulated_combined_image_directory)
validation_real_simulated_combined_image_generator=prepare_images(validation_real_simulated_combined_image_directory)
test_image_real_simulated_combined_generator=prepare_images(test_real_simulated_combined_image_directory)
"""
cread combined of real and simulated model and fit the model
"""
combined_real_simulated_face_model=prepare_model()
combined_real_simulated_face_results= combined_real_simulated_face_model.fit(train_real_simulated_combined_image_generator,epochs=6,steps_per_epoch=200,validation_data=validation_real_simulated_combined_image_generator,validation_steps=20)
"""
evaluated the combined model and save it
"""
combined_real_simulated_face_evaluation=combined_real_simulated_face_model.evaluate(test_image_real_simulated_combined_generator,batch_size=2,verbose=1)
combined_real_simulated_face_model.save('/content/drive/MyDrive/Colab Notebooks/MaskDetectionData/final_model/combined_real_simulated_face_model.h5')
"""
prepare all train, validation and test image generator for only simulated
face which is detected from simulated image with mask and without mask
"""
train_simulated_roi_image_generator=prepare_images(train_simulated_roi_image_directory)
validation_simulated_roi_image_generator=prepare_images(validation_simulated_roi_image_directory)
test_simulated_roi_image_generator=prepare_images(test_simulated_roi_image_directory)
"""
create model and fit the model for the data
"""
simulated_roi_model=prepare_model()
simulated_roi_result=simulated_roi_model.fit(train_simulated_roi_image_generator,epochs=6,steps_per_epoch=65,validation_data=validation_simulated_roi_image_generator,validation_steps=20)
"""
evaluate the model and save it
"""
simulated_roi_evaulation=simulated_roi_model.evaluate(test_simulated_roi_image_generator,batch_size=2,verbose=1)
simulated_roi_model.save('/content/drive/MyDrive/Colab Notebooks/MaskDetectionData/final_model/simulated_roi_model.h5')
"""
prepare all train, validation and test image generator for only
face which is detected from real human image with mask and without mask
"""
train_real_face_roi_image_generator=prepare_images(train_real_face_roi_image_directory)
validation_real_face_roi_image_generator=prepare_images(validation_real_face_roi_image_directory)
test_real_face_roi_image_generator=prepare_images(test_real_face_roi_image_directory)
"""
create model and fit the model for the data
"""
real_face_roi_model = prepare_model()
real_face_roi_result= real_face_roi_model.fit(train_real_face_roi_image_generator,epochs=6,steps_per_epoch=200,validation_data=validation_real_face_roi_image_generator,validation_steps=20)
"""
evaluate the model and save it
"""
real_face_roi_evaulation=real_face_roi_model.evaluate(test_real_face_roi_image_generator,batch_size=2,verbose=1)
real_face_roi_model.save('/content/drive/MyDrive/Colab Notebooks/MaskDetectionData/final_model/real_face_roi_model.h5')
"""
prepare all train, validation and test image generator for both real image and only
face which is detected from real human image with mask and without mask
"""
train_real_face_roi_combined_image_generator=prepare_images(train_real_roi_combined_directory)
validation_real_face_roi__combined_image_generator=prepare_images(validation_real_roi_combined_directory)
test_real_face_roi_combined_image_generator=prepare_images(test_real_roi_combined_directory)
"""
create model and fit the model for the data
"""
real_face_roi_combined_model = prepare_model()
real_face_roi_combined_result= real_face_roi_combined_model.fit(train_real_face_roi_combined_image_generator,epochs=6,steps_per_epoch=200,validation_data=validation_real_face_roi__combined_image_generator,validation_steps=20)
"""
evaluate the model and save it
"""
real_face_roi_combined_evaulation=real_face_roi_combined_model.evaluate(test_real_face_roi_combined_image_generator,batch_size=2,verbose=1)
real_face_roi_combined_model.save('/content/drive/MyDrive/Colab Notebooks/MaskDetectionData/final_model/real_face_roi_combined_model.h5')
"""
prepare all train, validation and test image generator for both simulated image and only
face which is detected from simulated image with mask and without mask
"""
train_simulated_face_roi_combined_image_generator=prepare_images(train_simulated_face_roi_combined_directory)
validation_simulated_face_roi_combined_image_generator=prepare_images(validation_simulated_face_roi_combined_directory)
test_simulated_face_roi_combined_image_generator=prepare_images(test_simulated_face_roi_combined_directory)
"""
create model and fit the model for the data
"""
simulated_face_roi_combined_model = prepare_model()
simulated_face_roi_combined_result= simulated_face_roi_combined_model.fit(train_simulated_face_roi_combined_image_generator,epochs=6,steps_per_epoch=100,validation_data=validation_simulated_face_roi_combined_image_generator,validation_steps=20)
"""
evaluate the model and save it
"""
simulated_face_roi_combined_evaulation=simulated_face_roi_combined_model.evaluate(test_simulated_face_roi_combined_image_generator,batch_size=2,verbose=1)
simulated_face_roi_combined_model.save('/content/drive/MyDrive/Colab Notebooks/MaskDetectionData/final_model/simulated_face_roi_combined_model.h5')
"""
prepare all train, validation and test image generator for both only face simulated image and only
face of real image with mask and without mask
"""
train_real_simulated_roi_image_generator=prepare_images(train_real_simulated_roi_image_directory)
validation_real_simulated_roi_image_generator=prepare_images(validation_real_simulated_roi_image_directory)
test_real_simulated_roi_image_generator=prepare_images(test_real_simulated_roi_image_directory)
"""
create model and fit the model for the data
"""
combined_real_simulated_roi_model=prepare_model()
combined_real_simulated_roi_model_result= combined_real_simulated_roi_model.fit(train_real_simulated_roi_image_generator,epochs=6,steps_per_epoch=200,validation_data=validation_real_simulated_roi_image_generator,validation_steps=20)
"""
evaluate the model and save it
"""
combined_real_simulated_roi_model_evaulation=combined_real_simulated_roi_model.evaluate(test_real_simulated_roi_image_generator,batch_size=2,verbose=1)
combined_real_simulated_roi_model.save('model/combined_real_simulated_roi_model.h5')
"""
prepare all train, validation and test image generator for all real , real face, simulated and simulated
with mask and without mask
"""
train_all_combined_image_generator=prepare_images(train_all_combined_directory)
validation_all_combined_image_generator=prepare_images(validation_all_combined_directory)
test_all_combined_image_generator=prepare_images(test_all_combined_directory)
"""
create model and fit the model for the data
"""
all_combined_model = prepare_model()
all_combined_result= all_combined_model.fit(train_all_combined_image_generator,epochs=6,steps_per_epoch=200,validation_data=validation_all_combined_image_generator,validation_steps=20)
"""
evaluate the model and save it
"""
all_combined_evaulation=all_combined_model.evaluate(test_all_combined_image_generator,batch_size=2,verbose=1)
all_combined_model.save('/content/drive/MyDrive/Colab Notebooks/MaskDetectionData/final_model/all_combined_model.h5')
| StarcoderdataPython |
93087 | import os
import shutil
import numpy as np
import mxnet as mx
from mxnet import gluon
from mxnet.gluon import nn
from mxnet import autograd as ag
def train_one_epoch(epoch, optimizer, train_data, criterion, ctx):
train_data.reset()
acc_metric = mx.metric.Accuracy()
loss_sum = 0.0
count = 0
for batch in train_data:
data = gluon.utils.split_and_load(batch.data[0], ctx_list=ctx,
batch_axis=0)
label = gluon.utils.split_and_load(batch.label[0], ctx_list=ctx,
batch_axis=0)
outputs = []
with ag.record():
for x, y in zip(data, label):
z = net(x)
loss = criterion(z, y)
loss_sum += float(loss.sum().asnumpy())
count += data[0].shape[0]
loss.backward()
outputs.append(z)
acc_metric.update(label, outputs)
optimizer.step(batch.data[0].shape[0])
_, avg_acc = acc_metric.get()
avg_loss = loss_sum / count
acc_metric.reset()
print('Epoch {} - Training: Avg accuracy: {:.2f} '
'Avg loss: {:.2f}'.format(epoch, 100.0*avg_acc, avg_loss))
def val_one_epoch(epoch, val_data, criterion, ctx):
val_data.reset()
acc_metric = mx.metric.Accuracy()
loss_sum = 0.0
count = 0
for batch in val_data:
data = gluon.utils.split_and_load(batch.data[0], ctx_list=ctx, batch_axis=0)
label = gluon.utils.split_and_load(batch.label[0], ctx_list=ctx, batch_axis=0)
outputs = []
for x, y in zip(data, label):
z = net(x)
loss = criterion(z, y)
loss_sum += float(loss.sum().asnumpy())
count += data[0].shape[0]
outputs.append(z)
acc_metric.update(label, outputs)
_, avg_acc = acc_metric.get()
avg_loss = loss_sum / count
acc_metric.reset()
if epoch >= 0:
print('Epoch {} - Validation: Avg accuracy: {:.2f} '
'Avg loss: {:.2f}'.format(epoch, 100.0*avg_acc, avg_loss))
return avg_acc
def save_checkpoint(net, checkpoint_dir, is_best=0):
net.save_params(os.path.join(checkpoint_dir, 'mnist_last.params'))
if is_best:
shutil.copyfile(os.path.join(checkpoint_dir, 'mnist_last.params'),
os.path.join(checkpoint_dir, 'mnist_best.params'))
def load_checkpoint(net, checkpoint_dir, val_data, criterion, ctx):
best_acc = 0
if not os.path.exists(checkpoint_dir):
os.mkdir(checkpoint_dir)
else:
if os.path.exists(os.path.join(checkpoint_dir,'mnist_best.params')):
net.load_params(os.path.join(checkpoint_dir,'mnist_best.params'))
best_acc = val_one_epoch(-1, val_data, criterion, ctx)
print('The last accuracy: {:.2f}'.format(100.0 * best_acc))
return best_acc
if __name__ == '__main__':
lr = 0.01
momentum = 0.5
epoch = 10
batch_size = 64
mnistdata_dir = '/gdata/MNIST'
checkpoint_dir = '/userhome/checkpoints'
train_data = mx.io.MNISTIter(
image=os.path.join(mnistdata_dir, "train-images-idx3-ubyte"),
label=os.path.join(mnistdata_dir, "train-labels-idx1-ubyte"),
batch_size=batch_size,
data_shape=(28, 28),
shuffle = True
)
val_data = mx.io.MNISTIter(
image=os.path.join(mnistdata_dir, "t10k-images-idx3-ubyte"),
label=os.path.join(mnistdata_dir, "t10k-labels-idx1-ubyte"),
batch_size=batch_size,
data_shape=(28, 28),
shuffle=False
)
net = nn.Sequential()
with net.name_scope():
net.add(nn.Conv2D(channels=10,kernel_size=5,use_bias=False)),
net.add(nn.MaxPool2D()),
net.add(nn.LeakyReLU(0))
net.add(nn.Conv2D(channels=20, kernel_size=5, use_bias=False)),
net.add(nn.Dropout(0.5)),
net.add(nn.MaxPool2D()),
net.add(nn.LeakyReLU(0)),
net.add(nn.Flatten()),
net.add(nn.Dense(50, activation='relu')),
net.add(nn.Dropout(0.5)),
net.add(nn.Dense(10))
gpus = mx.test_utils.list_gpus()
ctx = [mx.gpu()] if gpus else [mx.cpu(0), mx.cpu(1)]
net.initialize(mx.init.Xavier(magnitude=2.24), ctx=ctx)
trainer = gluon.Trainer(net.collect_params(), 'sgd',
{'learning_rate': lr, 'momentum':momentum})
softmax_cross_entropy_loss = gluon.loss.SoftmaxCrossEntropyLoss()
best_acc = load_checkpoint(net, checkpoint_dir, val_data, softmax_cross_entropy_loss, ctx)
print('start train...')
for i in range(epoch):
train_one_epoch(i, trainer, train_data, softmax_cross_entropy_loss, ctx)
acc = val_one_epoch(i, val_data, softmax_cross_entropy_loss, ctx)
is_best = acc > best_acc
best_acc = max(acc, best_acc)
save_checkpoint(net, checkpoint_dir, is_best)
| StarcoderdataPython |
11250446 | <reponame>behnazkhoshnood/boutique_ado_v1
from django.test import TestCase
from .forms import ContactForm
class TestContactForm(TestCase):
def test_email_is_requered(self):
form = ContactForm({'email': ''})
self.assertFalse(form.is_valid())
self.assertIn('email', form.errors.keys())
self.assertEqual(form.errors['email'][0], 'This field is required.')
def test_subject_is_requered(self):
form = ContactForm({'subject': ''})
self.assertFalse(form.is_valid())
self.assertIn('subject', form.errors.keys())
self.assertEqual(form.errors['subject'][0], 'This field is required.')
def test_message_is_requered(self):
form = ContactForm({'message': ''})
self.assertFalse(form.is_valid())
self.assertIn('message', form.errors.keys())
self.assertEqual(form.errors['message'][0], 'This field is required.')
| StarcoderdataPython |
11352728 | <filename>repokid/filters/utils.py
from typing import Optional
from repokid import CONFIG
from repokid.filters import FilterPlugins
from repokid.types import RepokidConfig
def get_filter_plugins(
account_number: str, config: Optional[RepokidConfig] = None
) -> FilterPlugins:
config = config or CONFIG
plugins = FilterPlugins()
# Blocklist needs to know the current account
filter_config = config["filter_config"]
blocklist_filter_config = filter_config.get(
"BlocklistFilter", filter_config.get("BlacklistFilter")
)
blocklist_filter_config["current_account"] = account_number
for plugin_path in config.get("active_filters", []):
plugin_name = plugin_path.split(":")[1]
if plugin_name == "ExclusiveFilter":
# ExclusiveFilter plugin active; try loading its config. Also, it requires the current account, so add it.
exclusive_filter_config = filter_config.get("ExclusiveFilter", {})
exclusive_filter_config["current_account"] = account_number
plugins.load_plugin(
plugin_path, config=config["filter_config"].get(plugin_name, None)
)
return plugins
| StarcoderdataPython |
11384029 | import pandas
import gym
import numpy as np
from sklearn.preprocessing import LabelEncoder
from keras.utils import np_utils
import tensorflow as tf
from tensorflow import keras
import os
currentDirectory = os.getcwd().replace('\\', '/')
datasetDirectory = currentDirectory.replace('/supervised-learning', '')
dataframe = pandas.read_csv(datasetDirectory + '/training_set.csv')
dataset = dataframe.T.values
voltages = dataset[1:,:41].astype(float)
action = dataset[1:,41]
action_onehot = np_utils.to_categorical(action) # Create one-hot encoding of action outputs
env = gym.make('gym_openDSS:openDSS-v0')
print('Number of actions: {}'.format(env.action_space.n))
# model = keras.Sequential([keras.layers.Flatten(input_shape=(1,) + env.observation_space.shape),
# keras.layers.Dense(len(env.VoltageMag), activation='relu'),
# keras.layers.Dense(len(env.VoltageMag), activation='relu'),
# keras.layers.Dense(len(env.VoltageMag), activation='relu'),
# keras.layers.Dense(4, activation='softmax')])
model = keras.Sequential([keras.layers.Flatten(input_shape=(1,) + env.observation_space.shape),
keras.layers.Dense(len(env.VoltageMag), activation='relu'),
keras.layers.Dense(4)])
# model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
# model.fit(voltages, action_onehot, epochs=100)
model.fit(voltages, action, epochs=50)
test_loss, test_acc = model.evaluate(voltages, action, verbose=2)
probability_model = tf.keras.Sequential([model, tf.keras.layers.Softmax()])
# Save model
probability_model.save(currentDirectory)
print("Saved model to disk")
predictions = probability_model.predict(voltages[:,:])
count = 0
for i in range(len(action)):
prediction = np.argmax(predictions[i])
print(prediction)
if prediction == action[i]:
count +=1
accuracy = count/len(action) | StarcoderdataPython |
4852182 | import bisect
def make_primes(n: int) -> list:
is_prime = [False, False] + ([True] * (n + 1))
for i in range(2, int(n**0.5) + 1):
if not is_prime[i]: continue
for j in range(i * 2, n + 1, i):
is_prime[j] = False
return [i for i in range(n + 1) if is_prime[i]]
X = int(input())
primes = make_primes(10**6)
print(primes[bisect.bisect_left(primes, X)]) | StarcoderdataPython |
1939982 | <filename>CS2/7200_RPG_turn_based_battle/main.py
import pygame, sprite, colors, game_manager
pygame.init()
screen_width = 1200
screen_height = 700
screen = pygame.display.set_mode((screen_width,screen_height))
clock = pygame.time.Clock()
gm = game_manager.GameManager(screen)
#Draw all images on the screen
done = False
while not done:
#Handle events and inputs
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
#Press enter to attack with current character
if event.key == pygame.K_RETURN:
gm.startAnimation()
#Press escape to quit
elif event.key == pygame.K_ESCAPE:
done = True
screen.fill(colors.black)
gm.update()
gm.draw()
pygame.display.flip()
#Delay to get 60 fps
clock.tick(60)
pygame.quit() | StarcoderdataPython |
3536593 | <gh_stars>1-10
import os
from random import randint
import shutil
from myhdl import *
from rhea.models.usbext import Fx2Model
from rhea.models.usbext.fx2 import slave_fifo
from rhea.utils.test import run_testbench
# The Fx2Model has two config modes. The actual FX2 controller has
# numerous programmable modes. The "configs" emulate configurations
# for different FX2 firmware (fpgalink, usrp, usbp, ...).
def test_config1_host_write():
"""
"""
fm = Fx2Model(config=1, verbose=True, trace=False)
fb = fm.get_bus()
tbdut = slave_fifo(fm, fb)
def _write(fm, num=1):
pass
def _read(fb, num=1):
yield fb.IFCLK.posedge
fb.SLRD.next = False
fb.SLOE.next = False
fb.ADDR.next = 0
for ii in range(num):
yield fb.IFCLK.posedge
fb.SLRD.next = True
fb.SLOE.next = True
fb.ADDR.next = 0
yield delay(3*fm.IFCLK_TICK)
def _bench_host_write():
@instance
def tbstim():
fb.ADDR.next = 0
yield delay(3*fm.IFCLK_TICK)
fb.RST.next = False
yield delay(13*fm.IFCLK_TICK)
fb.RST.next = True
yield delay(13*fm.IFCLK_TICK)
# FLAGC is gotdata
# FLAGB is gotroom
# In the config1 mode FLAGC is gotdata and FLAGB is gotroom.
# At start FLAGB == True and FLAGC == False. After a write
# FLAGC == True.
# Config1 onl
assert fb.FLAGB == True
assert fb.FLAGC == False
fm.write([0xCE], fm.EP2)
yield delay(3*fm.IFCLK_TICK)
assert fb.FLAGB == True # still should have room
assert fb.FLAGC == True # should have data now
assert fb.FDO == 0xCE
assert not fm.isempty(fm.EP2)
# read out the data written, 1 byte
yield _read(fb, 1)
assert fb.FLAGB == True # still should have room
assert fb.FLAGC == False # no data now
assert fm.isempty(fm.EP2)
yield delay(13*fm.IFCLK_TICK)
# Write a burst of data and read the burst of data
data = list(range(33))
data[0] = 0xFE
fm.write(data, fm.EP2)
yield delay(3*fm.IFCLK_TICK)
assert fb.FLAGB == True # still should have room
assert fb.FLAGC == True # should have data now
assert fb.FDO == 0xFE
assert not fm.isempty(fm.EP2)
yield _read(fb, 33)
assert fb.FLAGB == True # still should have room
assert fb.FLAGC == False # now data now
assert fm.isempty(fm.EP2)
# read one more
yield _read(fb, 1)
# fill the FIFO
data = [randint(0, 0xFF) for _ in range(512)]
fm.write(data, fm.EP2)
yield delay(3*fm.IFCLK_TICK)
assert fb.FLAGB == True # still should have room
assert fb.FLAGC == True # should have data now
assert fb.FDO == data[0]
assert not fm.isempty(fm.EP2)
yield _read(fb, 512)
assert fb.FLAGB == True # still should have room
assert fb.FLAGC == False # now data now
assert fm.isempty(fm.EP2)
# The model should handle flow, control it will take
# how much ever data? (this emulates how the host USB
# software stack would work).
data = [randint(0, 0xFF) for _ in range(517)]
fm.write(data, fm.EP2)
yield delay(3*fm.IFCLK_TICK)
assert fb.FLAGB == True # still should have room
assert fb.FLAGC == True # should have data now
assert fb.FDO == data[0]
assert not fm.isempty(fm.EP2)
yield _read(fb, 512)
assert fb.FLAGB == True # still should have room
assert fb.FLAGC == True # now data now
yield _read(fb, 7)
assert fb.FLAGB == True # still should have room
assert fb.FLAGC == False # now data now
assert fm.isempty(fm.EP2)
raise StopSimulation
return tbdut, tbstim
run_testbench(_bench_host_write)
def test_config1_host_read():
"""
"""
fm = Fx2Model(config=1, verbose=True, trace=False)
fb = fm.get_bus()
tbdut = slave_fifo(fm, fb)
def _write(fb, data):
yield fb.IFCLK.posedge
for dd in data:
fb.FDI.next = dd
fb.SLWR.next = False
yield fb.IFCLK.posedge
fb.SLWR.next = True
yield delay(3*fm.IFCLK_TICK)
def _read(fm, num=1):
pass
def _bench_host_read():
@instance
def tbstim():
fb.ADDR.next = 0
yield delay(3*fm.IFCLK_TICK)
fb.RST.next = False
yield delay(13*fm.IFCLK_TICK)
fb.RST.next = True
yield delay(13*fm.IFCLK_TICK)
fb.ADDR.next = 2
# FLAGC is gotdata
# FLAGB is gotroom
# In the config1 mode FLAGC is gotdata and FLAGB is gotroom.
# At start FLAGB == True and FLAGC == False. After a write
# FLAGC == True.
# Config1 onl
assert fb.FLAGB == True
assert fb.FLAGC == False
assert not fm.isdata(fm.EP6)
yield _write(fb, [0xCE])
assert fb.FLAGB == True
assert fb.FLAGC == False
assert fm.isdata(fm.EP6, num=1)
dd = fm.read(fm.EP6, num=1)
assert dd[0] == 0xCE
assert fb.FLAGB == True
assert fb.FLAGC == False
data = [randint(0, 0xFF) for _ in range(512)]
yield _write(fb, data)
assert fb.FLAGB == False
assert fb.FLAGC == False
assert fm.isdata(fm.EP6, num=1) # more than 1
assert fm.isdata(fm.EP6, num=512) # more than 1
yield _write(fb, [0xCE])
assert fb.FLAGB == False
assert fb.FLAGC == False
assert fm.isdata(fm.EP6, num=1) # more than 1
assert fm.isdata(fm.EP6, num=512) # more than 1
rdata = fm.read(fm.EP6, num=512)
for wd, rd in zip(data, rdata):
assert wd == rd
yield delay(13*fm.IFCLK_TICK)
assert fb.FLAGB == True
assert fb.FLAGC == False
assert not fm.isdata(fm.EP6)
raise StopSimulation
return tbdut, tbstim
run_testbench(_bench_host_read)
if __name__ == '__main__':
test_config1_host_write()
test_config1_host_read()
| StarcoderdataPython |
310284 | <filename>SW_lab/sw_lab_part4/servizio_mail/shell_utility_main.py
#!/usr/bin/env python3
"""
Exercise1 sw_lab4
:author: <NAME>, <NAME>
:copyright: Copyright 2020, <NAME>, <NAME>
..
Copyright 2020 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
# Standard Library
import json
from typing import Tuple
# Third Party
from prompt_toolkit.shortcuts import input_dialog
import requests
# -----------------------------------------------------------------------------
def gui() -> Tuple[str, int, str, str, str, str, str]:
ip = input_dialog(
title='Catalog IP',
text='Please type catalog IP:').run()
port = int(
input_dialog(
title='Catalog PORT',
text='Please type catalog PORT:').run()
)
user_id = input_dialog(
title='UserID',
text='Please type UserID:',
password=True
).run()
name = input_dialog(
title='Name',
text='Please type user Name:',
).run()
surname = input_dialog(
title='Surname',
text='Please type user Surname:',
).run()
work_email = input_dialog(
title='Work Email',
text='Please type Work email:',
).run()
personal_email = input_dialog(
title='Personal Email',
text='Please type Personal email:',
).run()
return ip, port, user_id, name, surname, work_email, personal_email
def main():
ip, port, user_id, name, surname, work_email, personal_email = gui()
if ip is "" or user_id is "" or name is "" or surname is "" or work_email is "" or personal_email is "":
print("WARNING, all fields must be entered. User not registered")
return
requests.post(
f"http://{ip}:{port}/catalog/users",
data=json.dumps(
{
"userID": user_id,
"name": name,
"surname": surname,
"email_addresses": {
"WORK": work_email,
"PERSONAL": personal_email
}
}
),
headers={"Content-Type": "application/json"}
)
if __name__ == "__main__":
main()
| StarcoderdataPython |
6534376 | from sqlalchemy import false, true
from api.extensions import mongo as db
from api.service import list_users
from api.service import update_balance as service
from flask import Response
import json
def create_new_transaction(transaction):
response = db.create_transaction(transaction)
return response
def update_values_of_transaction(transaction):
try:
data_payer = list_users.list_user_by_id(transaction["payer"])
#print("dados do pagador: ", data_payer)
user_payer = data_payer[0]
type_of_payer = user_payer["is_common_user"]
balance_payer = user_payer["balance"]
if type_of_payer != false:
dbResponsePayer = service.balance_update_payer(
transaction["payer"],
transaction["value"],
balance_payer)
#print("essa é a resposta do pagador: ", dbResponsePayer)
if dbResponsePayer != "not ok":
data_payee = list_users.list_user_by_id(transaction["payee"])
user_payee = data_payee[0]
balance_payee = user_payee["balance"]
dbResponsePayer = service.balance_update(
transaction["payee"],
transaction["value"],
balance_payee)
return true
else:
return "not ok"
except:
return "not ok" | StarcoderdataPython |
6583554 | <filename>importers/iff.py
import psycopg2
import psycopg2.extras
from datetime import datetime
import md5
from copy import deepcopy
cache = {}
def getFakePool(conn,stopbegin,stopend):
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cur.execute("""
SELECT
%s as privatecode,
1 as pointorder,
latitude,
longitude,
0 as distancefromstart
FROM quays
WHERE id = %s
UNION
SELECT
%s as privatecode,
2 as pointorder,
latitude,
longitude,
200 as distancefromstart
FROM quays
WHERE id = %s
""",[stopbegin,stopend]*2)
return cur.fetchall()
def getPoolIFF(conn,lineplanningnumber,stopcodebegin,stopcodeend):
print (lineplanningnumber,stopcodebegin,stopcodeend,'iff')
linePlanningNumberParts = lineplanningnumber.split(':')
if len(linePlanningNumberParts) > 3 or linePlanningNumberParts[1] in ['CNL','EN']:
getFakePool(conn,stopcodebegin,stopcodeend)
key = ':'.join([stopcodebegin,stopcodeend])
if key in cache:
print 'hit'
return deepcopy(cache[key])
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cur.execute("""
SELECT
NULL as privatecode,
p1.idx as pointorder,
cast(CAST(ST_Y(p1.the_geom) AS NUMERIC(8,5)) as text) AS latitude,
cast(CAST(ST_X(p1.the_geom) AS NUMERIC(7,5)) as text) AS longitude,
coalesce(SUM (st_distance(st_transform(p1.the_geom,28992),st_transform(p2.the_geom,28992))::integer)
OVER (partition by p1.stopbegin,p1.stopend order by p1.idx ROWS between UNBOUNDED PRECEDING and 1 PRECEDING),1) as distancefromstart
FROM poolpoints as p1 LEFT JOIN poolpoints as p2 ON (p1.stopbegin = p2.stopbegin AND p1.stopend = p2.stopend AND p1.idx +1 = p2.idx)
WHERE p1.stopbegin = %s and p1.stopend = %s
ORDER BY pointorder
""",[stopcodebegin,stopcodeend])
try:
cache[key] = cur.fetchall()
if len(cache[key]) < 2:
cache[key] = getFakePool(conn,stopcodebegin,stopcodeend)
else:
cache[key][0]['privatecode'] = stopcodebegin
cache[key][-1]['privatecode'] = stopcodebegin
return deepcopy(cache[key])
finally:
cur.close()
def calculateTimeDemandGroups(conn):
cur = conn.cursor('timdemgrps',cursor_factory=psycopg2.extras.RealDictCursor)
timdemgroup_ids = {}
timdemgroups = {}
journeyinfo = {}
cur.execute("""
SELECT concat_ws(':','IFF',serviceid,line_id,footnote,coalesce(variant,servicenumber)) as JOURNEY_id,
array_agg(cast(stoporder*10 as integer) order by stoporder) as stoporders,array_agg(toseconds(coalesce(arrivaltime,departuretime),0) order by stoporder) as
arrivaltimes,array_agg(toseconds(coalesce(departuretime,arrivaltime),0) order by stoporder) as departuretimes
FROM passtimes
GROUP BY JOURNEY_id
""")
for row in cur:
points = [(row['stoporders'][0],0,0)]
dep_time = row['departuretimes'][0]
for i in range(len(row['stoporders'][:-1])):
cur_arr_time = row['arrivaltimes'][i+1]
cur_dep_time = row['departuretimes'][i+1]
points.append((row['stoporders'][i+1],cur_arr_time-dep_time,cur_dep_time-cur_arr_time))
m = md5.new()
m.update(str(points))
timdemgrp = {'POINTS' : []}
for point in points:
point_dict = {'pointorder' : point[0],'totaldrivetime' : point[1], 'stopwaittime' : point[2]}
timdemgrp['POINTS'].append(point_dict)
if len(timdemgrp['POINTS']) == 0:
raise exception('TIMEDEMAND GROUP EMPTY?')
journeyinfo[row['journey_id']] = {'departuretime' : dep_time, 'timedemandgroupref' : m.hexdigest()}
timdemgrp['operator_id'] = m.hexdigest()
timdemgroups[m.hexdigest()] = timdemgrp
cur.close()
return (journeyinfo,timdemgroups)
def getStopPoints(conn):
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
userstops = {}
cur.execute("""
SELECT
'IFF:'||stopid as operator_id,
stopid as privatecode,
'IFF:'||station as stoparearef,
name,
NULL as town,
(trainchanges != 2) as isscheduled,
coalesce(latitude::text,ST_Y(the_geom)::NUMERIC(9,6)::text) AS latitude,
coalesce(longitude::text,ST_X(the_geom)::NUMERIC(8,6)::text) AS longitude,
coalesce(x,0) as rd_x,
coalesce(y,0) as rd_y,
platform as platformcode
FROM
(SELECT DISTINCT ON (station,platform) station,platform,stopid FROM (
SELECT station,platform,station||':'||coalesce(platform,'0') as stopid FROM passtimes
UNION
SELECT DISTINCT ON (station) station,NULL::text as platform,station||':0' as stopid from passtimes) as x) as stations
LEFT JOIN (select country,shortname as station,trainchanges,name,x,y,st_transform(st_setsrid(st_makepoint(x,y),28992),4326) as the_geom
from station) as station USING (station)
LEFT JOIN quays ON (stopid = quays.id)
;
""")
for row in cur.fetchall():
if row['rd_x'] is None:
print row
userstops[row['operator_id']] = row
cur.close()
return userstops
def getStopAreas(conn):
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
stopareas = {}
cur.execute("""
SELECT
'IFF:'||station as operator_id,
station as privatecode,
station as publiccode,
name,
NULL as town,
coalesce(latitude::text,ST_Y(the_geom)::NUMERIC(9,6)::text) AS latitude,
coalesce(longitude::text,ST_X(the_geom)::NUMERIC(8,6)::text) AS longitude,
CASE WHEN (country = 'GB') THEN 'Europe/London' ELSE 'Europe/Amsterdam' END as timezone
FROM
(SELECT DISTINCT ON (station) station FROM passtimes) as stations
LEFT JOIN (select country,shortname as station,trainchanges,name,x,y,st_transform(st_setsrid(st_makepoint(x,y),28992),4326) as the_geom from station) as station USING (station)
LEFT JOIN places ON (places.id = station)
""")
for row in cur.fetchall():
stopareas[row['operator_id']] = row
cur.close()
return stopareas
def getAvailabilityConditions(conn):
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
availabilityconditions = {}
cur.execute("""
SELECT
'IFF:'||versionnumber||':'||footnote as operator_id,
CONCAT (
CASE WHEN (monday > total / 10) THEN 1 ELSE NULL END,
CASE WHEN (tuesday > total / 10) THEN 2 ELSE NULL END,
CASE WHEN (wednesday > total / 10) THEN 3 ELSE NULL END,
CASE WHEN (thursday > total / 10) THEN 4 ELSE NULL END,
CASE WHEN (friday > total / 10) THEN 5 ELSE NULL END,
CASE WHEN (saturday > total / 10) THEN 6 ELSE NULL END,
CASE WHEN (sunday > total / 10) THEN 7 ELSE NULL END
) as dayflags,
fromdate,
todate,
weeks,
years,
'1' as versionref,
'IFF' as unitcode
FROM (
SELECT
footnote,
sum((extract(isodow from servicedate) = 1)::int4)::integer as monday,
sum((extract(isodow from servicedate) = 2)::int4)::integer as tuesday,
sum((extract(isodow from servicedate) = 3)::int4)::integer as wednesday,
sum((extract(isodow from servicedate) = 4)::int4)::integer as thursday,
sum((extract(isodow from servicedate) = 5)::int4)::integer as friday,
sum((extract(isodow from servicedate) = 6)::int4)::integer as saturday,
sum((extract(isodow from servicedate) = 7)::int4)::integer as sunday,
count(distinct servicedate) as total,
array_agg(extract(week from servicedate)::integer ORDER BY servicedate) as weeks,
array_agg(extract(year from servicedate)::integer ORDER BY servicedate) as years,
min(servicedate)::text as fromdate,
max(servicedate)::text as todate
FROM footnote
GROUP BY footnote) as x,delivery;
""")
for row in cur.fetchall():
signature = ''
seen = set()
seen_add = seen.add
fromDate = datetime.strptime(row['fromdate'],"%Y-%m-%d")
toDate = datetime.strptime(row['todate'],"%Y-%m-%d")
now = datetime.now()
if len(row['weeks']) > 5 or abs((now - fromDate).days) > 14 or abs((toDate - now).days) > 40:
signature = 'JD'+str(row['years'][-1])+'-'+str(row['weeks'][0])
else:
signature = 'WD'+'_'.join([ str(x) for x in row['weeks'] if x not in seen and not seen_add(x)])
signature = signature+'_'+row['dayflags']
row['name'] = signature
row['privatecode'] = signature
del(row['weeks'])
del(row['dayflags'])
del(row['years'])
availabilityconditions[row['operator_id']] = row
cur.execute("""
SELECT
'IFF:'||versionnumber||':'||footnote as availabilityconditionRef,
array_agg(servicedate::text) as validdates,
true as isavailable
FROM footnote,delivery
GROUP BY versionnumber,footnote
ORDER BY versionnumber,footnote
;
""")
for row in cur.fetchall():
availabilityconditions[row['availabilityconditionref']]['DAYS'] = row
cur.close()
return availabilityconditions
def getProductCategories(conn):
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
productcategories = {}
cur.execute("""
SELECT
'IFF:'||code as operator_id,
code as privatecode,
description as name
FROM trnsmode
WHERE code in (select distinct transmode from timetable_transport);
""")
for row in cur.fetchall():
productcategories[row['operator_id']] = row
cur.close()
return productcategories
def getNotices(conn):
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
notices = {}
cur.execute("""
SELECT
code as operator_id,
code as publiccode,
code as shortcode,
description as name,
processingcode
FROM trnsattr
WHERE code in (select distinct code from timetable_attribute);
""")
for row in cur.fetchall():
notices[row['operator_id']] = row
cur.close()
return notices
def getNoticeGroups(conn):
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
noticegroups = {}
cur.execute("""
SELECT
'IFF:'||attrs::text as operator_id,array_agg(attr) as noticerefs
FROM (SELECT DISTINCT ON (attrs,attr) attrs,unnest(attrs) as attr FROM timetable) as t
GROUP BY attrs;
""")
for row in cur.fetchall():
noticegroups[row['operator_id']] = row
cur.close()
return noticegroups
def getNoticeAssignments(conn):
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
noticeassignments = {}
cur.execute("""
SELECT DISTINCT ON (attrs)
'IFF:'||attrs::text as noticegroupref,
'IFF:'||attrs::text as operator_id,
attrs::text as name
FROM timetable
WHERE attrs is not null;
""")
for row in cur.fetchall():
noticeassignments[row['operator_id']] = row
cur.close()
return noticeassignments
def getDestinationDisplays(conn):
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
destinationdisplays = {}
cur.execute("""
SELECT DISTINCT ON (shortname)
shortname as privatecode,
'IFF:'||shortname as operator_id,
name,
name as shortname
FROM (
SELECT DISTINCT ON (serviceid,patterncode,line_id)
serviceid,servicenumber,station as shortname
FROM passtimes
ORDER BY serviceid ASC,patterncode ASC,line_id ASC,stoporder DESC) as x LEFT JOIN station USING (shortname);
""")
for row in cur.fetchall():
destinationdisplays[row['operator_id']] = row
cur.close()
return destinationdisplays
def clusterPatternsIntoRoute(conn,getPool):
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cur.execute("""
SELECT
line_id,array_agg(patterncode ORDER BY char_length(pattern) DESC,patterncode) as
patterncodes,array_agg(pattern ORDER BY char_length(pattern) DESC,patterncode) as patterns
FROM
(SELECT line_id,'IFF:'||line_id||':'||patterncode as patterncode,string_agg(station||':'||coalesce(platform,'0'),'>') as pattern
FROM (SELECT DISTINCT ON (line_id,patterncode,stoporder) * From passtimes order by line_id,patterncode,stoporder) as passtimes
GROUP BY line_id,patterncode) as y
GROUP BY line_id""")
rows = cur.fetchall()
patterncodeInRoute = {}
for row in rows:
if row['line_id'] not in patterncodeInRoute:
patterncodeInRoute[row['line_id']] = [ (row['patterns'][0],[row['patterncodes'][0]]) ]
for i in range(len(row['patterncodes'][1:])):
pattern = row['patterns'][i+1]
patterncode = row['patterncodes'][i+1]
route_found = False
for route in patterncodeInRoute[row['line_id']]:
if pattern in route[0]:
route[1].append(patterncode)
route_found = True
break
if not route_found:
patterncodeInRoute[row['line_id']].append((pattern,[patterncode]))
routes_result = {}
routeRefForPattern = {}
linecounter = 0
for line,routes in patterncodeInRoute.items():
linecounter += 1
print '%s / %s' % (linecounter,len(patterncodeInRoute))
for routes in routes:
result = {'POINTS' : []}
stops = routes[0].split('>')
for i in range(len(stops)-1):
stopbegin = stops[i]
stopend = stops[i+1]
if len(result['POINTS']) == 0:
order = 0
distance = 0
else:
order = result['POINTS'][-1]['pointorder']
distance = result['POINTS'][-1]['distancefromstart']
pool = getPool(conn,line,stopbegin,stopend)
if len(pool) == 0:
raise Exception('KV1: Pool empty')
if pool[0]['privatecode'] != stopbegin and len(result['POINTS']) == 0:
pointbegin = deepcopy(pool[0])
pointbegin['privatecode'] = stopbegin
order += 1
result['POINTS'].append(pointbegin)
if pool[-1]['privatecode'] != stopend:
pointend = deepcopy(pool[-1])
pointend['privatecode'] = stopend
pointend['pointorder'] += 1
pool.append(pointend)
for point in pool:
if len(result['POINTS']) > 0 and point['privatecode'] is not None and result['POINTS'][-1]['privatecode'] == point['privatecode']:
continue
point['pointorder'] += order
point['distancefromstart'] += distance
result['POINTS'].append(point)
m = md5.new()
if len(result['POINTS']) < 2:
raise Exception('Routepoints empty %s\n\n%s\n\n%s' % (line,stops,routes))
result['lineref'] = line
m.update(str(result))
result['operator_id'] = m.hexdigest()
routes_result[m.hexdigest()] = result
for patterncode in routes[1]:
routeRefForPattern[patterncode] = m.hexdigest()
cur.close()
return (routeRefForPattern,routes_result)
def getJourneyPatterns(routeRefForPattern,conn,routes):
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
journeypatterns = {}
cur.execute("""
SELECT
'IFF:'||line_id||':'||patterncode as operator_id,
NULL as routeref,
CASE WHEN (COALESCE(variant,servicenumber) != 0) THEN ((not COALESCE(variant,servicenumber)%2 = 1)::int4 + 1)
ELSE (stops[array_upper(stops,1)] < stops[array_lower(stops,1)])::int4 + 1 END as directiontype,
'IFF:'||stops[array_upper(stops,1)] as destinationdisplayref
FROM (
SELECT DISTINCT ON (line_id,patterncode) line_id,patterncode,servicenumber,variant,stops
FROM
(SELECT line_id,patterncode,array_agg(station ORDER BY stoporder) as stops FROM
(SELECT DISTINCT ON (line_id,patterncode,stoporder) * From passtimes order by line_id,patterncode,stoporder) as passtimes
GROUP BY line_id,patterncode) as x JOIN passtimes as p USING (line_id,patterncode)
ORDER BY line_id,patterncode,stoporder ASC) as y
""")
for row in cur.fetchall():
journeypatterns[row['operator_id']] = row
journeypatterns[row['operator_id']]['POINTS'] = []
row['routeref'] = routeRefForPattern[row['operator_id']]
cur.execute("""
SELECT DISTINCT ON (p1.line_id,p1.patterncode,p1.stoporder)
'IFF:'||p1.line_id||':'||p1.patterncode as journeypatternref,
p1.stoporder::integer*10 as pointorder,
NULL as privatecode,
NULL as operator_id,
'IFF:'||p1.station||':'||coalesce(p1.platform,'0') as pointref,
'IFF:'||p2.station||':'||coalesce(p2.platform,'0') as onwardpointref,
NULL as destinationdisplayref,
'IFF:'||p1.attrs::text as noticeassignmentRef,
NULL as administrativezoneref,
true as iswaitpoint,
0 as waittime,
NULL as requeststop,
coalesce(p1.foralighting,true) as foralighting,
coalesce(p1.forboarding,true) as forboarding,
0 as distancefromstartroute,
0 as fareunitspassed
FROM passtimes as p1 LEFT JOIN passtimes as p2 ON (p1.serviceid = p2.serviceid AND
(p1.servicenumber = 0 OR p1.servicenumber = p2.servicenumber OR p1.variant = p2.variant)AND
p1.stoporder +1 = p2.stoporder)
ORDER BY p1.line_id,p1.patterncode,p1.stoporder ASC
""")
distance = 0
patternref = None
for row in cur.fetchall():
if row['journeypatternref'] != patternref:
distance = 0
patternref = row['journeypatternref']
for point in routes[journeypatterns[row['journeypatternref']]['routeref']]['POINTS']:
if point['distancefromstart'] >= distance and point['privatecode'] is not None and 'IFF:'+point['privatecode'] == row['pointref']:
distance = point['distancefromstart']
row['distancefromstartroute'] = distance
break
if distance == 0 and int(row['pointorder']) > 30:
raise Exception('distancefromstartroute going wrong'+str(journeypatterns[row['journeypatternref']]['POINTS']))
row['distancefromstartroute'] = distance
journeypatterns[row['journeypatternref']]['POINTS'].append(row)
cur.close()
return journeypatterns
def getVersion(conn,filename):
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cur.execute("""
SELECT '1' as datasourceref,firstday as startdate, lastday as enddate, versionnumber as privatecode,description,%s as operator_id
FROM delivery LIMIT 1;""",[filename])
return cur.fetchone()
def getOperator(conn):
operators = {'THALYS' : {'url' : 'http://www.thalys.nl', 'language' : 'nl', 'phone' : '0900-9296'},
'DB' : {'url' : 'http://www.db.de' , 'language' : 'de', 'phone' : '+491806996633'},
'KEO' : {'url' : 'http://www.keolis.de', 'language' : 'de', 'phone' : '+4918029273727'},
'SYN' : {'url' : 'http://www.syntus.nl', 'language' : 'nl', 'phone' : '0314350111'},
'GVB' : {'url' : 'http://www.gvb.nl', 'language' : 'nl', 'phone' : '0900-8011'},
'NMBS' : {'url' : 'http://www.nmbs.be', 'language' : 'nl', 'phone' : '+3225282828'},
'GVU' : {'url' : 'http://www.gvu.nl', 'language' : 'nl', 'phone' : '0900-8998959'},
'UOV' : {'url' : 'http://www.u-ov.info', 'language' : 'nl', 'phone' : '0900-5252241'},
'LCB' : {'url' : 'http://www.locon-benelux.com', 'language' : 'nl', 'phone' : '038-4606779'},
'EUROSTAR': {'url' : 'http://www.eurostar.co.uk', 'language' : 'nl', 'phone' : '0900-9296'},
'BRENG' : {'url' : 'http://www.breng.nl', 'language' : 'nl', 'phone' : '026-2142140'},
'VEO' : {'url' : 'http://www.veolia.nl', 'language' : 'nl', 'phone' : '088-0761111'},
'VEOLIA' : {'url' : 'http://www.veolia.nl', 'language' : 'nl', 'phone' : '088-0761111'},
'QBUZZ' : {'url' : 'http://www.qbuzz.nl', 'language' : 'nl', 'phone' : '0900-7289965'},
'EETC' : {'url' : 'http://www.eetc.nl', 'language' : 'nl', 'phone' : '015-2133636'},
'VALLEI' : {'url' : 'http://www.valleilijn.nl', 'language' : 'nl', 'phone' : '0900-2666399'},
'HISPEED' : {'url' : 'http://www.nshispeed.nl', 'language' : 'nl', 'phone' : '0900-9296'},
'NSI' : {'url' : 'http://www.nsinternational.nl', 'language' : 'nl', 'phone' : '0900-9296'},
'SNCF' : {'url' : 'http://www.sncf.fr', 'language' : 'fr', 'phone' : '+33890640650'},
'CONNEXXI': {'url' : 'http://www.connexxion.nl', 'language' : 'nl', 'phone' : '0900-2666399'},
'RNET' : {'url' : 'http://www.connexxion.nl', 'language' : 'nl', 'phone' : '0900-2666399'},
'NS' : {'url' : 'http://www.ns.nl', 'language' : 'nl', 'phone' : '0900-2021163'},
'ARRIVA' : {'url' : 'http://www.arriva.nl', 'language' : 'nl', 'phone' : '0900-2022022'},
'NOORD' : {'url' : 'http://www.arriva.nl', 'language' : 'nl', 'phone' : '0900-2022022'}
}
result = {}
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cur.execute("""
select upper(code) as privatecode,
'IFF:'||upper(code) as operator_id,
name,
'Europe/Amsterdam' as timezone
FROM company where company in (select distinct companynumber from timetable_service);""")
rows = cur.fetchall()
cur.close()
for row in rows:
result[row['operator_id']] = operators[row['privatecode']]
result[row['operator_id']].update(row)
return result
def getJourneys(timedemandGroupRefForJourney,conn):
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cur.execute("""
SELECT DISTINCT ON (serviceid,line_id,patterncode,servicenumber)
concat_ws(':','IFF',transmode,coalesce(variant,servicenumber)) as privatecode,
concat_ws(':','IFF',serviceid,line_id,v.footnote,coalesce(variant,servicenumber)) as operator_id,
concat_ws(':', 'IFF',versionnumber,v.footnote) as availabilityconditionRef,
concat_ws(':','IFF',line_id,patterncode) as journeypatternref,
NULL as timedemandgroupref,
'IFF:'||transmode as productCategoryRef,
NULL as noticeassignmentRef,
NULL as departuretime,
'IFF:'||serviceid as blockref,
coalesce(variant,servicenumber)::integer as name,
NULL as lowfloor,
NULL as hasLiftOrRamp,
NULL as haswifi,
CASE WHEN transmode in ('NSS','NSB','B','BNS','X','U','Y') THEN false
WHEN (ARRAY['GEFI']::varchar[] <@ attrs) THEN false
WHEN (ARRAY['FIET']::varchar[] <@ attrs) THEN true
WHEN transmode in('IC','SPR','S','ST','INT','ES','THA','TGV','ICD') THEN true
ELSE NULL END as bicycleAllowed,
CASE WHEN (ARRAY['RESV']::varchar[] <@ attrs) THEN true ELSE NULL END as onDemand
FROM PASSTIMES LEFT JOIN timetable_validity as v USING (serviceid)
LEFT JOIN company ON (companynumber = company.company)
,delivery
ORDER BY serviceid,line_id,patterncode,servicenumber,stoporder
""")
journeys = {}
for row in cur.fetchall():
row.update(timedemandGroupRefForJourney[row['operator_id']])
journeys[row['operator_id']] = row
cur.close()
return journeys
def getTripTransfers(conn):
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cur.execute("""
SELECT DISTINCT ON (journeyref,pointref,onwardjourneyref,onwardpointref)
concat_ws(':','IFF',p.serviceid,p.line_id,p.footnote,coalesce(p.variant,p.servicenumber)) as journeyref,
'IFF:'||p.station||':'||coalesce(p.platform,'0') as pointref,
concat_ws(':','IFF',onward.serviceid,onward.line_id,onward.footnote,coalesce(onward.variant,onward.servicenumber)) as onwardjourneyref,
'IFF:'||onward.station||':'||coalesce(onward.platform,'0') as onwardpointref,
possiblechange as transfer_type
FROM
changes as c,passtimes as p, passtimes as onward
WHERE
c.fromservice = p.serviceid AND
c.station = p.station AND
c.toservice = onward.serviceid AND
c.station = onward.station AND
coalesce(p.foralighting,true) = true AND
coalesce(onward.forboarding,true) = true
ORDER BY journeyref,pointref,onwardjourneyref,onwardpointref,transfer_type""")
transfers = {}
for row in cur.fetchall():
row['operator_id'] = '/'.join([row['journeyref'],row['onwardjourneyref'],row['pointref'],row['onwardpointref']])
transfers[row['operator_id']] = row
cur.close()
return transfers
def getLines(conn):
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cur.execute("""
SELECT DISTINCT ON (operator_id)
operator_id,privatecode,operatorref,publiccode,name,transportmode,monitored FROM
(
(SELECT DISTINCT ON (line_id)
line_id as operator_id,
line_id as privatecode,
'IFF:'||upper(c.code) as operatorref,
description as publiccode,
CASE WHEN (servicename is not null) THEN servicename||' '||start.name||' <-> '||dest.name
WHEN (route(servicenumber,variant) is null) THEN start.name||' <-> '||dest.name
ELSE start.name||' <-> '||dest.name||' '||transmode||route(servicenumber,variant) END AS name,
CASE WHEN (transmode in ('NSS','NSB','B','BNS','X','U','Y')) THEN 'BUS'
WHEN (transmode = 'NSM') THEN 'METRO'
WHEN (transmode = 'NST') THEN 'TRAM'
ELSE 'TRAIN' END as transportmode,
CASE WHEN (transmode in ('NSS','NSB','B','BNS','X','U','Y','NSM','NST')) THEN false
ELSE true END as monitored,
0 as priority
FROM
(SELECT line_id,patterncode,count(servicedate) as patterncount FROM passtimes JOIN footnote USING (footnote) GROUP BY line_id,patterncode) as
patterns
JOIN (SELECT DISTINCT ON (line_id,patterncode)
line_id,companynumber,serviceid,footnote,transmode,servicenumber,variant,patterncode,station as headsign,servicename FROM passtimes
WHERE (coalesce(servicenumber,variant) = 0 or coalesce(servicenumber,variant) is null or coalesce(servicenumber,variant) % 2 = 1)
ORDER BY line_id,patterncode,idx DESC) as headsigns USING
(line_id,patterncode)
JOIN (SELECT DISTINCT ON (line_id,patterncode)
line_id,patterncode,station as startplace FROM passtimes
WHERE (coalesce(servicenumber,variant) = 0 or coalesce(servicenumber,variant) is null or coalesce(servicenumber,variant) % 2 = 1)
ORDER BY line_id,patterncode,idx ASC) as startplace USING (line_id,patterncode)
LEFT JOIN station AS dest ON (dest.shortname = headsign)
LEFT JOIN station AS start ON (start.shortname = startplace)
LEFT JOIN company AS c ON (c.company = companynumber)
LEFT JOIN trnsmode as trnsmode ON (trnsmode.code = transmode)
ORDER BY line_id,patterncount DESC)
UNION
(SELECT DISTINCT ON (line_id)
line_id as operator_id,
line_id as privatecode,
'IFF:'||upper(c.code) as operatorref,
description as publiccode,
CASE WHEN (servicename is not null) THEN servicename||' '||start.name||' <-> '||dest.name
WHEN (route(servicenumber,variant) is null) THEN description||' '||least(start.name,dest.name)||' <-> '||greatest(start.name,dest.name)
ELSE start.name||' <-> '||dest.name||' '||transmode||route(servicenumber,variant) END AS name,
CASE WHEN (transmode in ('NSS','NSB','B','BNS','X','U','Y')) THEN 'BUS'
WHEN (transmode = 'NSM') THEN 'METRO'
WHEN (transmode = 'NST') THEN 'TRAM'
ELSE 'TRAIN' END as transportmode,
CASE WHEN (transmode in ('NSS','NSB','B','BNS','X','U','Y','NSM','NST')) THEN false
ELSE true END as monitored,
1 as priority
FROM
(SELECT line_id,patterncode,count(servicedate) as patterncount FROM passtimes JOIN footnote USING (footnote) GROUP BY line_id,patterncode) as
patterns
JOIN (SELECT DISTINCT ON (line_id,patterncode)
line_id,companynumber,serviceid,footnote,transmode,servicenumber,variant,patterncode,station as headsign,servicename FROM passtimes
WHERE (coalesce(servicenumber,variant) = 0 or coalesce(servicenumber,variant) is null or coalesce(servicenumber,variant) % 2 = 0)
ORDER BY line_id,patterncode,idx DESC) as headsigns USING (line_id,patterncode)
JOIN (SELECT DISTINCT ON (line_id,patterncode)
line_id,patterncode,station as startplace FROM passtimes
WHERE (coalesce(servicenumber,variant) = 0 or coalesce(servicenumber,variant) is null or coalesce(servicenumber,variant) % 2 = 0)
ORDER BY line_id,patterncode,idx ASC) as startplace USING (line_id,patterncode)
LEFT JOIN station AS dest ON (dest.shortname = headsign)
LEFT JOIN station AS start ON (start.shortname = startplace)
LEFT JOIN company AS c ON (c.company = companynumber)
LEFT JOIN trnsmode as trnsmode ON (trnsmode.code = transmode)
ORDER BY line_id,patterncount DESC)) AS Y
ORDER BY operator_id,priority
""")
lines = {}
for row in cur.fetchall():
lines[row['operator_id']] = row
cur.close()
return lines
| StarcoderdataPython |
6640599 | <reponame>jayconrod/rules_go<filename>go/private/binary.bzl<gh_stars>0
# Copyright 2014 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
load("@io_bazel_rules_go//go/private:common.bzl", "get_go_toolchain", "go_filetype")
load("@io_bazel_rules_go//go/private:library.bzl", "emit_library_actions")
def _go_binary_impl(ctx):
"""go_binary_impl emits actions for compiling and linking a go executable."""
lib_result = emit_library_actions(ctx,
sources = depset(ctx.files.srcs),
deps = ctx.attr.deps,
cgo_object = None,
library = ctx.attr.library,
)
emit_go_link_action(
ctx,
transitive_go_libraries=lib_result.transitive_go_libraries,
transitive_go_library_paths=lib_result.transitive_go_library_paths,
cgo_deps=lib_result.transitive_cgo_deps,
libs=lib_result.files,
executable=ctx.outputs.executable,
gc_linkopts=gc_linkopts(ctx),
x_defs=ctx.attr.x_defs)
return struct(
files = depset([ctx.outputs.executable]),
runfiles = lib_result.runfiles,
cgo_object = lib_result.cgo_object,
)
go_binary = rule(
_go_binary_impl,
attrs = {
"data": attr.label_list(
allow_files = True,
cfg = "data",
),
"srcs": attr.label_list(allow_files = go_filetype),
"deps": attr.label_list(
providers = [
"transitive_go_library_paths",
"transitive_go_libraries",
"transitive_cgo_deps",
],
),
"importpath": attr.string(),
"library": attr.label(
providers = [
"direct_deps",
"go_sources",
"asm_sources",
"cgo_object",
"gc_goopts",
],
),
"gc_goopts": attr.string_list(),
"gc_linkopts": attr.string_list(),
"linkstamp": attr.string(),
"x_defs": attr.string_dict(),
#TODO(toolchains): Remove _toolchain attribute when real toolchains arrive
"_go_toolchain": attr.label(default = Label("@io_bazel_rules_go_toolchain//:go_toolchain")),
"_go_prefix": attr.label(default = Label(
"//:go_prefix",
relative_to_caller_repository = True,
)),
},
executable = True,
fragments = ["cpp"],
)
def c_linker_options(ctx, blacklist=[]):
"""Extracts flags to pass to $(CC) on link from the current context
Args:
ctx: the current context
blacklist: Any flags starts with any of these prefixes are filtered out from
the return value.
Returns:
A list of command line flags
"""
cpp = ctx.fragments.cpp
features = ctx.features
options = cpp.compiler_options(features)
options += cpp.unfiltered_compiler_options(features)
options += cpp.link_options
options += cpp.mostly_static_link_options(ctx.features, False)
filtered = []
for opt in options:
if any([opt.startswith(prefix) for prefix in blacklist]):
continue
filtered.append(opt)
return filtered
def gc_linkopts(ctx):
gc_linkopts = [ctx.expand_make_variables("gc_linkopts", f, {})
for f in ctx.attr.gc_linkopts]
return gc_linkopts
def _extract_extldflags(gc_linkopts, extldflags):
"""Extracts -extldflags from gc_linkopts and combines them into a single list.
Args:
gc_linkopts: a list of flags passed in through the gc_linkopts attributes.
ctx.expand_make_variables should have already been applied.
extldflags: a list of flags to be passed to the external linker.
Return:
A tuple containing the filtered gc_linkopts with external flags removed,
and a combined list of external flags.
"""
filtered_gc_linkopts = []
is_extldflags = False
for opt in gc_linkopts:
if is_extldflags:
is_extldflags = False
extldflags += [opt]
elif opt == "-extldflags":
is_extldflags = True
else:
filtered_gc_linkopts += [opt]
return filtered_gc_linkopts, extldflags
def emit_go_link_action(ctx, transitive_go_library_paths, transitive_go_libraries, cgo_deps, libs,
executable, gc_linkopts, x_defs):
"""Sets up a symlink tree to libraries to link together."""
go_toolchain = get_go_toolchain(ctx)
config_strip = len(ctx.configuration.bin_dir.path) + 1
pkg_depth = executable.dirname[config_strip:].count('/') + 1
ld = "%s" % ctx.fragments.cpp.compiler_executable
extldflags = c_linker_options(ctx) + [
"-Wl,-rpath,$ORIGIN/" + ("../" * pkg_depth),
]
for d in cgo_deps:
if d.basename.endswith('.so'):
short_dir = d.dirname[len(d.root.path):]
extldflags += ["-Wl,-rpath,$ORIGIN/" + ("../" * pkg_depth) + short_dir]
gc_linkopts, extldflags = _extract_extldflags(gc_linkopts, extldflags)
link_opts = [
"-L", "."
]
for path in transitive_go_library_paths:
link_opts += ["-L", path]
link_opts += [
"-o", executable.path,
] + gc_linkopts
# Process x_defs, either adding them directly to linker options, or
# saving them to process through stamping support.
stamp_x_defs = {}
for k, v in x_defs.items():
if v.startswith("{") and v.endswith("}"):
stamp_x_defs[k] = v[1:-1]
else:
link_opts += ["-X", "%s=%s" % (k, v)]
link_opts += go_toolchain.link_flags + [
"-extld", ld,
"-extldflags", " ".join(extldflags),
] + [lib.path for lib in libs]
link_args = [go_toolchain.go.path]
# Stamping support
stamp_inputs = []
if stamp_x_defs or ctx.attr.linkstamp:
stamp_inputs = [ctx.info_file, ctx.version_file]
for f in stamp_inputs:
link_args += ["-stamp", f.path]
for k,v in stamp_x_defs.items():
link_args += ["-X", "%s=%s" % (k, v)]
# linkstamp option support: read workspace status files,
# converting "KEY value" lines to "-X $linkstamp.KEY=value" arguments
# to the go linker.
if ctx.attr.linkstamp:
link_args += ["-linkstamp", ctx.attr.linkstamp]
link_args += ["--"] + link_opts
ctx.action(
inputs = list(transitive_go_libraries + [lib] + cgo_deps +
go_toolchain.tools + go_toolchain.crosstool + stamp_inputs),
outputs = [executable],
mnemonic = "GoLink",
executable = go_toolchain.link,
arguments = link_args,
env = go_toolchain.env,
) | StarcoderdataPython |
11300487 | <filename>blog/app/views.py
# coding=utf-8
from flask import Flask, url_for, render_template, request, redirect
import models
app = Flask(__name__)
@app.route('/')
@app.route('/<id>')
def hello_world(id=None):
full = request.args.get('full', False)
if request.method == 'GET':
pass
elif resquest.method == 'POST':
pass
user = models.User.get_user('toot')
posts = models.Post.get_posts(user['username'])
for post in posts:
commentaires = models.Commentaire.get_commentaires(post['id'])
post['commentaires'] = commentaires
post['nb_com'] = len(commentaires)
return render_template('index.html',
posts = posts,
titre='mon titre',
full=full)
@app.route('/create_post', methods=['GET', 'POST'])
def create_post():
champs = [
'titre',
'contenu'
]
if request.method == 'GET':
return render_template('post.html', champs=champs, form={}, errors={})
else:
form = request.form
result = validate(form, champs)
if result['valid']:
user = models.User.get_user('toot')
models.Post.insert('toot', result['form']['titre'], result['form']['contenu'])
return redirect('/')
else:
return render_template('post.html',
champs=champs,
form=result['form'],
errors=result['errors'])
def validate(form, champs):
result = {'valid': True, 'form': form, 'errors': {}}
for champ in champs:
result['valid'] = result['valid'] and champ_requis(form, champ, errors=result['errors'])
return result
def champ_requis(form, champ, errors):
if form.get(champ, None) == '':
errors[champ] = 'le champ {} est requis'.format(champ)
return False
else:
return True
| StarcoderdataPython |
12852825 | from typing import *
import collections
import copy
import hashlib
import math
import numpy as np
from pathlib import Path
import random
import re
from tqdm import tqdm
import traceback
import sys
from seutil import LoggingUtils, IOUtils, BashUtils
from seutil.project import Project
from roosterize.data.CoqDocument import CoqDocument
from roosterize.FilesManager import FilesManager
from roosterize.data.Definition import Definition
from roosterize.data.Lemma import Lemma
from roosterize.data.LemmaBackendSexpTransformers import LemmaBackendSexpTransformers
from roosterize.data.LemmaForeendSexpTransformers import LemmaForeendSexpTransformers
from roosterize.Environment import Environment
from roosterize.Macros import Macros
from roosterize.parser.CoqParser import CoqParser
from roosterize.parser.ParserUtils import ParserUtils
from roosterize.parser.SexpAnalyzer import SexpAnalyzer, SexpInfo
from roosterize.sexp import *
from roosterize.Utils import Utils
class DataMiner:
logger = LoggingUtils.get_logger(__name__, LoggingUtils.DEBUG)
from roosterize.Debug import Debug
if Debug.is_debug: logger.setLevel(LoggingUtils.DEBUG)
Project.set_downloads_dir(Macros.downloads_dir)
TASK_COQ_DOCUMENTS = FilesManager.COQ_DOCUMENTS # "coq-documents"
TASK_DATA_INDEXES = FilesManager.DATA_INDEXES # "data-indexes"
TASK_DEFINITIONS = FilesManager.DEFINITIONS # "definitions"
TASK_INSTALL_COQ_PROJECTS = "install-coq-projects"
TASK_LEMMA = FilesManager.LEMMAS # "lemmas"
TASK_LEMMA_BACKEND_SEXP_TRANSFORMATIONS = FilesManager.LEMMAS_BACKEND_SEXP_TRANSFORMATIONS # "lemmas-bsexp-transformations"
TASK_LEMMA_FILTERED = FilesManager.LEMMAS_FILTERED # "lemmas-filtered"
TASK_LEMMA_FOREEND_SEXP_TRANSFORMATIONS = FilesManager.LEMMAS_FOREEND_SEXP_TRANSFORMATIONS # "lemmas-fsexp-transformations"
dataset_dir = Macros.project_dir.parent / "math-comp-corpus"
@classmethod
def collect_data(cls, **options) -> NoReturn:
data_mgr = FilesManager(cls.dataset_dir)
task = options["task"]
projects_path = Path(options.get("corpus", cls.dataset_dir / "projects-standalone-8.10.yml"))
projects: List[Project] = IOUtils.dejsonfy(IOUtils.load(projects_path, "json"), Project)
if task == cls.TASK_COQ_DOCUMENTS:
files = Utils.get_option_as_list(options, "files", None)
is_verifying_tokenizer = Utils.get_option_as_boolean(options, "verify-tokenizer")
cls.collect_coq_documents_projects(data_mgr, projects, files, is_verifying_tokenizer)
elif task == cls.TASK_DATA_INDEXES:
cls.collect_data_indexes(data_mgr, projects)
elif task == cls.TASK_DEFINITIONS:
cls.collect_definitions(data_mgr)
elif task == cls.TASK_INSTALL_COQ_PROJECTS:
cls.install_coq_projects(projects)
elif task == cls.TASK_LEMMA:
files = Utils.get_option_as_list(options, "files", None)
cls.collect_lemmas(data_mgr, projects, files)
elif task == cls.TASK_LEMMA_BACKEND_SEXP_TRANSFORMATIONS:
cls.collect_lemmas_backend_sexp_transformations(data_mgr)
elif task == cls.TASK_LEMMA_FILTERED:
cls.filter_lemmas(data_mgr)
elif task == cls.TASK_LEMMA_FOREEND_SEXP_TRANSFORMATIONS:
cls.collect_lemmas_foreend_sexp_transformations(data_mgr)
else:
LoggingUtils.log_and_raise(cls.logger, f"Unknown task {task}", ValueError)
# end if
return
@classmethod
def collect_coq_documents_projects(cls,
data_mgr: FilesManager,
projects: List[Project],
files: List[str] = None,
is_verifying_tokenizer: bool = False,
) -> NoReturn:
# Prepare the used directories (coq-documents, raw-files, original-files)
for rel_path in [
[FilesManager.COQ_DOCUMENTS],
[FilesManager.RAW_FILES],
[FilesManager.ORIGINAL_FILES],
]:
data_mgr.clean_path(rel_path)
data_mgr.resolve(rel_path).mkdir(parents=True)
# end for
coq_documents: List[CoqDocument] = list()
names_projects = {p.full_name: p for p in projects}
for i, project in enumerate(projects):
try:
cls.logger.info(f"Project {i + 1}/{len(projects)}: {project.full_name}")
coq_documents_project = cls.collect_coq_documents_project(data_mgr, project, names_projects=names_projects, files=files, is_verifying_tokenizer=is_verifying_tokenizer)
except KeyboardInterrupt:
raise
except:
cls.logger.warning(f"Error while processing project {project.full_name}: {traceback.format_exc()}")
continue
else:
coq_documents.extend(coq_documents_project)
# end try
# end for
# Save datasets
data_mgr.dump_data([FilesManager.COQ_DOCUMENTS, FilesManager.COQ_DOCUMENTS], coq_documents, IOUtils.Format.json, is_batched=True)
return
@classmethod
def load_coq_documents(cls, data_mgr: FilesManager) -> List[CoqDocument]:
return data_mgr.load_data([FilesManager.COQ_DOCUMENTS, FilesManager.COQ_DOCUMENTS], IOUtils.Format.json, is_batched=True, clz=CoqDocument)
@classmethod
def collect_coq_documents_project(cls,
data_mgr: FilesManager,
project: Project,
names_projects: Dict[str, Project],
files: List[str] = None,
is_verifying_tokenizer: bool = False,
) -> List[CoqDocument]:
coq_documents: List[CoqDocument] = list()
# Clone and checkout repo
project.clone()
project.checkout(project.data["sha"], is_forced=True)
# Build the project
cls.install_coq_project(project, names_projects)
# For each file, parse code to tokens
with IOUtils.cd(project.checkout_dir):
coq_files: List[str] = BashUtils.run(f"find -name '*.v' -type f").stdout.split("\n")[:-1]
if files is not None:
coq_files = [f for f in coq_files if f[2:] in files] # [2:] is to remove the ./
# end if
re_ignore_path = re.compile(project.data["ignore_path_regex"]) if "ignore_path_regex" in project.data else None
for i, coq_file in enumerate(coq_files):
try:
coq_file = coq_file[2:]
cls.logger.debug(f"File {i + 1}/{len(coq_files)}: {coq_file}")
# Check if file is ignored
if re_ignore_path is not None and re_ignore_path.fullmatch(coq_file):
cls.logger.info(f"Ignoring file {coq_file}")
continue
# end if
# Read file
with open(coq_file, "r", newline="") as f:
source_code = f.read()
# end with
# Get unicode offsets
unicode_offsets = ParserUtils.get_unicode_offsets(source_code)
# Save original file to original_files
data_mgr.dump_data([FilesManager.ORIGINAL_FILES,project.full_name, coq_file], source_code, IOUtils.Format.txt)
# Call SerAPI
serapi_options = project.data.get("serapi_options", "")
ast_sexp_str: str = BashUtils.run(f"sercomp {serapi_options} --mode=sexp -- {coq_file}", expected_return_code=0).stdout
tok_sexp_str: str = BashUtils.run(f"sertok {serapi_options} -- {coq_file}", expected_return_code=0).stdout
# Save ast sexp to dataset (.ast.sexp)
data_mgr.dump_data([FilesManager.RAW_FILES,project.full_name, coq_file[:-2] + ".ast.sexp"], ast_sexp_str, IOUtils.Format.txt)
# Save tok sexp to dataset (.tok.sexp)
data_mgr.dump_data([FilesManager.RAW_FILES, project.full_name, coq_file[:-2] + ".tok.sexp"], tok_sexp_str, IOUtils.Format.txt)
# Parse ast sexp
ast_sexp_list: List[SexpNode] = SexpParser.parse_list(ast_sexp_str)
tok_sexp_list: List[SexpNode] = SexpParser.parse_list(tok_sexp_str)
# Verify the tokenizer if requested
if is_verifying_tokenizer:
if not cls.verify_tokenizer(tok_sexp_list, source_code, unicode_offsets):
LoggingUtils.log_and_raise(cls.logger, "Tokenized content doesn't match original file!", Exception)
# end if
# end if
# Parse the document
coq_document = CoqParser.parse_document(source_code, ast_sexp_list, tok_sexp_list, unicode_offsets=unicode_offsets)
# Save the parsed document (printed format) to raw_files
data_mgr.dump_data([FilesManager.RAW_FILES, project.full_name, coq_file], coq_document.str_with_space(), IOUtils.Format.txt)
# Set meta data
coq_document.file_name = coq_file
coq_document.project_name = project.full_name
coq_document.revision = project.revision
coq_documents.append(coq_document)
except KeyboardInterrupt:
cls.logger.warning("Keyboard interrupt!")
raise
except:
cls.logger.warning(f"File {coq_file} failed! Exception was: {traceback.format_exc()}")
continue
# end try
# end for
# end with
return coq_documents
@classmethod
def verify_tokenizer(cls, tok_sexp_list: List[SexpNode], source_code: str, unicode_offsets: List[int]) -> bool:
sertok_sentences = SexpAnalyzer.analyze_sertok_sentences(tok_sexp_list, unicode_offsets)
vernac_sentences = CoqParser.parse_sertok_sentences(sertok_sentences, source_code)
code_i = 0
has_error: bool = False
for sent_i, sentence in enumerate(vernac_sentences):
for token_i, token in enumerate(sentence.tokens):
# Check space/comment
if token.beg_charno != code_i:
if not ParserUtils.is_ws_or_comment(source_code[code_i:token.beg_charno]):
cls.logger.error(f"Unresolved characters at charno {code_i} to {token.beg_charno}; next expect token {token.content} beginning at charno {token.beg_charno} (lineno {token.lineno}); file content {source_code[code_i:token.beg_charno]};")
cls.logger.error(f"assotiated sexp: \n{tok_sexp_list[sent_i][1][token_i].pretty_format()}")
has_error = True
# end if
# end if
# Check token
code_i = token.beg_charno
if token.content != source_code[code_i:token.end_charno]:
cls.logger.error(f"Mismatch token at charno {code_i} to {token.end_charno}; expect token {token.content} beginning at charno {token.beg_charno} (lineno {token.lineno}); file content {source_code[code_i:token.end_charno]};")
cls.logger.error(f"assotiated sexp: \n{tok_sexp_list[sent_i][1][token_i].pretty_format()}")
has_error = True
# end if
code_i = token.end_charno
# end for, for
# Check space/comment at end of file
if code_i != len(source_code):
if not ParserUtils.is_ws_or_comment(source_code[code_i:len(source_code)]):
cls.logger.error(f"Unresolved characters at charno {code_i} to {len(source_code)} (end of file); file content {source_code[code_i:len(source_code)]}")
has_error = True
# end if
# end if
return not has_error
@classmethod
def install_coq_projects(cls, projects: List[Project]) -> None:
names_projects = {p.full_name: p for p in projects}
for i, p in enumerate(projects):
cls.logger.info(f"Installing {p.full_name} ({i}/{len(projects)})")
cls.install_coq_project(p, names_projects)
# end for
return
@classmethod
def install_coq_project(cls, project: Project, names_projects: Dict[str, Project]) -> None:
"""
:requires: the project is cloned and checked-out to the desired version.
"""
if not project.is_cloned:
project.clone()
project.checkout(project.data["sha"], is_forced=True)
# end if
# Check if the project is already compiled
confirmation_file = "lpc-installed.txt"
confirmation_content = project.revision + " " + BashUtils.run("opam list coq -s", expected_return_code=0).stdout.strip()
if (project.checkout_dir/confirmation_file).is_file() and IOUtils.load(project.checkout_dir/confirmation_file, "txt") == confirmation_content:
cls.logger.debug(f"Project {project.full_name} already installed")
return
# end if
project.clean()
# Install dependencies
for dependency in project.data.get("dependencies", []):
dependency_project = names_projects.get(dependency)
if dependency_project is None: raise Exception(f"Cannot find dependency {dependency}")
cls.logger.info(f"For Project {project.full_name}, installing dependency {dependency}")
cls.install_coq_project(dependency_project, names_projects)
# end for
if "build_cmd" not in project.data: raise Exception(f"Project {project.full_name} does not have build_cmd")
if "install_cmd" not in project.data: raise Exception(f"Project {project.full_name} does not have install_cmd")
with IOUtils.cd(project.checkout_dir):
# Build
cls.logger.info(f"Project {project.full_name}: Building with {project.data['build_cmd']}")
r = BashUtils.run(project.data["build_cmd"])
if r.return_code != 0:
raise Exception(f"Compilation failed! Return code is {r.return_code}! stdout:\n{r.stdout}\n; stderr:\n{r.stderr}")
else:
cls.logger.debug(f"Compilation finished. Return code is {r.return_code}. stdout:\n{r.stdout}\n; stderr:\n{r.stderr}")
# end if
# Install
cls.logger.info(f"Project {project.full_name}: Installing with {project.data['install_cmd']}")
r = BashUtils.run(project.data["install_cmd"])
if r.return_code != 0:
raise Exception(f"Installation failed! Return code is {r.return_code}! stdout:\n{r.stdout}\n; stderr:\n{r.stderr}")
else:
cls.logger.debug(f"Installation finished. Return code is {r.return_code}. stdout:\n{r.stdout}\n; stderr:\n{r.stderr}")
# end if
IOUtils.dump(project.checkout_dir / confirmation_file, confirmation_content, "txt")
# end with
return
@classmethod
def collect_data_indexes(cls, data_mgr: FilesManager, projects: List[Project]) -> NoReturn:
"""
Split the dataset and record the data indexes for {t1, t2, t3, lo, ta, allgroup} * {train, val, test, all} dataset parts.
"""
data_mgr.clean_path([FilesManager.DATA_INDEXES])
data_mgr.resolve([FilesManager.DATA_INDEXES]).mkdir(parents=True)
# (Random) Split by train/val/test
cls.logger.info(f"Splitting regular dataset info train/val/test sets with ratio of {Macros.DS_TRAIN_RATIO}/{Macros.DS_VAL_RATIO}/{Macros.DS_TEST_RATIO}")
cls.logger.info(f"Splitting leave-out dataset info train/val/test sets with ratio of {Macros.DS_LO_TRAIN_RATIO}/{Macros.DS_LO_VAL_RATIO}/{Macros.DS_LO_TEST_RATIO}")
# Load and sort coq-documents data
coq_documents: List[CoqDocument] = cls.load_coq_documents(data_mgr)
coq_documents.sort(key=lambda d: d.get_data_index())
cls.logger.info(f"Total dataset #doc = {len(coq_documents)}")
if len(coq_documents) < 10:
cls.logger.warning(f"Dataset is probably too small: {len(coq_documents)}")
# end if
trainevals_data_indexes: Dict[str, Set[str]] = collections.defaultdict(set)
# Split data for each project, using the same random seed salted with the project name
for project in projects:
documents_this_project: List[CoqDocument] = sorted([d for d in coq_documents if d.project_name == project.full_name])
hasher = hashlib.sha256()
hasher.update(str.encode(project.full_name))
hasher.update(str.encode(str(Environment.random_seed)))
salted_seed = int.from_bytes(hasher.digest(), "big")
random.seed(salted_seed)
random.shuffle(documents_this_project)
if project.data["group"] in [Macros.DS_GROUP_T1, Macros.DS_GROUP_T2, Macros.DS_GROUP_T3]:
train_ratio, val_ratio, test_ratio = Macros.DS_TRAIN_RATIO, Macros.DS_VAL_RATIO, Macros.DS_TEST_RATIO
elif project.data["group"] in [Macros.DS_GROUP_LO]:
train_ratio, val_ratio, test_ratio = Macros.DS_LO_TRAIN_RATIO, Macros.DS_LO_VAL_RATIO, Macros.DS_LO_TEST_RATIO
else:
LoggingUtils.log_and_raise(cls.logger, f"Invalid group name {project.data['group']} for {project.full_name}", Exception)
# end if
train_val_split_point = int(math.ceil(train_ratio * len(documents_this_project)))
val_test_split_point = int(math.ceil((train_ratio + val_ratio) * len(documents_this_project)))
trainevals_data_indexes[Macros.DS_TRAIN].update(set([d.get_data_index() for d in documents_this_project[:train_val_split_point]]))
trainevals_data_indexes[Macros.DS_VAL].update(set([d.get_data_index() for d in documents_this_project[train_val_split_point:val_test_split_point]]))
trainevals_data_indexes[Macros.DS_TEST].update(set([d.get_data_index() for d in documents_this_project[val_test_split_point:]]))
# end for
trainevals_data_indexes[Macros.DS_TRAINEVAL_ALL] = set.union(*trainevals_data_indexes.values())
cls.logger.info(f"Train/eval split #doc:\n" + ";\n".join([
f"{traineval}: {len(data_indexes)}"
for traineval, data_indexes in trainevals_data_indexes.items()
]))
# Split by groups
groups_project_names: Dict[str, List[str]] = {group: [p.full_name for p in projects if p.data["group"] == group] for group in Macros.DS_GROUPS}
groups_data_indexes: Dict[str, Set[str]] = dict()
for group, project_names in groups_project_names.items():
documents_this_group: List[CoqDocument] = [d for d in coq_documents if d.project_name in project_names]
groups_data_indexes[group] = set([d.get_data_index() for d in documents_this_group])
# end for
groups_data_indexes[Macros.DS_GROUP_TA] = set.union(groups_data_indexes[Macros.DS_GROUP_T1], groups_data_indexes[Macros.DS_GROUP_T2], groups_data_indexes[Macros.DS_GROUP_T3])
groups_data_indexes[Macros.DS_GROUP_ALL] = set.union(groups_data_indexes[Macros.DS_GROUP_T1], groups_data_indexes[Macros.DS_GROUP_T2], groups_data_indexes[Macros.DS_GROUP_T3], groups_project_names[Macros.DS_GROUP_LO])
cls.logger.info(f"Groups split #doc:\n" + ";\n".join([
f"{group}: {len(data_indexes)}"
for group, data_indexes in groups_data_indexes.items()
]))
# The final data indexes is cross product of the two splits
for traineval in Macros.DS_TRAINEVALS + [Macros.DS_TRAINEVAL_ALL]:
for group in Macros.DS_GROUPS + [Macros.DS_GROUP_TA, Macros.DS_GROUP_ALL]:
data_indexes = list(set.intersection(groups_data_indexes[group], trainevals_data_indexes[traineval]))
cls.logger.info(f"{group}-{traineval} #doc = {len(data_indexes)}")
data_mgr.dump_data([FilesManager.DATA_INDEXES, f"{group}-{traineval}.json"], data_indexes, IOUtils.Format.jsonPretty)
# end for
# end for
return
RE_PATH_TO_QUALIFIED_PREFIX = re.compile(r"-[QR] (?P<path>[^,]+),(?P<qprefix>\S+)")
@classmethod
def collect_lemmas(cls, data_mgr: FilesManager, projects: List[Project], files: List[str] = None):
data_mgr.clean_path([FilesManager.LEMMAS])
data_mgr.resolve([FilesManager.LEMMAS]).mkdir(parents=True)
# Increase recursion limit because the backend sexps are CRAZZZZY deep
sys.setrecursionlimit(10000)
# Load coq-documents
coq_documents: List[CoqDocument] = cls.load_coq_documents(data_mgr)
if files is not None: coq_documents = [d for d in coq_documents if d.file_name in files]
lemmas: List[Lemma] = list()
# Prepare serapi_options
project_2_serapi_options: Dict[str, str] = {p.full_name: p.data["serapi_options"] for p in projects}
errors: List[Tuple[str, str]] = list()
for doc_i, doc in enumerate(tqdm(coq_documents)):
try:
cls.logger.info(f"Collecting from file {doc.get_data_index()} ({doc_i}/{len(coq_documents)}). Collected: {len(lemmas)}")
# Load AST sexp
ast_sexp_list: List[SexpNode] = SexpParser.parse_list(data_mgr.load_data([FilesManager.RAW_FILES, doc.get_data_index()[:-2] + ".ast.sexp"], IOUtils.Format.txt))
# Collect lemmas from this doc
lemmas_doc: List[Lemma] = cls.collect_lemmas_doc(doc, ast_sexp_list, project_2_serapi_options[doc.project_name])
lemmas.extend(lemmas_doc)
except KeyboardInterrupt:
cls.logger.warning(f"Keyboard Interrupt!")
raise
except:
cls.logger.warning(f"Error while parsing {doc.get_data_index()}: {traceback.format_exc()}")
cls.logger.warning(f"The script will continue on other files before it returns with failure. Use Ctrl+C to cut it early.")
errors.append((doc.get_data_index(), traceback.format_exc()))
continue
# end try
# end for
if len(errors) > 0:
LoggingUtils.log_and_raise(cls.logger, f"There were {len(errors)} errors during collection.", Exception)
data_mgr.dump_data([FilesManager.LEMMAS, "errors.txt"], errors, IOUtils.Format.jsonPretty)
# end if
# Assign uids
for lemma_i, lemma in enumerate(lemmas): lemma.uid = lemma_i
data_mgr.dump_data([FilesManager.LEMMAS], lemmas, IOUtils.Format.json, is_batched=True, per_batch=5000)
return
@classmethod
def filter_lemmas(cls, data_mgr: FilesManager):
# Increase recursion limit because the backend sexps are CRAZZZZY deep
sys.setrecursionlimit(10000)
data_mgr.clean_path([FilesManager.LEMMAS_FILTERED])
data_mgr.resolve([FilesManager.LEMMAS_FILTERED]).mkdir(parents=True)
# Load lemmas
lemmas: List[Lemma] = data_mgr.load_data([FilesManager.LEMMAS], IOUtils.Format.json, is_batched=True, clz=Lemma)
heights: List[int] = [l.backend_sexp.height() for l in lemmas]
depth_cutoff_point = sorted(heights)[int(np.ceil(Macros.LEMMAS_DEPTH_CUTOFF * len(lemmas)))]
data_indexes_names: List[Tuple[str, str]] = [(l.data_index, l.name) for l in lemmas if l.backend_sexp.height() <= depth_cutoff_point]
cls.logger.info(f"Cutoff depth is {depth_cutoff_point}, and {len(data_indexes_names)} data are included")
lemmas_filtered: List[Lemma] = [l for l in lemmas if (l.data_index, l.name) in data_indexes_names]
# Assign uids
for lemma_i, lemma in enumerate(lemmas_filtered): lemma.uid = lemma_i
data_mgr.dump_data([FilesManager.LEMMAS_FILTERED], lemmas_filtered, IOUtils.Format.json, is_batched=True, per_batch=5000)
return
@classmethod
def collect_definitions(cls, data_mgr: FilesManager):
data_mgr.clean_path([FilesManager.DEFINITIONS])
data_mgr.resolve([FilesManager.DEFINITIONS]).mkdir(parents=True)
# Load coq-documents
coq_documents: List[CoqDocument] = cls.load_coq_documents(data_mgr)
definitions: List[Definition] = list()
errors: List[Tuple[str, str]] = list()
for doc_i, doc in enumerate(tqdm(coq_documents)):
try:
# Load AST sexp
ast_sexp_list: List[SexpNode] = SexpParser.parse_list(data_mgr.load_data([FilesManager.RAW_FILES, doc.get_data_index()[:-2] + ".ast.sexp"], IOUtils.Format.txt))
definitions_doc: List[Definition] = cls.collect_definitions_doc(doc, ast_sexp_list)
definitions.extend(definitions_doc)
except KeyboardInterrupt:
cls.logger.warning(f"Keyboard Interrupt!")
raise
except:
cls.logger.warning(f"Error while parsing {doc.get_data_index()}: {traceback.format_exc()}")
cls.logger.warning(f"The script will continue on other files before it returns with failure. Use Ctrl+C to cut it early.")
errors.append((doc.get_data_index(), traceback.format_exc()))
continue
# end try
# end for
if len(errors) > 0:
LoggingUtils.log_and_raise(cls.logger, f"There were {len(errors)} errors during collection.", Exception)
data_mgr.dump_data([FilesManager.DEFINITIONS, "errors.txt"], errors, IOUtils.Format.jsonPretty)
# end if
data_mgr.dump_data([FilesManager.DEFINITIONS, "definitions.json"], definitions, IOUtils.Format.json)
return
@classmethod
def collect_lemmas_backend_sexp_transformations(cls, data_mgr: FilesManager):
data_mgr.clean_path([cls.TASK_LEMMA_BACKEND_SEXP_TRANSFORMATIONS])
data_mgr.resolve([cls.TASK_LEMMA_BACKEND_SEXP_TRANSFORMATIONS]).mkdir(parents=True)
# Increase recursion limit because the backend sexps are CRAZZZZY deep
sys.setrecursionlimit(10000)
lemmas_filtered: List[Lemma] = data_mgr.load_data([FilesManager.LEMMAS_FILTERED], IOUtils.Format.json, is_batched=True, clz=Lemma)
# Main stream transformations, applied one after another
levels_lemmas_bsexp_transformed: Dict[str, List[SexpNode]] = dict()
last_level: Optional[str] = None # None means original
for level in LemmaBackendSexpTransformers.LEVELS:
cls.logger.info(f"Doing {last_level if last_level is not None else 'orig'} -> {level} transformation")
levels_lemmas_bsexp_transformed[level] = list()
for lemma_i, lemma in enumerate(tqdm(lemmas_filtered)):
orig_sexp = lemma.backend_sexp if last_level is None else levels_lemmas_bsexp_transformed[last_level][lemma_i]
bsexp_transformed = LemmaBackendSexpTransformers.transform(level, copy.deepcopy(orig_sexp))
levels_lemmas_bsexp_transformed[level].append(bsexp_transformed)
# end for
last_level = level
data_mgr.dump_data([cls.TASK_LEMMA_BACKEND_SEXP_TRANSFORMATIONS, level, "transformed"], levels_lemmas_bsexp_transformed[level], IOUtils.Format.json, is_batched=True, per_batch=5000)
# end for
# Other special transformation, directly applied on original trees
for tr_name in LemmaBackendSexpTransformers.SPECIALS:
cls.logger.info(f"Doing orig -> {tr_name} transformation")
bsexp_transformed_list = list()
for lemma_i, lemma in enumerate(tqdm(lemmas_filtered)):
orig_sexp = lemma.backend_sexp
bsexp_transformed = LemmaBackendSexpTransformers.transform(tr_name, copy.deepcopy(orig_sexp))
bsexp_transformed_list.append(bsexp_transformed)
# end for
data_mgr.dump_data([cls.TASK_LEMMA_BACKEND_SEXP_TRANSFORMATIONS, tr_name, "transformed"], bsexp_transformed_list, IOUtils.Format.json, is_batched=True, per_batch=5000)
# end for
return
@classmethod
def collect_lemmas_foreend_sexp_transformations(cls, data_mgr: FilesManager):
data_mgr.clean_path([cls.TASK_LEMMA_FOREEND_SEXP_TRANSFORMATIONS])
data_mgr.resolve([cls.TASK_LEMMA_FOREEND_SEXP_TRANSFORMATIONS]).mkdir(parents=True)
# Increase recursion limit because the backend sexps are CRAZZZZY deep
sys.setrecursionlimit(10000)
lemmas_filtered: List[Lemma] = data_mgr.load_data([FilesManager.LEMMAS_FILTERED], IOUtils.Format.json, is_batched=True, clz=Lemma)
# Main stream transformations, applied one after another
levels_lemmas_fsexp_transformed: Dict[str, List[SexpNode]] = dict()
last_level: Optional[str] = None # None means original
for level in LemmaForeendSexpTransformers.LEVELS:
cls.logger.info(f"Doing {last_level if last_level is not None else 'orig'} -> {level} transformation")
levels_lemmas_fsexp_transformed[level] = list()
for lemma_i, lemma in enumerate(tqdm(lemmas_filtered)):
orig_sexp = lemma.ast_sexp if last_level is None else levels_lemmas_fsexp_transformed[last_level][lemma_i]
fsexp_transformed = LemmaForeendSexpTransformers.transform(level, copy.deepcopy(orig_sexp))
levels_lemmas_fsexp_transformed[level].append(fsexp_transformed)
# end for
last_level = level
data_mgr.dump_data([cls.TASK_LEMMA_FOREEND_SEXP_TRANSFORMATIONS, level, "transformed"], levels_lemmas_fsexp_transformed[level], IOUtils.Format.json, is_batched=True, per_batch=5000)
# end for
# Other special transformation, directly applied on level 0 trees
for tr_name in LemmaForeendSexpTransformers.SPECIALS:
cls.logger.info(f"Doing {LemmaForeendSexpTransformers.LEVEL_0} -> {tr_name} transformation")
fsexp_transformed_list = list()
for lemma_i, lemma in enumerate(tqdm(lemmas_filtered)):
orig_sexp = levels_lemmas_fsexp_transformed[LemmaForeendSexpTransformers.LEVEL_0][lemma_i]
fsexp_transformed = LemmaForeendSexpTransformers.transform(tr_name, copy.deepcopy(orig_sexp))
fsexp_transformed_list.append(fsexp_transformed)
# end for
data_mgr.dump_data([cls.TASK_LEMMA_FOREEND_SEXP_TRANSFORMATIONS, tr_name, "transformed"], fsexp_transformed_list, IOUtils.Format.json, is_batched=True, per_batch=5000)
# end for
return
VTYPES_LEMMA = [SexpInfo.VernacConsts.type_start_theorem_proof]
VTYPES_MODULE_BEG = [SexpInfo.VernacConsts.type_define_module]
VTYPES_MODULE_END = [SexpInfo.VernacConsts.type_end_segment]
VTYPES_DEFINITIONS = [SexpInfo.VernacConsts.type_definition]
@classmethod
def collect_lemmas_doc(
cls,
doc: CoqDocument,
ast_sexp_list: List[SexpNode],
serapi_options: str,
) -> List[Lemma]:
lemmas_doc: List[Lemma] = list()
data_index = doc.get_data_index()
# Maintain a stack of module
modules: List[str] = list()
# Prepare qualified name prefix
qprefix_this_doc = "./" + doc.file_name[:-2] # Remove .v
for m in cls.RE_PATH_TO_QUALIFIED_PREFIX.finditer(serapi_options):
path = m.group("path")
if path != ".": path = "./" + path
qprefix = m.group("qprefix")
if qprefix_this_doc.startswith(path):
qprefix_this_doc = qprefix + qprefix_this_doc[len(path):]
break
# end if
# end for
if qprefix_this_doc.startswith("./"): qprefix_this_doc = qprefix_this_doc[len("./"):]
qprefix_this_doc = qprefix_this_doc.replace("/", ".")
for sent_i, sent in enumerate(doc.sentences):
ast_sexp = ast_sexp_list[sent_i]
vernac = SexpAnalyzer.analyze_vernac(ast_sexp)
if vernac.vernac_type in cls.VTYPES_MODULE_BEG:
# (VernacExpr()(VernacDefineModule() ( ( v ( Id <module name>)) ...
# 0 1 2 20 21 22 220 2201 22011
module_name = vernac.vernac_sexp[2][2][0][1][1].content_no_quote
modules.append(module_name)
elif vernac.vernac_type in cls.VTYPES_MODULE_END:
# (VernacExpr()(VernacEndSegment ( ( v ( Id <module name>)) ...
# 0 1 2 20 21 210 2101 21011
try:
module_name = vernac.vernac_sexp[2][1][0][1][1].content_no_quote
except:
print(vernac.vernac_sexp.pretty_format())
raise
# end try
if len(modules) > 0 and module_name == modules[-1]: modules.pop() # EndModule and EndSection share the same vernac type
elif vernac.vernac_type in cls.VTYPES_LEMMA:
# (VernacExpr()(VernacStartTheoremProof Lemma ( ( ( ( ( v ( Id <lemma name>))
# 0 1 2 20 21 22 2200000 2200001 22000011
lemma = Lemma()
lemma.data_index = data_index
lemma.name = vernac.vernac_sexp[2][2][0][0][0][0][1][1].content_no_quote
lemma.qname = qprefix_this_doc + "." + ".".join(modules + [lemma.name])
# Find lemma content, after the first token matching the lemma name
tok_i = 0
for tok in sent.tokens:
if tok.content == lemma.name: break
tok_i += 1
# end for
if tok_i == len(sent.tokens): LoggingUtils.log_and_raise(cls.logger, f"Lemma name {lemma.name} didn't appear in the source code {sent.str_with_space()}", Exception)
lemma.vernac_command = sent.tokens[:tok_i]
lemma.statement = sent.tokens[tok_i + 1:]
lemma.ast_sexp = vernac.vernac_sexp
lemmas_doc.append(lemma)
# end if
# end for
# Use sername to get the backend representations
lemma_qnames: str = "".join([l.qname + "\n" for l in lemmas_doc])
lemma_qnames_file = BashUtils.get_temp_file()
IOUtils.dump(lemma_qnames_file, lemma_qnames, IOUtils.Format.txt)
lemma_qnames_backend_sexps_str: str = BashUtils.run(f"sername {serapi_options} --require-lib={qprefix_this_doc} {lemma_qnames_file}", expected_return_code=0).stdout
IOUtils.rm(lemma_qnames_file)
for qname_backend_sexp_str in lemma_qnames_backend_sexps_str.splitlines():
qname, backend_sexp_str = qname_backend_sexp_str.split(":", 1)
backend_sexp = SexpParser.parse(backend_sexp_str)
for lemma in lemmas_doc:
if lemma.qname == qname:
lemma.backend_sexp = backend_sexp
break
# end if
# end for
# end for
lemmas_doc = [l for l in lemmas_doc if l.backend_sexp is not None]
return lemmas_doc
@classmethod
def collect_definitions_doc(cls,
doc: CoqDocument,
ast_sexp_list: List[SexpNode],
) -> List[Definition]:
definitions_doc: List[Definition] = list()
data_index = doc.get_data_index()
for sent_i, sent in enumerate(doc.sentences):
ast_sexp = ast_sexp_list[sent_i]
vernac = SexpAnalyzer.analyze_vernac(ast_sexp)
if vernac.vernac_type in cls.VTYPES_DEFINITIONS:
# (VernacExpr()( VernacDefinition ( NoDischarge Definition) ( ( ( v ( Name ( Id codom ))) ...
# 0 1 2 20 21 210 211 22 220 2200 22000 22001 220010 220011 2200110 2200111
try:
if vernac.vernac_sexp[2][1][0].content == "NoDischarge" and vernac.vernac_sexp[2][1][1].content == "Definition":
definition = Definition()
definition.data_index = data_index
definition.name = vernac.vernac_sexp[2][2][0][0][1][1][1].content_no_quote
definitions_doc.append(definition)
# end if
except IllegalSexpOperationException:
continue
# end try
# end if
# end for
return definitions_doc
@classmethod
def extract_data_project(cls,
project_path: Path,
files: Optional[List[str]],
exclude_files: Optional[List[str]],
exclude_pattern: Optional[str],
serapi_options: str,
output_path: Path,
):
# 1. Prepare output path
if output_path.is_dir():
cls.logger.warning(f"{output_path} already exists, will overwrite the files.")
elif output_path.is_file():
LoggingUtils.log_and_raise(cls.logger, f"{output_path} already exists as a file. Aborting.", Exception)
else:
IOUtils.mk_dir(output_path)
# end if
# 2. Extract documents, tok.sexp and ast.sexp
coq_documents: Dict[str, CoqDocument] = collections.OrderedDict()
ast_sexp_lists: Dict[str, List[SexpNode]] = dict()
tok_sexp_lists: Dict[str, List[SexpNode]] = dict()
with IOUtils.cd(project_path):
coq_files: List[str] = BashUtils.run(f"find -name '*.v' -type f").stdout.split("\n")[:-1]
coq_files = [coq_file[2:] for coq_file in coq_files]
if files is not None:
coq_files = [f for f in coq_files if f in files]
# end if
if exclude_files is not None:
coq_files = [f for f in coq_files if f not in exclude_files]
# end if
if exclude_pattern is not None:
re_exclude_pattern = re.compile(exclude_pattern)
coq_files = [f for f in coq_files if not re_exclude_pattern.fullmatch(f)]
# end if
for i, coq_file in enumerate(tqdm(coq_files)):
try:
# Read file
with open(coq_file, "r", newline="") as f:
source_code = f.read()
# end with
# Get unicode offsets
unicode_offsets = ParserUtils.get_unicode_offsets(source_code)
# Call SerAPI
ast_sexp_str: str = BashUtils.run(f"sercomp {serapi_options} --mode=sexp -- {coq_file}", expected_return_code=0).stdout
tok_sexp_str: str = BashUtils.run(f"sertok {serapi_options} -- {coq_file}", expected_return_code=0).stdout
# Parse ast sexp
ast_sexp_list: List[SexpNode] = SexpParser.parse_list(ast_sexp_str)
tok_sexp_list: List[SexpNode] = SexpParser.parse_list(tok_sexp_str)
# Parse the document
coq_document = CoqParser.parse_document(source_code, ast_sexp_list, tok_sexp_list, unicode_offsets=unicode_offsets)
# Set meta data
coq_document.file_name = coq_file
coq_document.project_name = project_path.name
coq_documents[coq_file] = coq_document
ast_sexp_lists[coq_file] = ast_sexp_list
tok_sexp_lists[coq_file] = tok_sexp_list
except KeyboardInterrupt:
cls.logger.warning("Keyboard interrupt!")
raise
except:
cls.logger.warning(f"File {coq_file} failed! Exception was: {traceback.format_exc()}")
continue
# end try
# end for
# 3. Extract and save lemmas and definitions
lemmas: List[Lemma] = list()
definitions: List[Definition] = list()
# Increase recursion limit because the backend sexps are CRAZZZZY deep
sys.setrecursionlimit(10000)
for file_path, doc in tqdm(coq_documents.items()):
ast_sexp_list = ast_sexp_lists[file_path]
lemmas_doc = cls.collect_lemmas_doc(doc, ast_sexp_list, serapi_options)
lemmas.extend(lemmas_doc)
definitions_doc = cls.collect_definitions_doc(doc, ast_sexp_list)
definitions.extend(definitions_doc)
# end for
IOUtils.dump(output_path/"lemmas.json", IOUtils.jsonfy(lemmas), IOUtils.Format.json)
IOUtils.dump(output_path/"definitions.json", IOUtils.jsonfy(definitions), IOUtils.Format.json)
# end with
return
@classmethod
def extract_data_from_corpus(cls,
corpus_path: Path,
trainevals: List[str],
groups: List[str],
output_path: Path,
):
# 1. Prepare output path
if output_path.is_dir():
cls.logger.warning(f"{output_path} already exists, will overwrite the files.")
elif output_path.is_file():
LoggingUtils.log_and_raise(cls.logger, f"{output_path} already exists as a file. Aborting.", Exception)
else:
IOUtils.mk_dir(output_path)
# end if
assert all([traineval in Macros.DS_TRAINEVALS for traineval in trainevals])
assert all([group in Macros.DS_GROUPS+[Macros.DS_GROUP_TA] for group in groups])
data_mgr = FilesManager(corpus_path)
# 2. Load lemmas and definitions
lemmas_filtered: List[Lemma] = data_mgr.load_data([FilesManager.LEMMAS_FILTERED], IOUtils.Format.json, is_batched=True, clz=Lemma)
definitions: List[Definition] = data_mgr.load_data([FilesManager.DEFINITIONS, "definitions.json"], IOUtils.Format.json, clz=Definition)
# 3. Output to output_path for each combination of traineval and group
for traineval in trainevals:
for group in groups:
IOUtils.mk_dir(output_path/f"{group}-{traineval}")
data_indexes = IOUtils.load(Macros.project_dir/"training"/f"{group}-{traineval}.json", IOUtils.Format.json)
IOUtils.dump(output_path/f"{group}-{traineval}/lemmas.json", IOUtils.jsonfy([l for l in lemmas_filtered if l.data_index in data_indexes]), IOUtils.Format.json)
IOUtils.dump(output_path/f"{group}-{traineval}/definitions.json", IOUtils.jsonfy([d for d in definitions if d.data_index in data_indexes]), IOUtils.Format.json)
# end for
# end for
return
| StarcoderdataPython |
5191183 | #!/usr/bin/env python
"""
A pygame program to show a slideshow of all images buried in a given directory.
Originally Released: 2007.10.31 (Happy halloween!)
"""
import argparse
import os
import stat
import sys
import time
import pygame
from pygame.locals import QUIT, KEYDOWN, K_ESCAPE
file_list = [] # a list of all images being shown
title = "pgSlideShow | My Slideshow!" # caption of the window...
waittime = 1 # default time to wait between images (in seconds)
def walktree(top, callback):
"""recursively descend the directory tree rooted at top, calling the
callback function for each regular file. Taken from the module-stat
example at: http://docs.python.org/lib/module-stat.html
"""
for f in os.listdir(top):
pathname = os.path.join(top, f)
mode = os.stat(pathname)[stat.ST_MODE]
if stat.S_ISDIR(mode):
# It's a directory, recurse into it
walktree(pathname, callback)
elif stat.S_ISREG(mode):
# It's a file, call the callback function
callback(pathname)
else:
# Unknown file type, print a message
print 'Skipping %s' % pathname
def addtolist(file, extensions=['.png', '.jpg', '.jpeg', '.gif', '.bmp']):
"""Add a file to a global list of image files."""
global file_list # ugh
filename, ext = os.path.splitext(file)
e = ext.lower()
# Only add common image types to the list.
if e in extensions:
print 'Adding to list: ', file
file_list.append(file)
else:
print 'Skipping: ', file, ' (NOT a supported image)'
def input(events):
"""A function to handle keyboard/mouse/device input events. """
for event in events: # Hit the ESC key to quit the slideshow.
if (event.type == QUIT or
(event.type == KEYDOWN and event.key == K_ESCAPE)):
pygame.quit()
def main(startdir="."):
global file_list, title, waittime
pygame.init()
# Test for image support
if not pygame.image.get_extended():
print "Your Pygame isn't built with extended image support."
print "It's likely this isn't going to work."
sys.exit(1)
walktree(startdir, addtolist) # this may take a while...
if len(file_list) == 0:
print "Sorry. No images found. Exiting."
sys.exit(1)
modes = pygame.display.list_modes()
pygame.display.set_mode(max(modes))
screen = pygame.display.get_surface()
pygame.display.set_caption(title)
pygame.display.toggle_fullscreen()
current = 0
num_files = len(file_list)
while(True):
try:
img = pygame.image.load(file_list[current])
img = img.convert()
# rescale the image to fit the current display
img = pygame.transform.scale(img, max(modes))
screen.blit(img, (0, 0))
pygame.display.flip()
input(pygame.event.get())
time.sleep(waittime)
except pygame.error as err:
print "Failed to display %s: %s" % (file_list[current], err)
# When we get to the end, re-start at the beginning
current = (current + 1) % num_files;
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Recursively loads images '
'from a directory, then displays them in a Slidshow.'
)
parser.add_argument(
'path',
metavar='ImagePath',
type=str,
default='.',
nargs="?",
help='Path to a directory that contains images'
)
parser.add_argument(
'--waittime',
type=int,
dest='waittime',
action='store',
default=1,
help='Amount of time to wait before showing the next image.'
)
parser.add_argument(
'--title',
type=str,
dest='title',
action='store',
default="pgSlidShow | My Slideshow!",
help='Set the title for the display window.'
)
args = parser.parse_args()
waittime = args.waittime
title = args.title
main(startdir=args.path)
| StarcoderdataPython |
11215840 | '''
A utility function such that you can test/train in-air controls without ever landing.
'''
import time
from bot_code.trainer.utils.floating_setup import bakkes
from random import random
# Calling bakkesmod too often may cause a crash.
# Therefore ratelimit it by dropping some calls.
MIN_DELAY_BETWEEN_BAKKES_CALLS = 3 * 1/60.
last_bakkes_call = {} # player_index -> time of last call
def should_call_bakkes(player_index):
# Note: this function mutates external state: last_bakkes_call.
now = time.clock()
if now - last_bakkes_call.get(player_index, 0) > MIN_DELAY_BETWEEN_BAKKES_CALLS:
last_bakkes_call[player_index] = now
return True
return False
def make_player_float(player_index, location):
# Call this every frame to reset the players position
if not should_call_bakkes(player_index):
return
height = 250 + 200*player_index
# Hopefully this dependence onc bakkesmod will be removed with the new RLBot api
bakkes.rcon(';'.join([
'player {} location {} {} {}'.format(player_index, *location),
'player {} velocity -0 0 10'.format(player_index),
]))
def make_ball_float(location=(200, 0, 500)):
if not should_call_bakkes('BALL'):
return
bakkes.rcon(';'.join([
'ball location {} {} {}'.format(*location),
'ball velocity 0 0 0',
]))
last_rotation_modification = {} # player_index -> time of last change of rotation/angular vel
def set_random_pitch_and_pitch_vel_periodically(player_index, period=2.0):
now = time.clock()
if now - last_rotation_modification.get(player_index, 0) > period:
last_rotation_modification[player_index] = now
set_random_pitch_and_pitch_vel(player_index)
def set_random_pitch_and_pitch_vel(player_index):
bakkes.rcon(';'.join([
'player {} rotation {} 0 0'.format( player_index, (100000 * (random() - 0.5))),
'player {} angularvelocity 0 {} 0'.format(player_index, ( 10 * (random() - 0.5))),
]))
| StarcoderdataPython |
11249803 | <reponame>Algy/pipex
import time
import numpy as np
from PIL import Image
from base64 import b64encode
from typing import Dict, Any
from html import escape
id_func = id
def repr_image(value):
buffer = value._repr_png_()
src = "data:image/png;base64," + b64encode(buffer).decode()
return "<img src='{}' style='width: 100%'>".format(src)
def repr_atom(atom) -> str:
value = atom.value
if atom.format == 'image' and isinstance(value, np.ndarray):
try:
return repr_image(Image.fromarray(value))
except Exception as e:
pass
if hasattr(value, '_repr_png_'):
return repr_image(value)
if hasattr(value, '_repr_html_'):
return value._repr_html_()
return "<pre>" + escape(repr(atom.value)) + "</pre>"
def repr_channel(channel_name, atom, is_active) -> str:
if atom is not None:
content = repr_atom(atom)
else:
content = escape(repr(atom))
return """
<tr>
<th>{}{}</th>
<td>{}</td>
</tr>
""".format(channel_name, "*" if is_active else "", content)
def _repr_html_(self):
channels = [self.active_channel]+ [chan for chan in self.channels if chan != self.active_channel]
prologue = '''
<div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe" style="width: 100%; table-layout: auto">
<caption>[[TARGET_CAPTION]]</caption>
<thead>
<tr style="text-align: right;">
<th>channel</th>
<th>value</th>
</tr>
</thead>
<tbody>
'''.replace("[[TARGET_CAPTION]]", escape(self.id))
epilogue = '''
</tbody>
</table>
</div>
'''
content = "\n".join(
repr_channel(channel, self.get_atom(channel), channel == self.active_channel)
for channel in channels
)
return prologue + content + epilogue
def _infer_format_from_type(channel_name: str, value: Any) -> str:
if isinstance(value, np.ndarray):
if channel_name.startswith('image') or channel_name.startswith('img'):
return 'image'
else:
return 'numpy.ndarray'
elif isinstance(value, (type(None), str, int, float, bool, list)):
return "data"
else:
return "blob"
class PAtom:
__slots__ = ('value', 'format', )
def __init__(self, *, value: Any, format: str):
self.value = value
self.format = format
class PRecord:
__slots__ = ('id', 'timestamp', 'active_channel', 'channel_atoms', '_value')
def __init__(self, *,
id: str,
timestamp: float = None,
active_channel: str = 'default',
channel_atoms: Dict[str, PAtom] = None):
self.id = id
self.timestamp = timestamp or time.time()
self.active_channel = active_channel
self.channel_atoms = channel_atoms or {}
@property
def atom(self):
return self.channel_atoms.get(self.active_channel)
@property
def value(self):
try:
return self._value
except AttributeError:
atom = self.atom
if atom is None:
value = None
else:
value = atom.value
self._value = value
return value
@property
def value_format(self):
atom = self.atom
if atom is None:
return None
return atom.format
@property
def channels(self):
return self.channel_atoms.keys()
def get(self, name, default=None):
atom = self.channel_atoms.get(name)
if atom is None:
return default
return atom.value
def get_atom(self, name):
return self.channel_atoms.get(name)
def __getitem__(self, name):
atom = self.channel_atoms[name]
return atom.value
def with_channel(self, channel_name: str) -> "PRecord":
return PRecord(
id=self.id,
timestamp=self.timestamp,
active_channel=channel_name,
channel_atoms=self.channel_atoms,
)
def select_channels(self, channels) -> "PRecord":
channel_atoms = {
k: v
for k, v in self.channel_atoms.items()
if k in channels
}
return PRecord(
id=self.id,
timestamp=self.timestamp,
active_channel=self.active_channel,
channel_atoms=channel_atoms,
)
def with_channel_item(self, channel_name: str, value: Any) -> "PRecord":
channel_atoms = self.channel_atoms.copy()
channel_atoms[channel_name] = PAtom(value=value, format=_infer_format_from_type(channel_name, value))
return PRecord(
id=self.id,
timestamp=self.timestamp,
active_channel=channel_name,
channel_atoms=channel_atoms,
)
def merge(self, **kwargs) -> "PRecord":
channel_atoms = self.channel_atoms.copy()
for key, value in kwargs.items():
channel_atoms[key] = PAtom(value=value, format=_infer_format_from_type(key, value))
return PRecord(
id=self.id,
timestamp=time.time(),
active_channel=self.active_channel,
channel_atoms=channel_atoms,
)
def with_id(self, id: str):
return PRecord(
id=id,
timestamp=self.timestamp,
active_channel=self.active_channel,
channel_atoms=self.channel_atoms,
)
def with_value(self, value: Any):
active_channel = self.active_channel
channel_atoms = self.channel_atoms.copy()
channel_atoms[active_channel] = PAtom(
value=value,
format=_infer_format_from_type(active_channel, value)
)
return PRecord(
id=self.id,
timestamp=self.timestamp,
active_channel=self.active_channel,
channel_atoms=channel_atoms,
)
@classmethod
def from_object(cls, obj, channel_name='default', id=None):
return cls(
id=id or str(id_func(obj)),
timestamp=time.time(),
active_channel=channel_name,
channel_atoms={
channel_name: PAtom(
value=obj,
format=_infer_format_from_type(channel_name, obj),
)
}
)
def __repr__(self):
return ("<PRecord id={!r} timestamp={!r} active_channel={!r} channels={!r}>"
.format(
self.id,
self.timestamp,
self.active_channel,
list(self.channels),
))
def _repr_html_(self):
return _repr_html_(self)
| StarcoderdataPython |
4938484 | <reponame>heyrict/cindy-realtime<gh_stars>1-10
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sui_hei', '%s'),
]
operations = [
migrations.RenameModel("Mondai", "Puzzle"),
migrations.RenameModel("Lobby", "Minichat"),
migrations.RenameModel("Shitumon", "Dialogue"),
migrations.RenameField(
model_name='puzzle',
old_name='kaisetu',
new_name='solution', ),
migrations.RenameField(
model_name='dialogue',
old_name='kaitou',
new_name='answer', ),
migrations.RenameField(
model_name='dialogue',
old_name='shitumon',
new_name='question', ),
migrations.RenameField(
model_name='comment',
old_name='mondai',
new_name='puzzle', ),
migrations.RenameField(
model_name='dialogue',
old_name='mondai',
new_name='puzzle', ),
migrations.RenameField(
model_name='star',
old_name='mondai',
new_name='puzzle', ),
]
| StarcoderdataPython |
11252020 | import sys
read = sys.stdin.readline
for _ in range(3):
s = 0
for _ in range(int(read())):
s += int(read())
if s > 0:
print('+')
elif s < 0:
print('-')
else:
print(0)
| StarcoderdataPython |
5011154 | import pytest
from serializers.property import PropertySerializer
from utils.time import Time
@pytest.mark.usefixtures("empty_test_db")
class TestPropertySerializer:
def test_serializer(self, create_property):
property = create_property()
assert PropertySerializer.serialize(property) == {
"id": property.id,
"name": property.name,
"address": property.address,
"num_units": property.num_units,
"city": property.city,
"state": property.state,
"zipcode": property.zipcode,
"archived": property.archived,
"created_at": Time.format_date(property.created_at),
"updated_at": Time.format_date(property.updated_at),
}
| StarcoderdataPython |
200948 | <filename>superinvoke/collections/misc.py
from invoke import task
@task(variadic=True)
def help(context, collection):
"""Show available commands."""
context.run(f"invoke --list {collection}")
| StarcoderdataPython |
157985 | <reponame>zhongxixixixi/myblog-Flask
from flask import Flask, render_template, request, redirect, url_for, session
import config
from exts import db
from models import User, Question, Comment
from decorators import login_required
app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)
@app.route('/')
def index():
context = {
'questions': Question.query.order_by('create_time').all()
}
return render_template('index.html', **context)
@app.route('/login/', methods=['GET', 'POST'])
def login():
if request.method == 'GET':
return render_template('login.html')
else:
ltele = request.form.get('l-tele')
lpw = request.form.get('l-pw')
luser = User.query.filter(User.telephone == ltele and User.password == <PASSWORD>).first()
if luser:
session['user_id'] = luser.id
session.permanent = True
return redirect(url_for('index'))
@app.route('/logout/')
def logout():
if session.get('user_id'):
session.pop('user_id')
return redirect(url_for('login'))
else:
pass
@app.route('/register/', methods=['GET', 'POST'])
def register():
if request.method == 'GET':
return render_template('register.html')
else:
rtele = request.form.get('r-tele')
rname = request.form.get('r-name')
rpw = request.form.get('r-pw')
rpw1 = request.form.get('r-pw1')
if User.query.filter(User.telephone == rtele).first():
return '该号码已被注册,请更换号码!'
elif rpw != rpw1:
return '两次密码输入不一致,请核对!'
else:
ruser = User(telephone=rtele, username=rname, password=<PASSWORD>)
db.session.add(ruser)
db.session.commit()
return redirect(url_for('login'))
@app.route('/question/', methods=['GET', 'POST'])
@login_required
def question():
if request.method == 'GET':
return render_template('question.html')
else:
qtit = request.form.get('q-title')
qcon = request.form.get('q-content')
quser_id = session.get('user_id')
qauthor = User.query.filter(User.id == quser_id).first()
question1 = Question(title=qtit, content=qcon)
question1.author = qauthor
db.session.add(question1)
db.session.commit()
return redirect(url_for('index'))
@app.route('/detial/<question_id>')
def detial(question_id):
question2 = Question.query.filter(Question.id == question_id).first()
count = len(question2.comments)
return render_template('detial.html', question=question2, count=count)
@app.route('/comment/', methods=['POST'])
@login_required
def comment():
dcon = request.form.get('d-content')
duser_id = session.get('user_id')
duser = User.query.filter(User.id == duser_id).first()
dqid = request.form.get('d-qid')
dquestion = Question.query.filter(Question.id == dqid).first()
comment1 = Comment(content=dcon)
comment1.author = duser
comment1.question = dquestion
db.session.add(comment1)
db.session.commit()
return redirect(url_for('detial', question_id=dqid))
@app.context_processor
def my_cp():
user_id = session.get('user_id')
user = User.query.filter(User.id == user_id).first()
if user:
return {'user': user}
else:
return {}
if __name__ == '__main__':
app.run()
| StarcoderdataPython |
4892359 | <gh_stars>0
import cv2
import numpy as np
import copy
def reshape_image(image):
'''归一化图片尺寸:短边400,长边不超过800,短边400,长边超过800以长边800为主'''
width, height = image.shape[1], image.shape[0]
min_len = width
scale = width * 1.0 / 400
new_width = 400
new_height = int(height / scale)
if new_height > 800:
new_height = 800
scale = height * 1.0 / 800
new_width = int(width / scale)
out = cv2.resize(image, (new_width, new_height))
return out
def detecte(image):
'''提取所有轮廓'''
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, gray = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY_INV)
contours, hierachy = cv2.findContours(gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
return image, contours, hierachy
def compute_1(contours, i, j):
'''最外面的轮廓和子轮廓的比例'''
area1 = cv2.contourArea(contours[i])
area2 = cv2.contourArea(contours[j])
if area2 == 0:
return False
ratio = area1 * 1.0 / area2
if abs(ratio - 49.0 / 25):
return True
return False
def compute_2(contours, i, j):
'''子轮廓和子子轮廓的比例'''
area1 = cv2.contourArea(contours[i])
area2 = cv2.contourArea(contours[j])
if area2 == 0:
return False
ratio = area1 * 1.0 / area2
if abs(ratio - 25.0 / 9):
return True
return False
def compute_center(contours, i):
'''计算轮廓中心点'''
M = cv2.moments(contours[i])
cx = int(M['m10'] / M['m00'])
cy = int(M['m01'] / M['m00'])
return cx, cy
def detect_contours(vec):
'''判断这个轮廓和它的子轮廓以及子子轮廓的中心的间距是否足够小'''
distance_1 = np.sqrt((vec[0] - vec[2]) ** 2 + (vec[1] - vec[3]) ** 2)
distance_2 = np.sqrt((vec[0] - vec[4]) ** 2 + (vec[1] - vec[5]) ** 2)
distance_3 = np.sqrt((vec[2] - vec[4]) ** 2 + (vec[3] - vec[5]) ** 2)
if sum((distance_1, distance_2, distance_3)) / 3 < 3:
return True
return False
def juge_angle(rec):
'''判断寻找是否有三个点可以围成等腰直角三角形'''
if len(rec) < 3:
return -1, -1, -1
for i in range(len(rec)):
for j in range(i + 1, len(rec)):
for k in range(j + 1, len(rec)):
distance_1 = np.sqrt((rec[i][0] - rec[j][0]) ** 2 + (rec[i][1] - rec[j][1]) ** 2)
distance_2 = np.sqrt((rec[i][0] - rec[k][0]) ** 2 + (rec[i][1] - rec[k][1]) ** 2)
distance_3 = np.sqrt((rec[j][0] - rec[k][0]) ** 2 + (rec[j][1] - rec[k][1]) ** 2)
if abs(distance_1 - distance_2) < 5:
if abs(np.sqrt(np.square(distance_1) + np.square(distance_2)) - distance_3) < 5:
return i, j, k
elif abs(distance_1 - distance_3) < 5:
if abs(np.sqrt(np.square(distance_1) + np.square(distance_3)) - distance_2) < 5:
return i, j, k
elif abs(distance_2 - distance_3) < 5:
if abs(np.sqrt(np.square(distance_2) + np.square(distance_3)) - distance_1) < 5:
return i, j, k
return -1, -1, -1
def find(image, contours, hierachy, root=0):
'''找到符合要求的轮廓'''
rec = []
for i in range(len(hierachy)):
child = hierachy[i][2]
child_child = hierachy[child][2]
if child != -1 and hierachy[child][2] != -1:
if compute_1(contours, i, child) and compute_2(contours, child, child_child):
cx1, cy1 = compute_center(contours, i)
cx2, cy2 = compute_center(contours, child)
cx3, cy3 = compute_center(contours, child_child)
if detect_contours([cx1, cy1, cx2, cy2, cx3, cy3]):
rec.append([cx1, cy1, cx2, cy2, cx3, cy3, i, child, child_child])
'''计算得到所有在比例上符合要求的轮廓中心点'''
i, j, k = juge_angle(rec)
if i == -1 or j == -1 or k == -1:
return
ts = np.concatenate((contours[rec[i][6]], contours[rec[j][6]], contours[rec[k][6]]))
rect = cv2.minAreaRect(ts)
box = cv2.boxPoints(rect)
box = np.int0(box)
result = copy.deepcopy(image)
cv2.drawContours(result, [box], 0, (0, 0, 255), 2)
cv2.drawContours(image, contours, rec[i][6], (255, 0, 0), 2)
cv2.drawContours(image, contours, rec[j][6], (255, 0, 0), 2)
cv2.drawContours(image, contours, rec[k][6], (255, 0, 0), 2)
cv2.imshow('img', image)
cv2.waitKey(0)
cv2.imshow('result', result)
cv2.waitKey(0)
return
if __name__ == '__main__':
imgpath = 'C:\\tmp\\s2.jpg'
image = cv2.imread(imgpath)
image = reshape_image(image)
cv2.imshow('sb', image)
# cv2.waitKey(0)
image, contours, hierachy = detecte(image)
find(image, contours, np.squeeze(hierachy)) | StarcoderdataPython |
1999929 | <reponame>supaflysnooka/whispers<gh_stars>0
from pathlib import Path
from whispers.utils import strip_string
class Htpasswd:
def pairs(self, filepath: Path):
for line in filepath.open("r").readlines():
if ":" not in line:
continue
creds = line.split(":")
value = strip_string(creds[1])
if value:
yield "htpasswd Hash", value
| StarcoderdataPython |
9636118 | import pandas as pd
from datetime import date, datetime, timedelta, timezone
######################################################
XLSX_PATH = 'wk16.xlsx'
ICAL_PATH = 'export.ics'
day_one = date(2021, 12, 13)
classes = [
'AP Psychology-Class 1',
'ACT1',
'AP Environmental Science',
'FAP1',
'AP Physics C E&M-Roger',
'AP Statistics Class 2',
'Contemporary English-Class 2'
]
cols = { 2:1, 4:3, 5:3, 6:3, 7:3 }
######################################################
tz_shanghai=timezone(timedelta(hours=8), 'Asia/Shanghai')
df = pd.read_excel(XLSX_PATH)
ical = open(ICAL_PATH, 'w')
ical.write('BEGIN:VCALENDAR\n')
for day_offset, col in enumerate(cols):
times = df.loc[:, df.columns[cols[col]]].dropna()
day = day_one + timedelta(days=day_offset)
for index in df.loc[:, df.columns[col]].dropna().index:
if any([cls for cls in classes if cls in df.loc[index, df.columns[col]]]):
ical.write('BEGIN:VEVENT\n')
term = df.loc[index, df.columns[col]].split('-')
time = ''
if (term.__len__() == 2):
ical.write('SUMMARY:{}\n'.format(term[1]))
if (term.__len__() == 3):
ical.write('SUMMARY:{}\n'.format(term[0]))
ical.write('LOCATION:{} {}\n'.format(term[2], term[1]))
if (term.__len__() == 4):
if 'class' in term[1].lower():
ical.write('SUMMARY:{}\n'.format(term[0]))
ical.write('LOCATION:{} {}\n'.format(term[3], term[2]))
else:
ical.write('SUMMARY:{}\n'.format(term[1]))
ical.write('LOCATION:{} {}\n'.format(term[3], term[2]))
for time_index in range(times.index.size):
if times.index[time_index] > index:
time = times.loc[times.index[time_index - 1]].split('-')
break
dtstart_list = time[0].split(':')
dtend_list = time[1].split(':')
dtstart = datetime(day.year, day.month, day.day, int(dtstart_list[0]), int(dtstart_list[1]), tzinfo=tz_shanghai)
dtend = datetime(day.year, day.month, day.day, int(dtend_list[0]), int(dtend_list[1]), tzinfo=tz_shanghai)
ical.write(f'DTSTART:{dtstart.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")}\n')
ical.write(f'DTEND:{dtend.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")}\n')
ical.write('END:VEVENT\n')
ical.write('END:VCALENDAR\n')
ical.close() | StarcoderdataPython |
1831221 | # Allow from hapiplotserver import hapiplotserver
from hapiplotserver.hapiplotserver import hapiplotserver
| StarcoderdataPython |
6441710 | <reponame>biomicrodev/broadside
import logging
from pathlib import Path
from typing import List, Any, Tuple
from natsort import natsort_keygen
from qtpy.QtCore import QAbstractTableModel, QModelIndex, Qt, QAbstractItemModel
from qtpy.QtWidgets import (
QTableView,
QAbstractItemView,
QHeaderView,
QWidget,
QVBoxLayout,
QStyledItemDelegate,
QStyleOptionViewItem,
QFileDialog,
QDialog,
QScrollArea,
)
from ..blocks.devices import NamesDelegate
from ....editor import Editor
from ....viewer_model import ViewerModel
from .....models.block import Block
from .....models.image import Image
from .....models.panel import Panel
def get_names(items: List) -> List[str]:
def key(name: str) -> Tuple[bool, str]:
return name == "", name
natkey = natsort_keygen(key=key)
names = sorted([i.name for i in items], key=natkey)
return names
class ImagesTableModel(QAbstractTableModel):
keys = ["relpath", "block_name", "panel_name"]
headers = ["Path", "Block", "Panel"]
types = [Path, str, str]
def __init__(self, basepath: Path, images: List[Image]):
super().__init__()
self.basepath = basepath
self.images = images
def data(self, index: QModelIndex, role: Qt.ItemDataRole = None):
if role in [Qt.DisplayRole, Qt.EditRole, Qt.ToolTipRole]:
row = index.row()
col = index.column()
key = self.keys[col]
value = getattr(self.images[row], key)
return str(value)
elif role == Qt.TextAlignmentRole:
col = index.column()
key = self.keys[col]
if key == "relpath":
# see https://stackoverflow.com/a/35175211 for `int()`
return int(Qt.AlignLeft | Qt.AlignVCenter)
else:
return Qt.AlignCenter
def setData(
self, index: QModelIndex, value: Any, role: Qt.ItemDataRole = None
) -> bool:
if role == Qt.EditRole:
row = index.row()
col = index.column()
key = self.keys[col]
type_ = self.types[col]
value = type_(value)
oldValue = getattr(self.images[row], key)
if oldValue == value:
return False
if key == "relpath":
dstAbspath = value
dstRelpath = dstAbspath.relative_to(self.basepath / Image.images_dir)
# remove duplicates
for image in self.images:
if dstRelpath == image.relpath:
return False
# move image
self.images[row].move(self.basepath, dstRelpath)
self.dataChanged.emit(index, index, Qt.EditRole)
return True
else:
setattr(self.images[row], key, value)
self.dataChanged.emit(index, index, Qt.EditRole)
return True
return False
def flags(self, index: QModelIndex) -> Qt.ItemFlags:
return super().flags(index) | Qt.ItemIsEditable
def rowCount(self, parent: QModelIndex = None, *args, **kwargs) -> int:
return len(self.images)
def columnCount(self, parent: QModelIndex = None, *args, **kwargs) -> int:
return len(self.keys)
def headerData(
self, section: int, orientation: Qt.Orientation, role: Qt.ItemDataRole = None
) -> Any:
if role == Qt.DisplayRole:
# column headers
if orientation == Qt.Horizontal:
return self.headers[section]
# row headers
elif orientation == Qt.Vertical:
return section + 1
class FileRenameDelegate(QStyledItemDelegate):
def initStyleOption(self, option: QStyleOptionViewItem, index: QModelIndex) -> None:
super().initStyleOption(option, index)
option.textElideMode = Qt.ElideMiddle
def createEditor(
self, parent: QWidget, option: QStyleOptionViewItem, index: QModelIndex
) -> QWidget:
view: ImagesTableView = option.widget
model: ImagesTableModel = view.model()
path: str = model.data(index, Qt.EditRole)
path = Path(path)
abspath = model.basepath / Image.images_dir / path
dialog = QFileDialog(parent.window(), Qt.Dialog)
dialog.setWindowModality(Qt.ApplicationModal)
dialog.setMinimumWidth(800)
dialog.setMinimumHeight(600)
dialog.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.Dialog)
dialog.setAcceptMode(QFileDialog.AcceptSave)
dialog.setViewMode(QFileDialog.Detail)
dialog.setDirectory(str(abspath.parent))
dialog.selectFile(str(abspath.name))
dialog.setLabelText(QFileDialog.LookIn, "Rename image file")
return dialog
def setModelData(
self, editor: QWidget, model: QAbstractItemModel, index: QModelIndex
) -> None:
editor: QFileDialog
result: int = editor.result()
if result == QDialog.Accepted:
# if accepted, this means that the user also wanted to overwrite the file
dstPath: str = editor.selectedFiles()[0]
dstPath: Path = Path(dstPath)
model.setData(index, dstPath, Qt.EditRole)
class ImagesTableView(QTableView):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setSelectionMode(QAbstractItemView.SingleSelection)
self.setWordWrap(False)
horizontalHeader: QHeaderView = self.horizontalHeader()
horizontalHeader.setStretchLastSection(True)
class ImagesEditorView(QWidget):
def __init__(self, tableView: ImagesTableView):
super().__init__()
scrollArea = QScrollArea()
scrollArea.setWidget(tableView)
scrollArea.setWidgetResizable(True)
layout = QVBoxLayout()
layout.addWidget(scrollArea)
self.setLayout(layout)
class ImagesEditor(Editor):
log = logging.getLogger(__name__)
def __init__(self, model: ViewerModel):
super().__init__()
self.model = model
blocks = model.state.blocks
panels = model.state.panels
# set up Qt models/views
self.images_model = ImagesTableModel(model.path, model.state.images)
table_view = ImagesTableView()
table_view.setModel(self.images_model)
table_view.setColumnWidth(0, 300)
file_rename_delegate = FileRenameDelegate(parent=table_view)
block_names_delegate = NamesDelegate(blocks)
panel_names_delegate = NamesDelegate(panels)
table_view.setItemDelegateForColumn(0, file_rename_delegate)
table_view.setItemDelegateForColumn(1, block_names_delegate._view)
table_view.setItemDelegateForColumn(2, panel_names_delegate._view)
self._view = ImagesEditorView(table_view)
blocks.events.deleted.connect(lambda _: self._validate_block_names())
blocks.events.added.connect(lambda d: self._add_block_bindings(d["item"]))
for block in blocks:
self._add_block_bindings(block)
panels.events.deleted.connect(lambda _: self._validate_panel_names())
panels.events.added.connect(lambda d: self._add_panel_bindings(d["item"]))
for panel in panels:
self._add_panel_bindings(panel)
self.validate()
def _validate_block_names(self):
block_names = [block.name for block in self.model.state.blocks]
for image in self.model.state.images:
if image.block_name not in block_names:
image.block_name = ""
def _validate_panel_names(self):
panel_names = [panel.name for panel in self.model.state.panels]
for image in self.model.state.images:
if image.panel_name not in panel_names:
image.panel_name = ""
def _add_block_bindings(self, block: Block):
def update(old_name: str, new_name: str):
indexes_to_update = []
for i, image in enumerate(self.model.state.images):
if image.block_name == old_name:
image.block_name = new_name
indexes_to_update.append(i)
col = ImagesTableModel.keys.index("block_name")
for i in indexes_to_update:
index = self.images_model.index(i, col)
self.images_model.dataChanged.emit(index, index, [Qt.EditRole])
block.events.name.connect(lambda d: update(d["old"], d["new"]))
def _add_panel_bindings(self, panel: Panel):
def update(old_name: str, new_name: str):
indexes_to_update = []
for i, image in enumerate(self.model.state.images):
if image.panel_name == old_name:
image.panel_name = new_name
indexes_to_update.append(i)
col = ImagesTableModel.keys.index("panel_name")
for i in indexes_to_update:
index = self.images_model.index(i, col)
self.images_model.dataChanged.emit(index, index, [Qt.EditRole])
panel.events.name.connect(lambda d: update(d["old"], d["new"]))
def validate(self) -> None:
invalid_image_indexes = self.model.state.invalid_image_indexes()
self.is_valid = len(invalid_image_indexes) == 0
| StarcoderdataPython |
3238621 | <gh_stars>100-1000
import theano
import theano.tensor as T
import numpy as np
# predictions is the argmax of the posterior
def accuracy_instance(predictions, targets, n=[1, 2, 3, 4, 5, 10], \
nb_classes=5, nb_samples_per_class=10, batch_size=1):
accuracy_0 = theano.shared(np.zeros((batch_size, nb_samples_per_class), \
dtype=theano.config.floatX))
indices_0 = theano.shared(np.zeros((batch_size, nb_classes), \
dtype=np.int32))
batch_range = T.arange(batch_size)
def step_(p, t, acc, idx):
acc = T.inc_subtensor(acc[batch_range, idx[batch_range, t]], T.eq(p, t))
idx = T.inc_subtensor(idx[batch_range, t], 1)
return (acc, idx)
(raw_accuracy, _), _ = theano.foldl(step_, sequences=[predictions.dimshuffle(1, 0), \
targets.dimshuffle(1, 0)], outputs_info=[accuracy_0, indices_0])
accuracy = T.mean(raw_accuracy / nb_classes, axis=0)
return accuracy | StarcoderdataPython |
28113 | <filename>tensorflow/python/keras/distribute/mnist_multi_worker.py<gh_stars>1-10
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""An example training a Keras Model using MirroredStrategy and native APIs."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import flags
# pylint: disable=g-direct-tensorflow-import
from tensorflow.python import keras
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.distribute import collective_all_reduce_strategy as collective_strategy
from tensorflow.python.distribute import multi_worker_util
from tensorflow.python.distribute.cluster_resolver import TFConfigClusterResolver
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.keras import backend
from tensorflow.python.keras import utils
from tensorflow.python.keras.datasets import mnist
from tensorflow.python.keras.optimizer_v2 import rmsprop
from tensorflow.python.ops import math_ops
from tensorflow.python.platform import app
from tensorflow.python.platform import tf_logging as logging
NUM_CLASSES = 10
flags.DEFINE_boolean(name='enable_eager', default=False, help='Enable eager?')
flags.DEFINE_enum('distribution_strategy', None, ['multi_worker_mirrored'],
'The Distribution Strategy to use.')
flags.DEFINE_string('model_dir', None, 'Directory for TensorBoard/Checkpoint.')
# TODO(rchao): Use multi_worker_util.maybe_shard_dataset() once that is provided
# there.
def maybe_shard_dataset(dataset):
"""Shard the dataset if running in multi-node environment."""
cluster_resolver = TFConfigClusterResolver()
cluster_spec = cluster_resolver.cluster_spec().as_dict()
if cluster_spec:
dataset = dataset.shard(
multi_worker_util.worker_count(cluster_spec,
cluster_resolver.task_type),
multi_worker_util.id_in_cluster(
cluster_spec, cluster_resolver.task_type, cluster_resolver.task_id))
return dataset
def get_data_shape():
# input image dimensions
img_rows, img_cols = 28, 28
if backend.image_data_format() == 'channels_first':
return 1, img_rows, img_cols
else:
return img_rows, img_cols, 1
def get_input_datasets(use_bfloat16=False):
"""Downloads the MNIST dataset and creates train and eval dataset objects.
Args:
use_bfloat16: Boolean to determine if input should be cast to bfloat16
Returns:
Train dataset and eval dataset. The dataset doesn't include batch dim.
"""
cast_dtype = dtypes.bfloat16 if use_bfloat16 else dtypes.float32
# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()
train_data_shape = (x_train.shape[0],) + get_data_shape()
test_data_shape = (x_test.shape[0],) + get_data_shape()
if backend.image_data_format() == 'channels_first':
x_train = x_train.reshape(train_data_shape)
x_test = x_test.reshape(test_data_shape)
else:
x_train = x_train.reshape(train_data_shape)
x_test = x_test.reshape(test_data_shape)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
# convert class vectors to binary class matrices
y_train = utils.to_categorical(y_train, NUM_CLASSES)
y_test = utils.to_categorical(y_test, NUM_CLASSES)
# train dataset
train_ds = dataset_ops.Dataset.from_tensor_slices((x_train, y_train))
# TODO(rchao): Remove maybe_shard_dataset() once auto-sharding is done.
train_ds = maybe_shard_dataset(train_ds)
train_ds = train_ds.repeat()
train_ds = train_ds.map(lambda x, y: (math_ops.cast(x, cast_dtype), y))
train_ds = train_ds.batch(64, drop_remainder=True)
# eval dataset
eval_ds = dataset_ops.Dataset.from_tensor_slices((x_test, y_test))
# TODO(rchao): Remove maybe_shard_dataset() once auto-sharding is done.
eval_ds = maybe_shard_dataset(eval_ds)
eval_ds = eval_ds.repeat()
eval_ds = eval_ds.map(lambda x, y: (math_ops.cast(x, cast_dtype), y))
eval_ds = eval_ds.batch(64, drop_remainder=True)
return train_ds, eval_ds
def get_model(index=0):
"""Builds a Sequential CNN model to recognize MNIST digits.
Args:
index: The worker index. Defaults to 0.
Returns:
a CNN Keras model used for MNIST
"""
# Define a CNN model to recognize MNIST digits.
model = keras.models.Sequential()
model.add(
keras.layers.Conv2D(
32,
kernel_size=(3, 3),
activation='relu',
input_shape=get_data_shape()))
model.add(keras.layers.Conv2D(64, (3, 3), activation='relu'))
model.add(keras.layers.MaxPooling2D(pool_size=(2, 2)))
model.add(keras.layers.Dropout(0.25, name='dropout_worker%s_first' % index))
model.add(keras.layers.Flatten())
model.add(keras.layers.Dense(128, activation='relu'))
model.add(keras.layers.Dropout(0.5, name='dropout_worker%s_second' % index))
model.add(keras.layers.Dense(NUM_CLASSES, activation='softmax'))
return model
def main(_):
if flags.FLAGS.enable_eager:
ops.enable_eager_execution()
logging.info('Eager execution enabled for MNIST Multi-Worker.')
else:
logging.info('Eager execution not enabled for MNIST Multi-Worker.')
# Build the train and eval datasets from the MNIST data.
train_ds, eval_ds = get_input_datasets()
if flags.FLAGS.distribution_strategy == 'multi_worker_mirrored':
# MultiWorkerMirroredStrategy for multi-worker distributed MNIST training.
strategy = collective_strategy.CollectiveAllReduceStrategy()
else:
raise ValueError('Only `multi_worker_mirrored` is supported strategy '
'in Keras MNIST example at this time. Strategy passed '
'in is %s' % flags.FLAGS.distribution_strategy)
# Create and compile the model under Distribution strategy scope.
# `fit`, `evaluate` and `predict` will be distributed based on the strategy
# model was compiled with.
with strategy.scope():
model = get_model()
optimizer = rmsprop.RMSProp(learning_rate=0.001)
model.compile(
loss=keras.losses.categorical_crossentropy,
optimizer=optimizer,
metrics=['accuracy'])
# Train the model with the train dataset.
tensorboard_callback = keras.callbacks.TensorBoard(
log_dir=flags.FLAGS.model_dir)
model.fit(
x=train_ds,
epochs=20,
steps_per_epoch=468,
callbacks=[tensorboard_callback])
# Evaluate the model with the eval dataset.
score = model.evaluate(eval_ds, steps=10, verbose=0)
logging.info('Test loss:{}'.format(score[0]))
logging.info('Test accuracy:{}'.format(score[1]))
if __name__ == '__main__':
logging.set_verbosity(logging.INFO)
app.run()
| StarcoderdataPython |
6530528 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
------------------------------------
@Project : interfaceTest
@Time : 2021/3/8 14:16
@Auth : wrc
@Email : <EMAIL>
@File : test_login.py
@IDE : PyCharm
------------------------------------
"""
import allure
from api_doc.apis import Login
from common.Init import run_case
from utils.stroperate import String
@allure.feature('Login')
class TestLogin:
@allure.story('user login')
@allure.severity(allure.severity_level.BLOCKER)
@allure.title('正常登录测试')
@allure.testcase('http://www.baidu.com', '登录测试')
@allure.issue('http://www.baidu.com', "登录时接口报错")
def test_user_login(self):
param = {
"username": '<EMAIL>',
"password": String.transfer_md5('<PASSWORD>')
}
run_case(Login, 0, ['access_token', 'refresh_token'], param=param, params_type='form')
| StarcoderdataPython |
79406 | import argparse
import base64
import binascii
import json
import msgpack
import sys
__version__ = "0.0.1"
ACTION_VALIDATE = "validate"
ACTION_DECODE = "decode"
actions = (ACTION_DECODE, ACTION_VALIDATE)
parser = argparse.ArgumentParser(description='python msgpack native formatter %s' % __version__)
parser.add_argument('-v', '--version', action='version', version=__version__)
parser.add_argument('action', help="Available actions: %s" % str(actions))
parser.add_argument('value', help="Value encoded with base64")
def main():
args = parser.parse_args()
if args.action not in actions:
print("Error: Invalid action %s" % args.action)
sys.exit(1)
def process_error(msg):
if args.action == ACTION_VALIDATE:
return print(json.dumps({
"valid": False,
"message": msg
}))
else:
print(msg)
sys.exit(2)
try:
decoded_value = base64.b64decode(args.value)
except binascii.Error as e:
return process_error("Cannot decode value: %s" % e)
try:
unpacked_value = msgpack.unpackb(decoded_value, encoding='utf-8')
except msgpack.UnpackValueError as e:
return process_error("Cannot unpack value: %s" % e)
if args.action == ACTION_VALIDATE:
return print(json.dumps({
"valid": True,
"message": ""
}))
else:
return print(json.dumps({
"output": repr(unpacked_value),
"read-only": True,
"format": "plain_text",
}))
if __name__ == "__main__":
main()
| StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.