id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
1902926
<filename>delivery/client.py<gh_stars>0 import requests import gci.componentmodel as cm import ci.util class DeliveryServiceRoutes: def __init__(self, base_url: str): self._base_url = base_url def component_descriptor(self): return 'http://' + ci.util.urljoin( self._base_url, 'cnudie', 'component', ) class DeliveryServiceClient: def __init__(self, routes: DeliveryServiceRoutes): self._routes = routes def component_descriptor( self, name: str, version: str, ctx_repo_url: str, validation_mode: cm.ValidationMode=cm.ValidationMode.NONE, ): res = requests.get( url=self._routes.component_descriptor(), params={ 'component_name': name, 'version': version, 'ctx_repo_url': ctx_repo_url, }, ) res.raise_for_status() return cm.ComponentDescriptor.from_dict( res.json(), validation_mode=validation_mode, )
StarcoderdataPython
5171735
n = int(input()) result = ((n + n) * n - n) // n print(result)
StarcoderdataPython
6631765
<gh_stars>1-10 from kivy.app import App from kivy.uix.textinput import TextInput class SimpleApp(App): def build(self): t = TextInput(font_size=150) return t if __name__ == "__main__": SimpleApp().run()
StarcoderdataPython
3560396
<reponame>Extreme-classification/ECLARE<filename>ECLARE/libs/model.py from xclib.utils.sparse import topk, retain_topk import xclib.evaluation.xc_metrics as xc from .model_base import ModelBase import libs.features as feat import scipy.sparse as sp from sklearn.preprocessing import normalize import numpy as np import torch import time import os class ModelECLARE(ModelBase): def __init__(self, params, net, criterion, optimizer, *args, **kwargs): super(ModelECLARE, self).__init__(params, net, criterion, optimizer, *args, **kwargs) class ModelECLAREpp(ModelBase): def __init__(self, params, net, criterion, optimizer, *args, **kwargs): super(ModelECLAREpp, self).__init__(params, net, criterion, optimizer, *args, **kwargs) def get_lbl_cent(self, dataset): encoder = self.net._get_encoder() dataset.mode = "test" docs = normalize(self._doc_embed(dataset, 0, encoder, True)) dataset.mode = "train" y = dataset.labels.Y lbl_cnt = y.transpose().dot(docs) return lbl_cnt class ModelECLAREfe(ModelBase): def __init__(self, params, net, criterion, optimizer, *args, **kwargs): super(ModelECLAREfe, self).__init__(params, net, criterion, optimizer, *args, **kwargs) self.lbl_cnt = params.lbl_cnt def _prep_for_depth(self, depth, train_ds, valid_ds): torch.manual_seed(self.tree_idx) torch.cuda.manual_seed_all(self.tree_idx) np.random.seed(self.tree_idx) self.logger.info("learning for depth %d" % (depth)) train_ds.mode = 'test' self._prep_ds_for_depth(depth, train_ds, valid_ds) self.net.cpu() self.net._prep_for_depth(depth) print(self.net) if depth == 0: document = self._doc_embed(train_ds, 0, self.net.depth_node, True) train_ds.feature_type = "dense" train_ds.features = feat.construct("", "", document, False, "dense") document = self._doc_embed(valid_ds, 0, self.net.depth_node, True) valid_ds.feature_type = "dense" valid_ds.features = feat.construct("", "", document, False, "dense") self.learning_rate = self.lrs[depth] self.dlr_step = self.dlr_steps[depth] self.optimizer.learning_rate = self.lrs[depth] self.optimizer.construct(self.net.depth_node, None) train_ds.mode = 'train' return self._prep_dl_for_depth(depth, train_ds, valid_ds) def get_lbl_cent(self, dataset): encoder = self.net._get_encoder() dataset.mode = "test" docs = normalize(self._doc_embed(dataset, 0, encoder, True)) dataset.mode = "train" y = dataset.labels.Y lbl_cnt = normalize(y.transpose().dot(docs)) return lbl_cnt def predict(self, data_dir, model_dir, dataset, data=None, ts_feat_fname='tst_X_Xf.txt', ts_label_fname='tst_X_Y.txt', batch_size=256, num_workers=6, keep_invalid=False, feature_indices=None, label_indices=None, normalize_features=True, normalize_labels=False, **kwargs): self.net.load(fname=model_dir) dataset = self._create_dataset( os.path.join(data_dir, dataset), fname_features=ts_feat_fname, fname_labels=ts_label_fname, data=data, keep_invalid=keep_invalid, normalize_features=normalize_features, normalize_labels=normalize_labels, mode='test', feature_indices=feature_indices, label_indices=label_indices) encoder = self.net._get_encoder() docs = self._doc_embed(dataset, 0, encoder, True) dataset.feature_type = "dense" dataset.features = feat.construct("", "", docs, False, "dense") predicted_labels, _ = self._predict(dataset, model_dir, **kwargs) self._print_stats(dataset.labels.ground_truth, predicted_labels) return predicted_labels
StarcoderdataPython
244911
<filename>surf/rf.py # -*- coding: utf-8 -*- """ /*------------------------------------------------------* | Spatial Uncertainty Research Framework | | | | Author: <NAME>, UC Berkeley, <EMAIL> | | | | Date: 04/07/2019 | *------------------------------------------------------*/ """ from scipy.spatial.distance import squareform, cdist, pdist import numpy as np def getSIGMA( data, covfunc, n, N=0 ): # check dimensions of next if np.ndim( n ) == 1: n = [n] # check dimensions, make sure data and if(len(n[0]) != len(data[0,:])-1): print("Data dimension != input dimension!") print([len(n), len(data[0,:])-1]) exit() # get dnp d = cdist( data[:,:-1], n ) P = np.hstack(( data, d )) if N > 0: # use N nearest neighbor P = P[d[:,0].argsort()[:N]] else: # include all known data N = len(P) # get SIGMAnp SIGMA12 = covfunc( P[:,-1] ) SIGMA12 = np.matrix( SIGMA12 ).T # get SIGMApp dMatrix = squareform( pdist( P[:,:-2] ) ) SIGMA22 = np.array ( covfunc( dMatrix.ravel() ) ) SIGMA22 = SIGMA22.reshape(N,N) SIGMA22 = np.matrix( SIGMA22 ) return SIGMA22, SIGMA12, P def SK( data, covfunc, n, N = 0, nug = 0 ): # get matrix SIGMA22, SIGMA12 SIGMA22, SIGMA12, newData = getSIGMA( data, covfunc, n, N ) # calculate weights w = np.linalg.inv( SIGMA22 ) * SIGMA12 w = np.array( w ) # normalize to 1 w = np.dot(w, 1.0/np.sum(w)) # SIGMA21 * SIGMA22 * SIGMA12 k = SIGMA12.T * w # get original mean mu = np.mean( data[:,-1] ) # get the residuals residuals = newData[:,-2] - mu # best mean mu = np.dot( w.T, residuals ) + mu #mu = np.dot( w.T, newData[:,-2] ) # get sigma sill = np.var( data[:,-1] ) k = float( sill + nug - k ) std = np.sqrt( k ) return float(mu), std
StarcoderdataPython
1756405
<reponame>trachpro/Emotion_recognition<filename>test.py import numpy as np import cv2 import imutils import time from keras.preprocessing.image import img_to_array from keras.models import load_model import numpy as np detection_model_path = 'haarcascade_files/haarcascade_frontalface_default.xml' emotion_model_path = 'models/_mini_XCEPTION.102-0.66.hdf5' emotion_classifier = load_model(emotion_model_path, compile=False) EMOTIONS = ["angry" ,"disgust","scared", "happy", "sad", "surprised", "neutral"] face_detection = cv2.CascadeClassifier(detection_model_path) # camera = cv2.VideoCapture("C:/Users/TuPM/Downloads/Video/emotion_video.mkv") #Using video camera = cv2.VideoCapture(0) #using camera cv2.namedWindow('frame') while True: start_time = time.time() ret, frame = camera.read() frame = imutils.resize(frame,width=300) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = face_detection.detectMultiScale(gray,scaleFactor=1.1,minNeighbors=5,minSize=(30,30),flags=cv2.CASCADE_SCALE_IMAGE) canvas = np.zeros((250, 300, 3), dtype="uint8") frameClone = frame.copy() if len(faces) > 0: # for (x,y,w,h) in faces: # cv2.rectangle(gray, (x, y), (x+w, y+h), (0, 255, 0), 2) faces = sorted(faces, reverse=True, key=lambda x: (x[2] - x[0]) * (x[3] - x[1]))[0] # print(faces) (fX, fY, fW, fH) = faces roi = gray[fY: fY + fH, fX:fX + fW] roi = cv2.resize(roi, (64, 64)) roi = roi.astype("float") / 255.0 roi = img_to_array(roi) roi = np.expand_dims(roi, axis = 0) preds = emotion_classifier.predict(roi)[0] emotion_probability = np.max(preds) label = EMOTIONS[preds.argmax()] for i, (emotion, prob) in enumerate(zip(EMOTIONS, preds)): text = "{}: {:.2f}%".format(emotion, prob * 100) w = int(prob * 300) cv2.rectangle(canvas, (7, (i * 35) + 5), (w, (i * 35) + 35), (0, 0, 255), -1) cv2.putText(canvas, text, (10, (i * 35) + 23), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (255, 255, 255), 2) cv2.putText(frameClone, label, (fX, fY - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2) cv2.rectangle(frameClone, (fX, fY), (fX + fW, fY + fH), (0, 0, 255), 2) cv2.imshow('frame', frameClone) cv2.imshow("Probabilities", canvas) if cv2.waitKey(1) & 0xFF == ord('q'): break # print("FPS: ", 1.0 / (time.time() - start_time)) # print(len(faces)) camera.release() # cv2.distroyAllWindows()
StarcoderdataPython
1925658
<gh_stars>1-10 """Quantum Inspire library Copyright 2019 <NAME> qilib is available under the [MIT open-source license](https://opensource.org/licenses/MIT): 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. """ from typing import Optional, Type import numpy as np from qcodes.instrument_drivers.ZI.ZIUHFLI import ZIUHFLI from qilib.configuration_helper.adapters.common_instrument_adapter import CommonInstrumentAdapter from qilib.utils.python_json_structure import PythonJsonStructure class ZIUHFLIInstrumentAdapter(CommonInstrumentAdapter): def __init__(self, address: str, instrument_name: Optional[str] = None, instrument_class: Optional[Type[ZIUHFLI]] = None) -> None: super().__init__(address, instrument_name) if instrument_class is None: instrument_class = ZIUHFLI self._instrument: ZIUHFLI = instrument_class(self._instrument_name, device_ID=address) def _filter_parameters(self, parameters: PythonJsonStructure) -> PythonJsonStructure: for values in parameters.values(): if 'value' in values and isinstance(values['value'], np.int64): values['value'] = int(values['value']) if 'raw_value' in values and isinstance(values['raw_value'], np.int64): values['raw_value'] = int(values['raw_value']) if 'val_mapping' in values: values.pop('val_mapping') return parameters
StarcoderdataPython
3580129
from collections import Counter, defaultdict, OrderedDict li = [1, 2, 4, 3, 4, 4, 5, 6, 6, 7, 8] print(Counter(li)) # Counter({4: 3, 6: 2, 1: 1, 2: 1, 3: 1, 5: 1, 7: 1, 8: 1}) dict = defaultdict(int, {'a': 1, 'b': 2, 'c': 4}) print(dict['d']) # 0 dict2 = defaultdict(lambda: "value does not exist", {'a': 1, 'b': 2}) print(dict2['d']) # value does not exist dict3 = OrderedDict() products = {"3" : "banana", "1" : "apple", "5" : "potatoes"} for key, value in products.items(): dict3[key] = value print(dict3)
StarcoderdataPython
174559
def say(words): print words name = "this is a import demo"
StarcoderdataPython
9685955
<reponame>rgg81/Neural-Fictitous-Self-Play<filename>NFSP/workers/la/action_buffer/_ActionReservoirBufferBase.py # Copyright (c) 2019 <NAME> class ActionReservoirBufferBase: def __init__(self, env_bldr, max_size, min_prob): self._env_bldr = env_bldr self._max_size = max_size self._min_prob = min_prob # track self.size = 0 self.n_entries_seen = 0 def sample(self, batch_size, device): raise NotImplementedError def state_dict(self): raise NotImplementedError def load_state_dict(self, state): raise NotImplementedError class AvgMemorySaverBase: def __init__(self, env_bldr, buffer): self._env_bldr = env_bldr self._buffer = buffer def add_step(self, pub_obs, a, legal_actions_mask): raise NotImplementedError def reset(self, range_idx): raise NotImplementedError
StarcoderdataPython
6169
<reponame>canovasjm/InterviewProject_JuanCanovas #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Mar 1 18:17:07 2021 @author: jm """ # %% required libraries import numpy as np import pandas as pd from sqlalchemy import create_engine # %% connect to DB # create connection using pymssql engine = create_engine('mssql+pymssql://sa:<<PASSWORD>>@localhost:1433/rga') connection = engine.connect() # %% read data sets from where I will build the dimension tables # read employee roster data employee_roster = pd.read_excel("datasources/Employee_Roster_Data.xlsx", sheet_name = 'Sheet1') # read skills data skills = pd.read_excel("datasources/skills.xlsx", sheet_name = "Sheet1") # read hours data hours = pd.read_excel("datasources/hours.xlsx", sheet_name = "Sheet1") # %% dimensions created from source employee_roster # %% create DIM_Currency # get unique values currencies = sorted(employee_roster['Currency'].unique()) # create a data frame DIM_Currency = pd.DataFrame({'id_currency': (np.arange(len(currencies)) + 1), 'currency': currencies}) # send data frame to DB DIM_Currency.to_sql('DIM_Currency', con = connection, if_exists = 'append', index = False) # %% create DIM_Department # get unique values departments = sorted(pd.concat([employee_roster['Department'], skills['Department']], axis = 0).unique()) # create a data frame DIM_Department = pd.DataFrame({'id_department': (np.arange(len(departments)) + 1), 'department': departments}) # send data frame to DB DIM_Department.to_sql('DIM_Department', con = connection, if_exists = 'append', index = False) # %% create DIM_Gender # get unique values genders = sorted(pd.concat([employee_roster['Gender'], skills['Gender']], axis = 0).unique()) # create a data frame DIM_Gender = pd.DataFrame({'id_gender': (np.arange(len(genders)) + 1), 'gender': genders}) # send data frame to DB DIM_Gender.to_sql('DIM_Gender', con = connection, if_exists = 'append', index = False) # %% create DIM_User # check if 'UserId' values in 'skills' are in 'User_ID' in 'employee_roster' # we get 20134 'True' values, meaning that all 'UserId' in 'skills' are already # in 'User_ID' in employee_roster users_check_1 = np.isin(skills['UserId'], employee_roster['User_ID']).sum() # check if 'UserId' values in 'hours' are in 'User_ID' in 'employee_roster' # we get 7659 'True' values, meaning that NOT all 'UserId' in 'hours' are already # in 'User_ID' in employee_roster users_check_2 = np.isin(hours['UserId'], employee_roster['User_ID']).sum() # get unique values users = sorted(pd.concat([employee_roster['User_ID'], skills['UserId'], hours['UserId']], axis = 0).unique()) # create a data frame to use pd.merge() df_users = pd.DataFrame({'User_ID': users}) # left join 'df_user' with 'employee_roster' on 'UserID' users_final = pd.merge(df_users, employee_roster, on = 'User_ID', how ='left') # select only columns I need users_final = users_final[['User_ID', 'Email_ID', 'Fullname']] # rename columns users_final.rename(columns = {'User_ID': 'id_user', 'Email_ID': 'id_email', 'Fullname': 'fullname'}, inplace = True) # send data frame to DB users_final.to_sql('DIM_User', con = connection, if_exists = 'append', index = False) # %% dimensions created from source skills # %% create DIM_AttributeGroup # get unique values att_group = sorted(skills['Attribute Group'].unique()) # create a data frame DIM_AttributeGroup = pd.DataFrame({'id_att_group': (np.arange(len(att_group)) + 1), 'attribute_group': att_group}) # send data frame to DB DIM_AttributeGroup.to_sql('DIM_AttributeGroup', con = connection, if_exists = 'append', index = False) # %% create DIM_AttributeSubGroup # get unique values att_sub_group = sorted(skills['Attribute Sub-Group'].unique()) # create a data frame DIM_AttributeSubGroup = pd.DataFrame({'id_att_sub_group': (np.arange(len(att_sub_group)) + 1), 'attribute_sub_group': att_sub_group}) # send data frame to DB DIM_AttributeSubGroup.to_sql('DIM_AttributeSubGroup', con = connection, if_exists = 'append', index = False) # %% create DIM_AttributeName # get unique values att_name = sorted(skills['Attribute Name'].unique()) # create a data frame DIM_AttributeName = pd.DataFrame({'id_att_name': (np.arange(len(att_name)) + 1), 'attribute_name': att_name}) # send data frame to DB DIM_AttributeName.to_sql('DIM_AttributeName', con = connection, if_exists = 'append', index = False)
StarcoderdataPython
11385140
from __future__ import print_function import argparse import logging from trekipsum import dialog, markov logger = logging.getLogger(__name__) def positive(value): """Type check value is a natural number (positive nonzero integer).""" value = int(value) if value < 1: raise ValueError() return value def parse_cli_args(): """Parse command-line arguments.""" parser = argparse.ArgumentParser(description='TrekIpsum generator') parser.add_argument('-m', '--markov', action='store_true', help='use markov chain mode for generation') parser.add_argument('--speaker', type=str, help='limit output to this speakers') parser.add_argument('-a', '--attribute', action='store_true', help='include speaker attribution') parser.add_argument('-n', '--paragraphs', type=positive, default=3, help='number of paragraphs to output (default: %(default)s)') parser.add_argument('-s', '--sentences', type=positive, default=4, help='number of sentences per paragraph (default: %(default)s)') parser.add_argument('--debug', action='store_true', help='enable debug logging') return parser.parse_args() def print_dialog(line, speaker, show_speaker=False): """Print the line and speaker, formatted appropriately.""" if show_speaker: speaker = speaker.title() print('{} -- {}'.format(line.__repr__(), speaker)) else: print(line) def main_cli(): """Execute module as CLI program.""" args = parse_cli_args() loglevel = logging.DEBUG if args.debug else logging.CRITICAL logging.basicConfig(level=loglevel, format='%(asctime)s %(levelname)s: %(message)s') logger.setLevel(loglevel) if args.markov is True: chooser = markov.MarkovRandomChooser() else: chooser = dialog.SqliteRandomChooser() for paragraph in range(args.paragraphs): speaker = args.speaker lines = [] for __ in range(args.sentences): speaker, line = chooser.random_dialog(speaker) lines.append(line) print_dialog(' '.join(set(lines)), speaker, args.attribute) if paragraph < args.paragraphs - 1: print() # padding between paragraphs
StarcoderdataPython
1981645
import textgrid import sys def cut(input): tg = textgrid.TextGrid() tg.read(input) # print(tg.tiers[0].minTime, tg.tiers[0].maxTime) # nums = len(tg.tiers[0].intervals) intervals = tg.tiers[0].intervals start = tg.tiers[0].minTime end = tg.tiers[0].maxTime if intervals[0].mark == 'silence': start = intervals[0].bounds()[1] if intervals[-1].mark == 'silence': end = intervals[-1].bounds()[0] print(start, end) # for interval in tg.tiers[0].intervals: # print(interval.bounds(), interval.mark) if __name__ == '__main__': input_tg = sys.argv[1] cut(input_tg)
StarcoderdataPython
3409739
import os from typing import Generator from unittest.mock import patch import pytest from twitterapiv2.appauth_client import AppAuthClient from tests.fixtures.mock_http import MockHTTP MOCK_KEY = "<KEY>" MOCK_SECRET = "<KEY>" MOCK_CRED = "eHZ6MWV2RlM0d0VFUFRHRUZQSEJvZzpMOHFxOVBaeVJnNmllS0dFS2hab2xHQzB2SldMdzhpRUo4OERSZHlPZw==" # noqa: E501 MOCK_RESP = '{"token_type":"bearer","access_token":"<PASSWORD>"}' # noqa: E501 BAD_REQUEST = '{"errors":[{"code":99,"message":"Unable to verify your credentials","label":"authenticity_token_error"}]}' # noqa: 501 BAD_RESPONSE = '{"token_type":"bearer"}' @pytest.fixture def client() -> Generator[AppAuthClient, None, None]: appclient = AppAuthClient() with patch.object(appclient, "http", MockHTTP()): yield appclient def test_encoded_credentials() -> None: client = AppAuthClient() env = { "TW_CONSUMER_KEY": MOCK_KEY, "TW_CONSUMER_SECRET": MOCK_SECRET, } with patch.dict(os.environ, env): result = client.encoded_credentials() assert result == MOCK_CRED def test_require_environ_vars() -> None: client = AppAuthClient() os.environ.pop("TW_CONSUMER_KEY", None) with pytest.raises(KeyError): client.encoded_credentials() os.environ["TW_CONSUMER_KEY"] = "Mock" os.environ.pop("TW_CONSUMER_SECRET", None) with pytest.raises(KeyError): client.encoded_credentials() def test_set_bearer_token(client: AppAuthClient) -> None: client.http.add(client.twitter_api + "/oauth2/token", MOCK_RESP, 200) client.set_bearer_token() assert os.getenv("TW_BEARER_TOKEN") is not None def test_fetch_bearer_token(client: AppAuthClient) -> None: client.http.add(client.twitter_api + "/oauth2/token", MOCK_RESP, 200) client.fetch_bearer_token() assert os.getenv("TW_BEARER_TOKEN") is None def test_invalid_bearer_request(client: AppAuthClient) -> None: client.http.add(client.twitter_api + "/oauth2/token", BAD_REQUEST, 403) with pytest.raises(ValueError): client.set_bearer_token() def test_invalid_bearer_response(client: AppAuthClient) -> None: client.http.add(client.twitter_api + "/oauth2/token", BAD_RESPONSE, 200) with pytest.raises(ValueError): client.set_bearer_token()
StarcoderdataPython
6588412
<filename>api/serializers.py from .models import Home from rest_framework import serializers class HomeSerializer(serializers.HyperlinkedModelSerializer): unpublished_page_data = serializers.CharField(required=False, allow_null=True, allow_blank=True) class Meta: model = Home fields = ('guid', 'page_data', 'unpublished_page_data', 'meta_data')
StarcoderdataPython
6698315
<filename>start_training_with_all_avaliable_gpus/start.py #-*-coding:utf-8-*- import sys import os import json import numpy as np import multiprocessing import datetime import pynvml from pynvml import * nvmlInit() MEMORY_THESHOLD = 15 # GB def get_aviliable_gpus(): print ("Driver Version:", nvmlSystemGetDriverVersion()) deviceCount = nvmlDeviceGetCount() GPU_AVILIABLE=[] for i in range(deviceCount): handle = nvmlDeviceGetHandleByIndex(i) meminfo = pynvml.nvmlDeviceGetMemoryInfo(handle) memo_total = meminfo.total/(1024*1024*1024) memo_used = meminfo.used/(1024*1024*1024) if memo_total>=MEMORY_THESHOLD and memo_used/memo_total<=0.2: GPU_AVILIABLE.append(i) if len(GPU_AVILIABLE)==0: print('No GPU Is Avilable!') sys.exit(0) else: print('Avilable GPUS:',GPU_AVILIABLE) return GPU_AVILIABLE def get_search_space(cfg_path='search_space.json'): if not os.path.isfile(cfg_path): print('Cannot find search space file:{}'.format(cfg_path)) sys.exit(0) search_space = json.loads(open(cfg_path,'r').read()) print('search space\n:',search_space) return search_space def get_params(search_space): params={} for k,v in search_space.items(): if v["type"] == "uniform": value = np.random.uniform(v["value"][0],v["value"][1]) elif v["type"] == "choice": value = np.random.choice(v["value"],1) params[k] = value[0] if isinstance(value,np.ndarray) else value return params def start_running(*args,**kwargs): GPU_ID = int(args[0]) print('start run train.py on GPU_ID:',GPU_ID) learning_rate = kwargs['learning_rate'] batch_size = kwargs['batch_size'] optimizer = kwargs['optimizer'] max_number_of_steps = kwargs['max_number_of_steps'] learning_rate_decay_type = kwargs['learning_rate_decay_type'] print('pid:',os.getpid(),'running config:\nlearning rate:',learning_rate,'batch_size:',batch_size,'optimizer:',optimizer,'max_num_of_steps:',max_number_of_steps,'learning_rate_decay_type:',learning_rate_decay_type) today = datetime.date.today() checkpoint_dir = '{}/{}'.format(today,os.getpid()) try: os.makedirs(checkpoint_dir) except OSError: if not os.path.isdir(checkpoint_dir): raise os.popen('CUDA_VISIBLE_DEVICES={} python train.py --batch_size={} --max_number_of_steps={} --learning_rate={} --optimizer={} --checkpoint_dir={} --learning_rate_decay_type={}'.format(GPU_ID,batch_size,max_number_of_steps,learning_rate,optimizer,checkpoint_dir,learning_rate_decay_type),mode='w') if __name__=='__main__': GPU_AVILIABLE = get_aviliable_gpus() search_space = get_search_space('search_space.json') pp1=[multiprocessing.Process(target = start_running,args=(str(GPU_ID)),kwargs=get_params(search_space)) for i,GPU_ID in enumerate(GPU_AVILIABLE)] for p in pp1: p.start() for p in pp1: p.join()
StarcoderdataPython
3223576
from pyspark import SparkContext, SparkConf, SparkFiles from pyspark.sql import SQLContext, Row import configparser import os from vina_utils import get_files_log from json_utils import create_jsondata_from_docking_output_file, create_json_file from os_utils import make_directory def log_to_json(log_file): path_to_save = path_to_save_b.value log_file_name = str(log_file) splited = log_file_name.split('/') json_name = splited[-1].replace('log', 'json') key_name = json_name.split('.')[0] json_data = create_jsondata_from_docking_output_file(log_file) json_final_data = {key_name: json_data} json_name = os.path.join(path_to_save, json_name ) create_json_file(json_name, json_final_data) if __name__ == '__main__': config = configparser.ConfigParser() config.read('config.ini') sc = SparkContext() sqlCtx = SQLContext(sc) log_file = config.get('DEFAULT', 'path_save_log') path_to_save = config.get('DEFAULT', 'json_log') path_spark_drugdesign = config.get('DRUGDESIGN', 'path_spark_drugdesign') sc.addPyFile(os.path.join(path_spark_drugdesign,"vina_utils.py")) sc.addPyFile(os.path.join(path_spark_drugdesign,"json_utils.py")) sc.addPyFile(os.path.join(path_spark_drugdesign,"os_utils.py")) #Broadcast log_file_b = sc.broadcast(log_file) path_to_save_b = sc.broadcast(path_to_save) make_directory(path_to_save) all_log_files = get_files_log(log_file) log_filesRDD = sc.parallelize(all_log_files) log_filesRDD.foreach(log_to_json)
StarcoderdataPython
5077330
<reponame>RAVIKANT-YADAV/AI-based-Digital-Voice.-assistance import speak_Function as sf import wikipedia def wikipedia_query(): if 'wikipedia' in query: sf.speak("Searching............") query = query.replace("wikipedia", "") results = wikipedia.summary(query, sentences=2) sf.speak("According to wikipedia") print(results) sf.speak(results)
StarcoderdataPython
148155
<reponame>ir4n6/aws-security-automation # MIT No Attribution # 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. # 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. import boto3 import json import logging import os from base64 import b64decode from urllib.request import Request, urlopen from urllib.error import URLError, HTTPError client = boto3.client('s3') HOOK_URL = os.environ['HookUrl'] # The Slack channel to send a message to stored in the slackChannel environment variable SLACK_CHANNEL = os.environ['SlackChannel'] logger = logging.getLogger() logger.setLevel(logging.INFO) def lambda_handler(event, context): instanceID = event['instanceID'] targetGroupArn = event['targetGroupArn'] slack_message_text = formatMyMessage(instanceID, targetGroupArn) # slack_message_text = response req = Request(HOOK_URL, json.dumps(slack_message_text).encode('utf-8')) try: response = urlopen(req) response.read() logger.info("Message posted to %s", SLACK_CHANNEL) except HTTPError as e: logger.error("Request failed: %d %s", e.code, e.reason) except URLError as e: logger.error("Server connection failed: %s", e.reason) return event def formatMyMessage(instanceID, targetGroupArn): slack_message = { "attachments": [ { "fallback": "Required plain-text summary of the attachment.", "color": "#b7121a", "title": "High Alert!! \n Security Incident detected \n Instance Isolated due to security incident detected by guard duty from ALB : " + instanceID , "text": "", "fields":[{ "value": "Next Steps : " + '\n 1. Snapshot of the volume will be created \n 2. Snapshot will be mounted into volume for Forsensic Analysis \n 3. New Forensic Instance will be created and the volume will be mounted for forensic analysis \n 4. Forensic report will sent to security channel' }, { "value": "Instance under isolation: " + instanceID }, { "value": "TargetGroup ARN where instance is drained from : " + targetGroupArn }] } ] } return slack_message
StarcoderdataPython
6627865
<gh_stars>1-10 # -*- coding: utf-8 -*- """Check the application dependencies.""" import sys from pineboolib.core.utils import logging from pineboolib.core.utils.utils_base import is_deployed from pineboolib.core.utils.check_dependencies import get_dependency_errors from pineboolib.core.utils.check_dependencies import DependencyCheck, DependencyError from pineboolib.application import project logger = logging.getLogger(__name__) def check_dependencies(dict_: DependencyCheck, exit: bool = True) -> bool: """ Check if a package is installed and return the result. @param dict_. Dict with the name of the agency and the module to be checked. @param exit . Exit if dependence fails. """ dep_error: DependencyError = get_dependency_errors(dict_) if not dep_error: return True msg = "" logger.debug("Error trying to import modules:\n%s", "\n\n".join(dep_error.values())) logger.warning("Unmet dependences:") for (dep, suggestedpkg), errormsg in dep_error.items(): logger.warning("Install package %s for %s", suggestedpkg, dep) msg += "Instale el paquete %s.\n%s" % (suggestedpkg, errormsg) if dep == "pyfpdf": msg += "\n\n\n Use pip3 install -i https://test.pypi.org/simple/ pyfpdf==1.7.3" if exit: if project.DGI.useDesktop() and project.DGI.localDesktop(): from pineboolib.qt3_widgets.messagebox import MessageBox MessageBox.warning(None, "Pineboo - Dependencias Incumplidas -", msg, MessageBox.Ok) if not is_deployed(): sys.exit(32) return False
StarcoderdataPython
3347874
<filename>neural_spline_flows/nde/transforms/svd.py<gh_stars>0 import numpy as np import torch from torch import nn from torch.nn import init from neural_spline_flows.nde import transforms from neural_spline_flows.nde.transforms.linear import Linear class SVDLinear(Linear): """A linear module using the SVD decomposition for the weight matrix.""" def __init__(self, features, num_householder, using_cache=False): super().__init__(features, using_cache) # First orthogonal matrix (U). self.orthogonal_1 = transforms.HouseholderSequence( features=features, num_transforms=num_householder) # Logs of diagonal entries of the diagonal matrix (S). self.log_diagonal = nn.Parameter(torch.zeros(features)) # Second orthogonal matrix (V^T). self.orthogonal_2 = transforms.HouseholderSequence( features=features, num_transforms=num_householder) self._initialize() def _initialize(self): stdv = 1.0 / np.sqrt(self.features) init.uniform_(self.log_diagonal, -stdv, stdv) init.constant_(self.bias, 0.0) def forward_no_cache(self, inputs): """Cost: output = O(KDN) logabsdet = O(D) where: K = num of householder transforms D = num of features N = num of inputs """ outputs, _ = self.orthogonal_2(inputs) # Ignore logabsdet as we know it's zero. outputs *= torch.exp(self.log_diagonal) outputs, _ = self.orthogonal_1(outputs) # Ignore logabsdet as we know it's zero. outputs += self.bias logabsdet = self.logabsdet() * torch.ones(outputs.shape[0]) return outputs, logabsdet def inverse_no_cache(self, inputs): """Cost: output = O(KDN) logabsdet = O(D) where: K = num of householder transforms D = num of features N = num of inputs """ outputs = inputs - self.bias outputs, _ = self.orthogonal_1.inverse(outputs) # Ignore logabsdet since we know it's zero. outputs *= torch.exp(-self.log_diagonal) outputs, _ = self.orthogonal_2.inverse(outputs) # Ignore logabsdet since we know it's zero. logabsdet = -self.logabsdet() logabsdet = logabsdet * torch.ones(outputs.shape[0]) return outputs, logabsdet def weight(self): """Cost: weight = O(KD^2) where: K = num of householder transforms D = num of features """ diagonal = torch.diag(torch.exp(self.log_diagonal)) weight, _ = self.orthogonal_2.inverse(diagonal) weight, _ = self.orthogonal_1(weight.t()) return weight.t() def weight_inverse(self): """Cost: inverse = O(KD^2) where: K = num of householder transforms D = num of features """ diagonal_inv = torch.diag(torch.exp(-self.log_diagonal)) weight_inv, _ = self.orthogonal_1(diagonal_inv) weight_inv, _ = self.orthogonal_2.inverse(weight_inv.t()) return weight_inv.t() def logabsdet(self): """Cost: logabsdet = O(D) where: D = num of features """ return torch.sum(self.log_diagonal)
StarcoderdataPython
8158698
STATION_TABLE = [] from itertools import combinations import numpy as np class Scheduler: def __init__(self, total, n, p, alpha, beta): # self.opt = opt self.station_num = n self.time = p self.total = total self.station_table = init_table(n, p) self.alpha = alpha self.beta = beta self.last_assignment = np.array([0] * n) self.virtual_model = init_table(n, p) self.last_q = 0 self.w1 = 1.0 def naive_scheduler(self, sample_matrix, usage_vector): # not related to sample_matrix assignment = [int(x / sum(usage_vector) * self.total) for x in usage_vector] assignment[-1] = self.total - sum(assignment[:-1]) self.last_assignment = assignment return assignment def greedy_scheduler(self, true_model_sample, usage_vector): self.virtual_model = np.ceil(self.alpha * self.virtual_model + (1-self.alpha) *true_model_sample) # print(self.virtual_model) # extract feature from virtual model. # print(true_model_sample.size) # print(usage_vector.size) if sum(self.last_assignment) == 0: temp_ass = np.ones((1, self.station_num)) * int(self.total / self.station_num) self.last_assignment = temp_ass[0] return self.last_assignment else: f, Q_val = Q(self.virtual_model, self.last_assignment, self.w1) # print("compute %d", Q_val) true_rewards = sum(usage_vector) diff = true_rewards - Q_val self.w1 = self.w1 + self.beta*diff*f[0] # self.w1 = 1 # find action(generating) # print(self.w1) action_candidate = [self.last_assignment / sum(self.last_assignment)] for _ in range(34): # print(self.last_assignment.shape) random_vct = np.abs(np.random.randn(self.last_assignment.shape[0])) # print(random_vct.shape) action_candidate.append(random_vct / sum(random_vct)) for iter in range(6): # print("iter") action_candidate = generation(action_candidate, self.virtual_model, self.total, self.w1) # print(action_candidate) action_candidate = ooxx(action_candidate) # print(action_candidate) # print(1, ) # print("after generation") assignment = action_candidate[0] self.last_assignment = assignment # print(assignment) return assignment def generation(cdd, vm, total, w): action = [] qvals = np.array([0] * 20).astype(float) for i in range(20): action_now = normalize_with_weight(cdd[i], total) f, Qval = Q(vm, action_now, w) qvals[i] = Qval action.append(action_now) index = (np.argsort(qvals)) action_ooxx = [] for i in range(5): action_ooxx.append(action[index[19 - i]]) # print(max(qvals), end='->') return action_ooxx def random_seq(a, b, n): s = [] while(len(s) < n): x = np.random.randint(a, b) if x not in s: s.append(x) return s def ooxx(tobe_ooxx): change_number = 5 new_candidate = [] for cdd in tobe_ooxx: new_candidate.append(cdd.copy()) for comb in combinations(tobe_ooxx, 2): rand_seq = random_seq(0, comb[0].shape[0], change_number) for j in rand_seq: temp = comb[0][j] comb[0][j] = comb[1][j] comb[1][j] = temp new_candidate.append(comb[0].copy()) new_candidate.append(comb[1].copy()) return new_candidate def Q(vm, a, w): f1 = sum(simulate(vm, a)) return [f1], w*f1 def normalize_with_weight(vet, total): temp = np.floor(vet / sum(vet) * total) temp[-1] = total - sum(temp[:-1]) return temp def simulate(model, assignment): usage = np.zeros(assignment.shape) left = assignment.astype('float64') for t in range(model.shape[0]): trans_matrix = model[t] # print(trans_matrix) buffer = np.zeros(assignment.shape) for i in range(model.shape[1]): # maybe leave total_leave = min(left[i], sum(trans_matrix[i])) # print(total_leave) if (sum(trans_matrix[i]) == 0): continue temp_trans = np.floor(trans_matrix[i] / sum(trans_matrix[i]) * total_leave) temp_trans[-1] = (total_leave - sum(temp_trans[:-1])) # print(sum(temp_trans) == total_leave) left[i] -= total_leave for j in range(model.shape[1]): # print(buffer, temp_trans[i]) buffer[j] += temp_trans[j] usage += buffer # print(sum(buffer)) left += buffer # print(sum(left), sum(buffer)) return usage def init_table(n, p): return np.ones((p, n, n)) * 100 def main(): alpha = 0.9 sche = Scheduler(10000, 10, 72, alpha) sample_matrix = init_table(10, 72) usage_vector = np.array([100] * 10) usage_vector[0] = 0 print(usage_vector) sample_matrix[:, 0, :] = 0 # print(sample_matrix[0]) # print(simulate(sample_matrix, usage_vector)) sche.greedy_scheduler(sample_matrix, usage_vector) sche.greedy_scheduler(sample_matrix, usage_vector) sche.greedy_scheduler(sample_matrix, usage_vector) sche.greedy_scheduler(sample_matrix, usage_vector) sche.greedy_scheduler(sample_matrix, usage_vector) sche.greedy_scheduler(sample_matrix, usage_vector) sche.greedy_scheduler(sample_matrix, usage_vector) sche.greedy_scheduler(sample_matrix, usage_vector) sche.greedy_scheduler(sample_matrix, usage_vector) sche.greedy_scheduler(sample_matrix, usage_vector) sche.greedy_scheduler(sample_matrix, usage_vector) sche.greedy_scheduler(sample_matrix, usage_vector) if __name__ == '__main__': main() # a = np.array([1, 2, 3, 4, 5, 3, 4, 5, 6, 7, 7, 8, 9]) # b = np.array([2, 3, 4, 5, 6, 7, 7, 8, 9, 9, 0, 0, 1]) # c = np.array([0, 7, 2, 5, 6, 7, 7, 5, 6, 7, 7, 8, 9]) # for i in (ooxx([a, b, c])): # print(i)
StarcoderdataPython
4827732
<reponame>Zbot21/zcoins<filename>zcoins/exchanges/exchange.py # This file contains the interface that should be implemented by an exchange. from __future__ import annotations from abc import ABC, abstractmethod from dataclasses import dataclass from typing import Text, Callable, Union from zcoins.exchanges import OrderSide, OrderReport, OrderType, Product, TickerMessage from zcoins.exchanges import Account class ExchangeProductInfo(ABC): @classmethod @abstractmethod def make_product_id(cls, base_currency, quote_currency) -> Text: pass def get_quote_currency(self, product_id: Text) -> Text: """Given a product_id, return the quote_currency.""" return self.get_product(product_id).quote_currency def get_base_currency(self, product_id: Text) -> Text: """Given a product_id, return the base_currency.""" return self.get_product(product_id).base_currency @abstractmethod def get_all_products(self) -> list[Product]: pass @abstractmethod def get_product(self, product_id: Text) -> Product: pass class Exchange(ExchangeProductInfo, ABC): """Contains information about an exchange.""" def __init__(self, name: Text, order_books): self.name = name self.order_books = order_books @dataclass class _TickerCallback: callback: Callable[[Union[Exchange, AuthenticatedExchange], TickerMessage], None] product_matcher: Product = None # By Default, this matches all products. @abstractmethod def add_ticker_callback(self, callback: Callable[[Exchange, TickerMessage], None]) -> Text: """Adds a callback function to this exchange.""" def get_product_ids(self): """Get all product ids available on this exchange, this is not necessarily all *available* products, but only the products that are being tracked by the MultiProductOrderBook contained in this Exchange.""" return self.order_books def add_order_book(self, product_id: Text): """Adds an order book""" return self.order_books.add_order_book(product_id) def get_all_order_books(self): """Returns a MultiProductOrderBook representing all products that are currently being followed.""" return self.order_books def get_order_book(self, product_id): """Returns a SingleProductOrderBook for the given product_id.""" return self.order_books.get_order_book(product_id) def get_order_book_by_base_currency(self, base_currency): """Returns a dict of SingleProductOrderBook using base_currency keyed by quote_currency.""" return self.order_books.get_order_books_by_base_currency(base_currency) def get_order_book_by_quote_currency(self, quote_currency): """Returns a dict of SingleProductOrderBook using quote_currency, keyed by base_currency.""" return self.order_books.get_order_books_by_quote_currency(quote_currency) def get_order_book_by_currencies(self, base_currency, quote_currency): """Returns a SingleProductOrderBook for the given base and quote currencies.""" return self.get_order_book(self.make_product_id(base_currency=base_currency, quote_currency=quote_currency)) class AuthenticatedExchange(Exchange, ABC): """Contains an exchange that you can make trades on.""" def __init__(self, name: Text, order_books): super().__init__(name, order_books) @abstractmethod def get_all_accounts(self) -> list[Account]: """Get all the 'accounts' (currency balances) on this exchange.""" pass @abstractmethod def get_account(self, currency: Text = None, account_id: Text = None) -> Account: """Can get an account either by account_id or by the currency, it's invalid to specify both.""" pass @abstractmethod def cancel_order(self, order_id: Text, product_id: Text = None): """Cancel an order with exchange-provided order id.""" pass @abstractmethod def limit_order(self, product_id: Text, side: OrderSide, price, size) -> OrderReport: """Posts a limit order.""" pass @abstractmethod def market_order(self, product_id: Text, side: OrderSide, size=None, funds=None) -> OrderReport: """Posts a market order.""" pass
StarcoderdataPython
3405530
<reponame>tobyatgithub/PythonDataStructureAndAlgo """ Similar to maxheap, here we have a class for min heap. Implementing via array """ class minHeap(): def __init__(self, A, DEBUG=False): self.A = A self.LEN = len(A) self.DEBUG = DEBUG self.buildMinHeap() def getLeftIndex(self, k): return 2 * k + 1 def getRightIndex(self, k): return 2 * k + 2 def minHeapify(self, k): l = self.getLeftIndex(k) r = self.getRightIndex(k) if l < self.LEN and self.A[l] < self.A[k]: smallest = l else: smallest = k if r < self.LEN and self.A[r] < self.A[smallest]: smallest = r if self.DEBUG: print(f"minHeapify: k = {k}, A[k] = {self.A[k]}, A = {self.A}.") print(f"minHeapify: l = {l}, r = {r}, smallest = {smallest}.") if k != smallest: self.A[k], self.A[smallest] = self.A[smallest], self.A[k] self.minHeapify(smallest) def buildMinHeap(self): n = int(self.LEN // 2) - 1 for i in range(n, -1, -1): self.minHeapify(i) def __str__(self): return str(self.A) array = [3, 9, 2, 1, 4, 5] test = minHeap(array, True) print(test)
StarcoderdataPython
314470
import pytest import json from runeatest import testreporter def test_add_all_passed_test_cases(mocker): x = '{"tags": {"opId": "ServerBackend-f421e441fa310430","browserUserAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36","orgId": "1009391617598028","userAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36","clusterId": "0216-124733-lone970","user": "<EMAIL>","principalIdpObjectId": "71b45910-e7b4-44d8-82f7-bf6fac4630d0","browserHostName": "uksouth.azuredatabricks.net","parentOpId": "RPCClient-bb9b9591c29c01f7","jettyRpcType": "InternalDriverBackendMessages$DriverBackendRequest"},"extraContext":{"notebook_path":"/Users/lorem.ipsum@fake.io/runeatest"}}' context = json.loads(x) mocker.patch("runeatest.pysparkconnect.get_context", return_value=context) actual = [] actual.append( testreporter.add_testcase( "test name", True, "this test will check that something will work" ) ) actual.append( testreporter.add_testcase( "test name 2", True, "this test also will check that something will work" ) ) expected = [ { "test": "test name", "issuccess": "True", "description": "this test will check that something will work", "classname": "/Users/lorem.ipsum@fake.io/runeatest", "result": "success", "failurereason": "", }, { "test": "test name 2", "issuccess": "True", "description": "this test also will check that something will work", "classname": "/Users/lorem.ipsum@fake.io/runeatest", "result": "success", "failurereason": "", }, ] assert expected == actual def test_add_passed_test_case(mocker): x = '{"tags": {"opId": "ServerBackend-f421e441fa310430","browserUserAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36","orgId": "1009391617598028","userAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36","clusterId": "0216-124733-lone970","user": "<EMAIL>","principalIdpObjectId": "71b45910-e7b4-44d8-82f7-bf6fac4630d0","browserHostName": "uksouth.azuredatabricks.net","parentOpId": "RPCClient-bb9b9591c29c01f7","jettyRpcType": "InternalDriverBackendMessages$DriverBackendRequest"},"extraContext":{"notebook_path":"/Users/lorem.ipsum@fake.io/runeatest"}}' context = json.loads(x) mocker.patch("runeatest.pysparkconnect.get_context", return_value=context) actual = [] actual.append( testreporter.add_testcase( "test name", True, "this test will check that something will work" ) ) expected = [ { "test": "test name", "issuccess": "True", "description": "this test will check that something will work", "classname": "/Users/lorem.ipsum@fake.io/runeatest", "result": "success", "failurereason": "", } ] assert expected == actual def test_add_failed_test_case(mocker): x = '{"tags": {"opId": "ServerBackend-f421e441fa310430","browserUserAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36","orgId": "1009391617598028","userAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36","clusterId": "0216-124733-lone970","user": "<EMAIL>","principalIdpObjectId": "71b45910-e7b4-44d8-82f7-bf6fac4630d0","browserHostName": "uksouth.azuredatabricks.net","parentOpId": "RPCClient-bb9b9591c29c01f7","jettyRpcType": "InternalDriverBackendMessages$DriverBackendRequest"},"extraContext":{"notebook_path":"/Users/lorem.ipsum@fake.io/runeatest"}}' context = json.loads(x) mocker.patch("runeatest.pysparkconnect.get_context", return_value=context) actual = [] actual.append( testreporter.add_testcase( "test name", False, "this test will check that something will work", "actual isn't expected", ) ) expected = [ { "test": "test name", "issuccess": "False", "description": "this test will check that something will work", "classname": "/Users/lorem.ipsum@fake.io/runeatest", "result": "failure", "failurereason": "actual isn't expected", } ] assert expected == actual def test_add_all_failed_test_cases(mocker): x = '{"tags": {"opId": "ServerBackend-f421e441fa310430","browserUserAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36","orgId": "1009391617598028","userAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36","clusterId": "0216-124733-lone970","user": "<EMAIL>","principalIdpObjectId": "71b45910-e7b4-44d8-82f7-bf6fac4630d0","browserHostName": "uksouth.azuredatabricks.net","parentOpId": "RPCClient-bb9b9591c29c01f7","jettyRpcType": "InternalDriverBackendMessages$DriverBackendRequest"},"extraContext":{"notebook_path":"/Users/lorem.ipsum@fake.io/runeatest"}}' context = json.loads(x) mocker.patch("runeatest.pysparkconnect.get_context", return_value=context) actual_test_add_all_failed_test_cases = [] actual_test_add_all_failed_test_cases.append( testreporter.add_testcase( "test name", False, "this test will check that something will work", "this test failed", ) ) actual_test_add_all_failed_test_cases.append( testreporter.add_testcase( "test name 2", False, "this test will check that something will work", "that test failed", ) ) expected_test_add_all_failed_test_cases = [ { "test": "test name", "issuccess": "False", "description": "this test will check that something will work", "classname": "/Users/lorem.ipsum@fake.io/runeatest", "result": "failure", "failurereason": "this test failed", }, { "test": "test name 2", "issuccess": "False", "description": "this test will check that something will work", "classname": "/Users/lorem.ipsum@fake.io/runeatest", "result": "failure", "failurereason": "that test failed", }, ] assert ( expected_test_add_all_failed_test_cases == actual_test_add_all_failed_test_cases ) def test_add_one_passed_one_failed_test_cases(mocker): x = '{"tags": {"opId": "ServerBackend-f421e441fa310430","browserUserAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36","orgId": "1009391617598028","userAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36","clusterId": "0216-124733-lone970","user": "<EMAIL>","principalIdpObjectId": "71b45910-e7b4-44d8-82f7-bf6fac4630d0","browserHostName": "uksouth.azuredatabricks.net","parentOpId": "RPCClient-bb9b9591c29c01f7","jettyRpcType": "InternalDriverBackendMessages$DriverBackendRequest"},"extraContext":{"notebook_path":"/Users/lorem.ipsum@fake.io/runeatest"}}' context = json.loads(x) mocker.patch("runeatest.pysparkconnect.get_context", return_value=context) actual = [] actual.append( testreporter.add_testcase( "test name", True, "this test will check that something will work" ) ) actual.append( testreporter.add_testcase( "test name 2", False, "this test will check that something will work", "my test failed here", ) ) expected = [ { "test": "test name", "issuccess": "True", "description": "this test will check that something will work", "classname": "/Users/lorem.ipsum@fake.io/runeatest", "result": "success", "failurereason": "", }, { "test": "test name 2", "issuccess": "False", "description": "this test will check that something will work", "classname": "/Users/lorem.ipsum@fake.io/runeatest", "result": "failure", "failurereason": "my test failed here", }, ] actual_string = str(actual) assert expected == actual def test_add_one_passed_one_failed_test_cases_to_string(mocker): x = '{"tags": {"opId": "ServerBackend-f421e441fa310430","browserUserAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36","orgId": "1009391617598028","userAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36","clusterId": "0216-124733-lone970","user": "<EMAIL>","principalIdpObjectId": "71b45910-e7b4-44d8-82f7-bf6fac4630d0","browserHostName": "uksouth.azuredatabricks.net","parentOpId": "RPCClient-bb9b9591c29c01f7","jettyRpcType": "InternalDriverBackendMessages$DriverBackendRequest"},"extraContext":{"notebook_path":"/Users/lorem.ipsum@fake.io/runeatest"}}' context = json.loads(x) mocker.patch("runeatest.pysparkconnect.get_context", return_value=context) actual = [] actual.append( testreporter.add_testcase( "test name", True, "this test will check that something will work" ) ) actual.append( testreporter.add_testcase( "test name 2", False, "this test will check that something will work", "a failed test", ) ) expected = "[{'test': 'test name', 'issuccess': 'True', 'description': 'this test will check that something will work', 'classname': '/Users/lorem.ipsum@fake.io/runeatest', 'result': 'success', 'failurereason': ''}, {'test': 'test name 2', 'issuccess': 'False', 'description': 'this test will check that something will work', 'classname': '/Users/lorem.ipsum@fake.io/runeatest', 'result': 'failure', 'failurereason': 'a failed test'}]" actual_string = str(actual) assert expected == actual_string def test_add_all_failed_test_cases_to_string(mocker): x = '{"tags": {"opId": "ServerBackend-f421e441fa310430","browserUserAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36","orgId": "1009391617598028","userAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36","clusterId": "0216-124733-lone970","user": "<EMAIL>","principalIdpObjectId": "71b45910-e7b4-44d8-82f7-bf6fac4630d0","browserHostName": "uksouth.azuredatabricks.net","parentOpId": "RPCClient-bb9b9591c29c01f7","jettyRpcType": "InternalDriverBackendMessages$DriverBackendRequest"},"extraContext":{"notebook_path":"/Users/lorem.ipsum@fake.io/runeatest"}}' context = json.loads(x) mocker.patch("runeatest.pysparkconnect.get_context", return_value=context) actual_test_add_all_failed_test_cases = [] actual_test_add_all_failed_test_cases.append( testreporter.add_testcase( "test name", False, "this test will check that something will work", "test name 1 has failed", ) ) actual_test_add_all_failed_test_cases.append( testreporter.add_testcase( "test name 2", False, "this test will check that something will work", "test name 2 has failed", ) ) expected_test_add_all_failed_test_cases_string = "[{'test': 'test name', 'issuccess': 'False', 'description': 'this test will check that something will work', 'classname': '/Users/lorem.ipsum@fake.io/runeatest', 'result': 'failure', 'failurereason': 'test name 1 has failed'}, {'test': 'test name 2', 'issuccess': 'False', 'description': 'this test will check that something will work', 'classname': '/Users/lorem.ipsum@fake.io/runeatest', 'result': 'failure', 'failurereason': 'test name 2 has failed'}]" actual_test_add_all_failed_test_cases_string = str( actual_test_add_all_failed_test_cases ) assert ( expected_test_add_all_failed_test_cases_string == actual_test_add_all_failed_test_cases_string ) def test_add_all_passed_test_cases_failure_included(mocker): x = '{"tags": {"opId": "ServerBackend-f421e441fa310430","browserUserAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36","orgId": "1009391617598028","userAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36","clusterId": "0216-124733-lone970","user": "<EMAIL>","principalIdpObjectId": "71b45910-e7b4-44d8-82f7-bf6fac4630d0","browserHostName": "uksouth.azuredatabricks.net","parentOpId": "RPCClient-bb9b9591c29c01f7","jettyRpcType": "InternalDriverBackendMessages$DriverBackendRequest"},"extraContext":{"notebook_path":"/Users/lorem.ipsum@fake.io/runeatest"}}' context = json.loads(x) mocker.patch("runeatest.pysparkconnect.get_context", return_value=context) actual = [] actual.append( testreporter.add_testcase( "test name", True, "this test will check that something will work", "my test may have failed because of something", ) ) actual.append( testreporter.add_testcase( "test name 2", True, "this test will check that something will work", "my test may have failed because of something else", ) ) expected = [ { "test": "test name", "issuccess": "True", "description": "this test will check that something will work", "classname": "/Users/lorem.ipsum@fake.io/runeatest", "result": "success", "failurereason": "my test may have failed because of something", }, { "test": "test name 2", "issuccess": "True", "description": "this test will check that something will work", "classname": "/Users/lorem.ipsum@fake.io/runeatest", "result": "success", "failurereason": "my test may have failed because of something else", }, ] assert expected == actual
StarcoderdataPython
1853998
<reponame>NikaEgorova/goiteens-python3-egorova Ned = {"Інструменти для лівшів", "Зелений чай", "Шоколад"} Gomer = {"Піцу", "Премію на роботі", "Касети з всіма випусками Клоуна Красті", "Шоколад"} i = Ned.intersection(Gomer) print(i)
StarcoderdataPython
3231785
<gh_stars>0 """ LC621 task scheduler Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks. Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle. However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle. You need to return the least number of intervals the CPU will take to finish all the given tasks. Example: Input: tasks = ["A","A","A","B","B","B"], n = 2 Output: 8 """ # Runtime: 440 ms, faster than 65.87% of Python3 online submissions for Task Scheduler. # Memory Usage: 13 MB, less than 100.00% of Python3 online submissions for Task Scheduler. from collections import defaultdict class Solution: def leastInterval(self, tasks: List[str], n: int) -> int: max_freq = 0 max_freq_task = 0 freq = defaultdict(int) for letter in tasks: freq[letter] += 1 if freq[letter] == max_freq: max_freq_task += 1 elif max_freq < freq[letter]: max_freq = freq[letter] max_freq_task = 1 avaliable_slot = (n - max_freq_task + 1) * (max_freq - 1) avaliable_task = len(tasks) - max_freq * max_freq_task idle = max(0, avaliable_slot - avaliable_task) return len(tasks) + idle # faster version # Runtime: 404 ms, faster than 92.71% of Python3 online submissions for Task Scheduler. # Memory Usage: 13 MB, less than 100.00% of Python3 online submissions for Task Scheduler. class Solution: def leastInterval(self, tasks: List[str], n: int) -> int: max_freq = 0 num_task_max_freq = 0 all_freq = collections.Counter(tasks) for letter, freq in all_freq.items(): if max_freq == freq: num_task_max_freq += 1 elif max_freq < freq: max_freq = freq num_task_max_freq = 1 avaliable_slot = (n - num_task_max_freq + 1) * (max_freq - 1) avaliable_task = len(tasks) - num_task_max_freq * max_freq idle = max(0, avaliable_slot - avaliable_task) return len(tasks) + idle
StarcoderdataPython
5101832
import configparser config = configparser.ConfigParser() config.read('config.ini') if config['IHC']['ODTC'] == "True": from .odtcFinder import OdtcFinderWrapper from .odtc import DataEventOdtcSensorValue, OdtcWrapper from .odtcConfigXml import OdtcConfigXmlWrapper from .odtcParamsXml import OdtcParamsXmlWrapper from .odtcDownloader import OdtcDownloaderWrapper if config['IHC']['SCILA'] == "True": from .scila import ScilaWrapper from .scilaFinder import ScilaFinderWrapper from .scilaConfigXml import ScilaConfigXmlWrapper from .scilaParamsXml import ScilaParamsXmlWrapper from .scilaDownloader import ScilaDownloaderWrapper from .pms import PmsWrapper from .device import DeviceWrapper from .status import StatusWrapper from .deviceIdentification import DeviceIdentificationWrapper from .networkInterfaceTypes import NetworkInterfaceTypesWrapper from .statusEventArgs import StatusEventArgsWrapper from .ftpItem import FtpItemWrapper
StarcoderdataPython
282759
from itertools import groupby from operator import itemgetter def summary(data, key=itemgetter(0), field=itemgetter(1)): """ Summarise the given data (a sequence of rows), grouped by the given key (default: the first item of each row), giving totals of the given field (default: the second item of each row). The key and field arguments should be functions which, given a data record, return the relevant value. """ for k, group in groupby(data, key): yield k, sum(field(row) for row in group) if __name__ == "__main__": # Example: given a sequence of sales data for city within region, # _sorted on region_, produce a sales report by region sales = [('Scotland', 'Edinburgh', 20000), ('Scotland', 'Glasgow', 12500), ('Wales', 'Cardiff', 29700), ('Wales', 'Bangor', 12800), ('England', 'London', 90000), ('England', 'Manchester', 45600), ('England', 'Liverpool', 29700)] for region, total in summary(sales, field=itemgetter(2)): print "%10s: %d" % (region, total)
StarcoderdataPython
1998289
from cryptography import x509 from cryptography.x509.oid import ExtensionOID from cryptography.x509.oid import ObjectIdentifier from cryptography.hazmat.backends import default_backend import asn1 import struct # This is a very simplistic ASN1 parser. Production code should use # something like ans1c to build a parser from the ASN1 spec file so # that it can check and enforce data validity. class SgxPckCertificateExtensions: id_ce_sGXExtensions = '1.2.840.113741.1.13.1' id_ce_sGXExtensions_tCB= id_ce_sGXExtensions+".2" id_ce_sGXExtensions_configuration= id_ce_sGXExtensions+".7" id_cdp_extension = '192.168.127.12' decoder= asn1.Decoder() _data= {} ca= '' oids= { id_ce_sGXExtensions: 'sGXExtensions', id_ce_sGXExtensions+".1": 'pPID', id_ce_sGXExtensions_tCB: 'tCB', id_ce_sGXExtensions_tCB+".1": 'tCB-sGXTCBComp01SVN', id_ce_sGXExtensions_tCB+".2": 'tCB-sGXTCBComp02SVN', id_ce_sGXExtensions_tCB+".3": 'tCB-sGXTCBComp03SVN', id_ce_sGXExtensions_tCB+".4": 'tCB-sGXTCBComp04SVN', id_ce_sGXExtensions_tCB+".5": 'tCB-sGXTCBComp05SVN', id_ce_sGXExtensions_tCB+".6": 'tCB-sGXTCBComp06SVN', id_ce_sGXExtensions_tCB+".7": 'tCB-sGXTCBComp07SVN', id_ce_sGXExtensions_tCB+".8": 'tCB-sGXTCBComp08SVN', id_ce_sGXExtensions_tCB+".9": 'tCB-sGXTCBComp09SVN', id_ce_sGXExtensions_tCB+".10": 'tCB-sGXTCBComp10SVN', id_ce_sGXExtensions_tCB+".11": 'tCB-sGXTCBComp11SVN', id_ce_sGXExtensions_tCB+".12": 'tCB-sGXTCBComp12SVN', id_ce_sGXExtensions_tCB+".13": 'tCB-sGXTCBComp13SVN', id_ce_sGXExtensions_tCB+".14": 'tCB-sGXTCBComp14SVN', id_ce_sGXExtensions_tCB+".15": 'tCB-sGXTCBComp15SVN', id_ce_sGXExtensions_tCB+".16": 'tCB-sGXTCBComp16SVN', id_ce_sGXExtensions_tCB+".17": 'tCB-pCESVN', id_ce_sGXExtensions_tCB+".18": 'tCB-cPUSVN', id_ce_sGXExtensions+".3": 'pCE-ID', id_ce_sGXExtensions+".4": 'fMSPC', id_ce_sGXExtensions+".5": 'sGXType', id_ce_sGXExtensions+".6": 'platformInstanceID', id_ce_sGXExtensions_configuration: 'configuration', id_ce_sGXExtensions_configuration+".1": 'dynamicPlatform', id_ce_sGXExtensions_configuration+".2": 'cachedKeys', id_ce_sGXExtensions_configuration+".3": 'sMTEnabled' } def _parse_asn1(self, d, oid, lnr=asn1.Numbers.ObjectIdentifier): tag= self.decoder.peek() while tag: if tag.typ == asn1.Types.Constructed: self.decoder.enter() if ( lnr == asn1.Numbers.ObjectIdentifier ): d[self.oids[oid]]= {} self._parse_asn1(d[self.oids[oid]], oid, tag.nr) else: self._parse_asn1(d, oid, tag.nr) self.decoder.leave() elif tag.typ == asn1.Types.Primitive: tag, value= self.decoder.read() if ( tag.nr == asn1.Numbers.ObjectIdentifier ): oid= value else: d[self.oids[oid]]= value lnr= tag.nr tag= self.decoder.peek() return def parse_pem_certificate(self, pem): self._data= {} cert= x509.load_pem_x509_certificate(pem, default_backend()) issuerCN = cert.issuer.rfc4514_string() if (issuerCN.find('Processor') != -1) : self.ca = 'PROCESSOR' elif (issuerCN.find('Platform') != -1) : self.ca = 'PLATFORM' else : self.ca = None sgxext= cert.extensions.get_extension_for_oid( ObjectIdentifier(self.id_ce_sGXExtensions) ) self.decoder.start(sgxext.value.value) self._parse_asn1(self._data, self.id_ce_sGXExtensions) def get_root_ca_crl(self, pem): self._data= {} cert= x509.load_pem_x509_certificate(pem, default_backend()) cdpext= cert.extensions.get_extension_for_oid( ObjectIdentifier(self.id_cdp_extension) ) return getattr(getattr(cdpext.value[0], "_full_name")[0], "value") def data(self, field=None): if 'sGXExtensions' not in self._data: return None d= self._data['sGXExtensions'] if field: if field in d: return d[field] return None return d def _hex_data(self, field): val= self.data(field) if val is None: return None return val.hex() # Commonly-needed data fields #------------------------------ def get_fmspc(self): return self._hex_data('fMSPC') def get_ca(self): return self.ca def get_tcbm(self): tcb= self.data('tCB') if tcb is None: return None return tcb['tCB-cPUSVN'].hex() + self.get_pcesvn() def get_pceid(self): return self._hex_data('pCE-ID') def get_ppid(self): return self._hex_data('pPID') def get_pcesvn(self): tcb= self.data('tCB') # pCESVN should be packed little-endian pcesvn= struct.pack('<H', tcb['tCB-pCESVN']) return pcesvn.hex()
StarcoderdataPython
6438264
import timeago import datetime from datetime import timezone from doing.utils import run_command, get_repo_name, replace_user_aliases, validate_work_item_type from rich.table import Table from rich.live import Live from rich.progress import track from rich.console import Console from typing import List, Dict console = Console() def work_item_query(assignee: str, author: str, label: str, state: str, area: str, iteration: str, type: str): """ Build query in wiql. # More on 'work item query language' syntax: # https://docs.microsoft.com/en-us/azure/devops/boards/queries/wiql-syntax?view=azure-devops """ # ensure using user aliases assignee = replace_user_aliases(assignee) author = replace_user_aliases(author) # Get all workitems query = "SELECT [System.Id],[System.Title],[System.AssignedTo]," query += "[System.WorkItemType],[System.State],[System.CreatedDate]" query += f"FROM WorkItems WHERE [System.AreaPath] = '{area}' " # Filter on iteration. Note we use UNDER so that user can choose to provide teams path for all sprints. query += f"AND [System.IterationPath] UNDER '{iteration}' " if assignee: query += f"AND [System.AssignedTo] = '{assignee}' " if author: query += f"AND [System.CreatedBy] = '{author}' " if label: for lab in label.split(","): query += f"AND [System.Tags] Contains '{lab.strip()}' " if state == "open": query += "AND [System.State] NOT IN ('Resolved','Closed','Done','Removed') " if state == "closed": query += "AND [System.State] IN ('Resolved','Closed','Done') " if state == "all": query += "AND [System.State] <> 'Removed' " if type: validate_work_item_type(type) query += f"AND [System.WorkItemType] = '{type}' " # Ordering of results query += "ORDER BY [System.CreatedDate] asc" return query def cmd_list( assignee: str, author: str, label: str, state: str, team: str, area: str, iteration: str, organization: str, project: str, type: str, ) -> None: """ Run `doing list` command. """ # Get config settings assignee = replace_user_aliases(assignee) author = replace_user_aliases(author) query = work_item_query(assignee, author, label, state, area, iteration, type) work_items = run_command(f'az boards query --wiql "{query}" --org "{organization}" -p "{project}"') if len(work_items) == 0: msg = f"[dark_orange3]>[/dark_orange3] No issues in sprint '{iteration}' given filters used" console.print(msg) return workitem_prs = {} # type: Dict # Now for each work item we could get linked PRs # However, APIs requests are slow, and most work items don't have a PR. # Instead, we'll retrieve all active PRs and see which items are linked (less API calls) repo_name = get_repo_name() query = f'az repos pr list --repository "{repo_name}" --org "{organization}" -p "{project}" ' query += '--status active --query "[].pullRequestId"' active_pullrequest_ids = run_command(query) with Live(build_table(work_items, workitem_prs, iteration, False), refresh_per_second=4, console=console) as live: # For each PR, get linked work items. Note that "az repos pr list --include-links" does not work :( # Posted issue on bug here: https://github.com/Azure/azure-cli-extensions/issues/2946 for pr_id in track(active_pullrequest_ids, description="Processing pull requests", transient=False): linked_workitems = run_command( f'az repos pr work-item list --id {pr_id} --query "[].id" --org "{organization}"', allow_verbose=False ) for work_item in linked_workitems: if work_item in workitem_prs.keys(): workitem_prs[work_item].append(str(pr_id)) else: workitem_prs[work_item] = [str(pr_id)] live.update(build_table(work_items, workitem_prs, iteration, False)) live.update(build_table(work_items, workitem_prs, iteration, last_build=True)) def build_table(work_items: List, workitem_prs: Dict, iteration: str, last_build: bool = False) -> Table: """ Build rich table with open issues. """ # Create our table table = Table(title=f"Work-items in current iteration {iteration}") table.add_column("ID", justify="right", style="cyan", no_wrap=True) table.add_column("Title", justify="left", style="cyan", no_wrap=False) table.add_column("Assignee", justify="left", style="cyan", no_wrap=False) table.add_column("Type", justify="left", style="cyan", no_wrap=True) table.add_column("Created", justify="right", style="cyan", no_wrap=True) table.add_column("PRs", justify="right", style="cyan", no_wrap=True) for item in work_items: # item = run_command(f"az boards work-item show --id {work_item_id}", # "--fields 'System.Title,System.CreatedBy,System.WorkItemType'") # ) fields = item.get("fields") item_id = fields.get("System.Id") item_title = fields.get("System.Title") item_createdby = fields.get("System.AssignedTo", {}).get("displayName", "") item_type = fields.get("System.WorkItemType") # For example: # '2020-11-17T13:33:32.463Z' # details: https://docs.microsoft.com/en-us/azure/devops/boards/queries/wiql-syntax?view=azure-devops#date-time-pattern # noqa item_datetime = fields.get("System.CreatedDate") try: item_datetime = datetime.datetime.strptime(item_datetime, "%Y-%m-%dT%H:%M:%S.%fZ") except ValueError: # sometimes milliseconds is missing from the timestamp, try without item_datetime = datetime.datetime.strptime(item_datetime, "%Y-%m-%dT%H:%M:%SZ") item_datetime = item_datetime.replace(tzinfo=timezone.utc) now = datetime.datetime.now(timezone.utc) item_datetime = timeago.format(item_datetime, now) if int(item_id) in workitem_prs.keys(): item_linked_prs = ",".join(workitem_prs[int(item_id)]) elif last_build: item_linked_prs = "" else: item_linked_prs = "[bright_black]loading..[bright_black]" # TODO: If current git branch equal to branch ID name, different color. table.add_row(str(item_id), item_title, item_createdby, item_type, item_datetime, item_linked_prs) return table
StarcoderdataPython
6657363
<gh_stars>1-10 # Copyright 2018 The glTF-Blender-IO authors. # # 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 bpy from .gltf2_blender_animation_bone import BlenderBoneAnim from .gltf2_blender_animation_node import BlenderNodeAnim from .gltf2_blender_animation_weight import BlenderWeightAnim from .gltf2_blender_animation_utils import restore_animation_on_object class BlenderAnimation(): """Dispatch Animation to bone or object animation.""" def __new__(cls, *args, **kwargs): raise RuntimeError("%s should not be instantiated" % cls) @staticmethod def anim(gltf, anim_idx, node_idx): """Dispatch Animation to bone or object.""" if gltf.data.nodes[node_idx].is_joint: BlenderBoneAnim.anim(gltf, anim_idx, node_idx) else: BlenderNodeAnim.anim(gltf, anim_idx, node_idx) BlenderWeightAnim.anim(gltf, anim_idx, node_idx) if gltf.data.nodes[node_idx].children: for child in gltf.data.nodes[node_idx].children: BlenderAnimation.anim(gltf, anim_idx, child) @staticmethod def restore_animation(gltf, node_idx, animation_name): """Restores the actions for an animation by its track name on the subtree starting at node_idx.""" node = gltf.data.nodes[node_idx] if node.is_joint: obj = bpy.data.objects[gltf.data.skins[node.skin_id].blender_armature_name] else: obj = bpy.data.objects[node.blender_object] restore_animation_on_object(obj, animation_name) if obj.data and hasattr(obj.data, 'shape_keys'): restore_animation_on_object(obj.data.shape_keys, animation_name) if gltf.data.nodes[node_idx].children: for child in gltf.data.nodes[node_idx].children: BlenderAnimation.restore_animation(gltf, child, animation_name)
StarcoderdataPython
3395791
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import torch import torch.nn as nn import torch.nn.functional as F from typing import Dict, List, Optional, Tuple from detectron2.config import configurable from detectron2.layers import ShapeSpec, cat, get_norm from detectron2.modeling import PROPOSAL_GENERATOR_REGISTRY from detectron2.utils.events import get_event_storage from detectron2.structures import ImageList, Instances from detectron2.modeling.proposal_generator.rpn import RPN_HEAD_REGISTRY, build_rpn_head from detectron2.modeling.anchor_generator import build_anchor_generator from continuous.custom.modeling import Box2BoxTransform, Box2BoxTransformRotated from continuous.utils.smooth_l1_loss import smooth_l1_loss from continuous.custom.continuous import RConv from .rrpn import CustomizedRRPN @RPN_HEAD_REGISTRY.register() class BranchRPNHead(nn.Module): """ Standard RPN classification and regression heads described in :paper:`Faster R-CNN`. Uses a 3x3 conv to produce a shared hidden state from which one 1x1 conv predicts objectness logits for each anchor and a second 1x1 conv predicts bounding-box deltas specifying how to deform each anchor into an object proposal. """ @configurable def __init__(self, *, in_channels: int, num_anchors: int, box_dim: int = 4, num_branch: int = 1): """ NOTE: this interface is experimental. Args: in_channels (int): number of input feature channels. When using multiple input features, they must have the same number of channels. num_anchors (int): number of anchors to predict for *each spatial position* on the feature map. The total number of anchors for each feature map will be `num_anchors * H * W`. box_dim (int): dimension of a box, which is also the number of box regression predictions to make for each anchor. An axis aligned box has box_dim=4, while a rotated box has box_dim=5. """ super().__init__() self.num_branch = num_branch kernel_type = 0 if num_branch is 8 else 1 # 3x3 conv for the hidden representation self.rconv = RConv(in_channels, in_channels, kernel_type=kernel_type, stride=1, padding=1) # 1x1 conv for predicting objectness logits self.objectness_logits = nn.Conv2d(in_channels, num_anchors, kernel_size=1, stride=1) # 1x1 conv for predicting box2box transform deltas self.anchor_deltas = nn.Conv2d(in_channels, num_anchors * box_dim, kernel_size=1, stride=1) nn.init.normal_(self.rconv.weight, std=0.01) for l in [self.objectness_logits, self.anchor_deltas]: nn.init.normal_(l.weight, std=0.01) nn.init.constant_(l.bias, 0) @classmethod def from_config(cls, cfg, input_shape): num_branch = cfg.MODEL.CUSTOM.BRANCH.NUM_BRANCH # Standard RPN is shared across levels: in_channels = [s.channels for s in input_shape] assert len(set(in_channels)) == 1, "Each level must have the same channel!" in_channels = in_channels[0] # RPNHead should take the same input as anchor generator # NOTE: it assumes that creating an anchor generator does not have unwanted side effect. anchor_generator = build_anchor_generator(cfg, input_shape) num_anchors = anchor_generator.num_anchors box_dim = anchor_generator.box_dim assert ( len(set(num_anchors)) == 1 ), "Each level must have the same number of anchors per spatial position" return {"in_channels": in_channels, "num_anchors": num_anchors[0], "box_dim": box_dim, "num_branch": num_branch} def forward(self, features: List[torch.Tensor], rot: int = 0): """ Args: features (list[Tensor]): list of feature maps Returns: list[Tensor]: A list of L elements. Element i is a tensor of shape (N, A, Hi, Wi) representing the predicted objectness logits for all anchors. A is the number of cell anchors. list[Tensor]: A list of L elements. Element i is a tensor of shape (N, A*box_dim, Hi, Wi) representing the predicted "deltas" used to transform anchors to proposals. """ pred_objectness_logits = [] pred_anchor_deltas = [] for x in features: t = F.relu(self.rconv(x, rot)) pred_objectness_logits.append(self.objectness_logits(t)) x = self.anchor_deltas(t) pred_anchor_deltas.append(x) return pred_objectness_logits, pred_anchor_deltas @PROPOSAL_GENERATOR_REGISTRY.register() class BranchRRPN(CustomizedRRPN): """ Trident RRPN subnetwork. """ def __init__(self, cfg, input_shape): super(BranchRRPN, self).__init__(cfg, input_shape) self.box2box_transform = Box2BoxTransformRotated(weights=cfg.MODEL.RPN.BBOX_REG_WEIGHTS) self.rpn_head = build_rpn_head(cfg, [input_shape[f] for f in self.in_features]) self.num_branch = cfg.MODEL.CUSTOM.BRANCH.NUM_BRANCH self.rotation_direction = 1 def losses( self, anchors, pred_objectness_logits: List[torch.Tensor], gt_labels: List[torch.Tensor], pred_anchor_deltas: List[torch.Tensor], gt_boxes ): """ Return the losses from a set of RPN predictions and their associated ground-truth. Args: anchors (list[Boxes or RotatedBoxes]): anchors for each feature map, each has shape (Hi*Wi*A, B), where B is box dimension (4 or 5). pred_objectness_logits (list[Tensor]): A list of L elements. Element i is a tensor of shape (N, Hi*Wi*A) representing the predicted objectness logits for all anchors. gt_labels (list[Tensor]): Output of :meth:`label_and_sample_anchors`. pred_anchor_deltas (list[Tensor]): A list of L elements. Element i is a tensor of shape (N, Hi*Wi*A, 4 or 5) representing the predicted "deltas" used to transform anchors to proposals. gt_boxes (list[Boxes or RotatedBoxes]): Output of :meth:`label_and_sample_anchors`. Returns: dict[loss name -> loss value]: A dict mapping from loss name to loss value. Loss names are: `loss_rpn_cls` for objectness classification and `loss_rpn_loc` for proposal localization. """ num_batches = len(gt_labels) gt_labels = torch.stack(gt_labels) # (N, sum(Hi*Wi*Ai)) anchors = type(anchors[0]).cat(anchors).tensor # Ax(4 or 5) num_images = num_batches / self.num_branch angle_step = 360.0 / self.num_branch * self.rotation_direction gt_anchor_deltas = [] for branch_idx in range(self.num_branch): for image_idx in range(int(num_images)): idx = int(branch_idx * num_images + image_idx) gt_anchor_deltas.append(self.box2box_transform.get_deltas(anchors, gt_boxes[idx], torch.tensor([branch_idx * angle_step], device=anchors.device))) gt_anchor_deltas = torch.stack(gt_anchor_deltas) # (N, sum(Hi*Wi*Ai), 4 or 5) # Log the number of positive/negative anchors per-image that's used in training pos_mask = (gt_labels == 1) | (gt_labels == -2) num_pos_anchors = pos_mask.sum().item() num_neg_anchors = (gt_labels == 0).sum().item() storage = get_event_storage() storage.put_scalar("rpn/num_pos_anchors", num_pos_anchors / num_images) storage.put_scalar("rpn/num_neg_anchors", num_neg_anchors / num_images) localization_loss = smooth_l1_loss( cat(pred_anchor_deltas, dim=1)[pos_mask], gt_anchor_deltas[pos_mask], self.smooth_l1_beta, reduction="sum", ) valid_mask = gt_labels >= 0 p = torch.sigmoid(cat(pred_objectness_logits, dim=1)[valid_mask]) gt_target = gt_labels[valid_mask].to(torch.float32) ce_loss = F.binary_cross_entropy_with_logits( cat(pred_objectness_logits, dim=1)[valid_mask], gt_target, reduction="none", ) p_t = p * gt_target + (1 - p) * (1 - gt_target) focal_loss = ce_loss * ((1 - p_t) ** self.focal_loss_gamma) if self.focal_loss_alpha >= 0: alpha_t = self.focal_loss_alpha * gt_target + (1 - self.focal_loss_alpha) * (1 - gt_target) objectness_loss = alpha_t * focal_loss objectness_loss = objectness_loss.sum() normalizer = self.batch_size_per_image * num_images return { "loss_rpn_cls": objectness_loss / normalizer, "loss_rpn_loc": localization_loss / normalizer, } def _decode_proposals(self, anchors, pred_anchor_deltas: List[torch.Tensor]): """ Transform anchors into proposals by applying the predicted anchor deltas. Returns: proposals (list[Tensor]): A list of L tensors. Tensor i has shape (N, Hi*Wi*A, B) """ N = pred_anchor_deltas[0].shape[0] num_images = int(N / self.num_branch) angle_step = 360.0 / self.num_branch * self.rotation_direction proposals = [] # For each feature map for anchors_i, pred_anchor_deltas_i in zip(anchors, pred_anchor_deltas): B = anchors_i.tensor.size(1) # Expand anchors to shape (N*Hi*Wi*A, B) anchors_i = anchors_i.tensor.unsqueeze(0).expand(num_images, -1, -1).reshape(-1, B) proposals_i = [] for branch_idx in range(self.num_branch): start_idx = int(branch_idx * num_images) end_idx = start_idx + num_images pred_anchor_deltas_i_branch = pred_anchor_deltas_i[start_idx:end_idx] pred_anchor_deltas_i_branch = pred_anchor_deltas_i_branch.reshape(-1, B) proposals_i.append(self.box2box_transform.apply_deltas(pred_anchor_deltas_i_branch, anchors_i, torch.tensor([branch_idx * angle_step], device=anchors_i.device))) proposals_i = torch.cat(proposals_i) # Append feature map proposals with shape (N, Hi*Wi*A, B) proposals.append(proposals_i.view(N, -1, B)) return proposals def forward( self, images: ImageList, features: Dict[str, torch.Tensor], gt_instances: Optional[Instances] = None, ): """ Args: images (ImageList): input images of length `N` features (dict[str, Tensor]): input data as a mapping from feature map name to tensor. Axis 0 represents the number of images `N` in the input data; axes 1-3 are channels, height, and width, which may vary between feature maps (e.g., if a feature pyramid is used). gt_instances (list[Instances], optional): a length `N` list of `Instances`s. Each `Instances` stores ground-truth instances for the corresponding image. Returns: proposals: list[Instances]: contains fields "proposal_boxes", "objectness_logits" loss: dict[Tensor] or None """ batch_size = images.tensor.shape[0] images = ImageList( torch.cat([images.tensor] * self.num_branch), images.image_sizes * self.num_branch ) if gt_instances is not None: all_gt_instances = [] step_angle = 360.0 / self.num_branch for branch_idx in range(self.num_branch): instances = [] for gt_instance in gt_instances: instance = gt_instance instance.gt_boxes.tensor[:, 4] += self.rotation_direction * step_angle * branch_idx instances.append(instance) all_gt_instances.extend(instances) else: all_gt_instances = None gt_instances = all_gt_instances features = [features[f] for f in self.in_features] anchors = self.anchor_generator(features) branch_pred_objectness_logits = [] branch_pred_anchor_deltas = [] for rot in range(self.num_branch): start_idx = int(rot * batch_size) end_idx = int(start_idx + batch_size) branch_features = [feature[start_idx:end_idx, :, :, :] for feature in features] branch_pred_objectness_logit, branch_pred_anchor_delta = self.rpn_head(branch_features, rot) # Transpose the Hi*Wi*A dimension to the middle: branch_pred_objectness_logits.append([ # Reshape: (N, A, Hi, Wi) -> (N, Hi, Wi, A) -> (N, Hi*Wi*A) score.permute(0, 2, 3, 1).flatten(1) for score in branch_pred_objectness_logit ]) branch_pred_anchor_deltas.append([ # Reshape: (N, A*B, Hi, Wi) -> (N, A, B, Hi, Wi) -> (N, Hi, Wi, A, B) # -> (N, Hi*Wi*A, B) x.view(x.shape[0], -1, self.anchor_generator.box_dim, x.shape[-2], x.shape[-1]) .permute(0, 3, 4, 1, 2) .flatten(1, -2) for x in branch_pred_anchor_delta ]) pred_objectness_logits = [] pred_anchor_deltas = [] for in_feature_idx in range(len(branch_pred_objectness_logits[0])): in_feature_pred_objectness_logits = [] in_feature_pred_anchor_deltas = [] for branch_idx in range(self.num_branch): in_feature_pred_objectness_logits.append(branch_pred_objectness_logits[branch_idx][in_feature_idx]) in_feature_pred_anchor_deltas.append(branch_pred_anchor_deltas[branch_idx][in_feature_idx]) pred_objectness_logits.append(torch.cat(in_feature_pred_objectness_logits)) pred_anchor_deltas.append(torch.cat(in_feature_pred_anchor_deltas)) if self.training: gt_labels, gt_boxes = self.label_and_sample_anchors(anchors, gt_instances) losses = self.losses( anchors, pred_objectness_logits, gt_labels, pred_anchor_deltas, gt_boxes ) losses = {k: v * self.loss_weight for k, v in losses.items()} else: losses = {} proposals = self.predict_proposals( anchors, pred_objectness_logits, pred_anchor_deltas, images.image_sizes ) return proposals, losses
StarcoderdataPython
11390464
#!/usr/bin/env python # -*- coding: utf-8 -*- # pylint: disable=unused-argument, attribute-defined-outside-init, eval-used from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.uix.textinput import TextInput class MainApp(App): def build(self): self.operators = ["/", "*", "+", "-"] self.last_was_operator = None self.last_button = None main_layout = BoxLayout(orientation="vertical") self.solution = TextInput(multiline=False, readonly=True, halign="right", font_size=55) main_layout.add_widget(self.solution) buttons = [ ["7", "8", "9", "/"], ["4", "5", "6", "*"], ["1", "2", "3", "-"], [".", "0", "C", "+"], ] for row in buttons: h_layout = BoxLayout() for label in row: button = Button( text=label, pos_hint={ "center_x": 0.5, "center_y": 0.5 }, ) button.bind(on_press=self.on_button_press) h_layout.add_widget(button) main_layout.add_widget(h_layout) equals_button = Button(text="=", pos_hint={ "center_x": 0.5, "center_y": 0.5 }) equals_button.bind(on_press=self.on_solution) main_layout.add_widget(equals_button) return main_layout def on_button_press(self, instance): current = self.solution.text button_text = instance.text if button_text == "C": # Clear the solution widget self.solution.text = "" else: if current and (self.last_was_operator and button_text in self.operators): # Don't add two operators right after each other return elif current == "" and button_text in self.operators: # First character cannot be an operator return else: new_text = current + button_text self.solution.text = new_text self.last_button = button_text self.last_was_operator = self.last_button in self.operators def on_solution(self, instance): text = self.solution.text if text: solution = str(eval(self.solution.text)) self.solution.text = solution if __name__ == "__main__": app = MainApp() app.run()
StarcoderdataPython
6695124
<gh_stars>100-1000 # Copyright 2021 Peng Cheng Laboratory (http://www.szpclab.com/) and FedLab Authors (smilelab.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. from abc import ABC, abstractmethod import numpy as np from . import functional as F class DataPartitioner(ABC): """Base class for data partition in federated learning. """ @abstractmethod def _perform_partition(self): raise NotImplementedError @abstractmethod def __getitem__(self, index): raise NotImplementedError @abstractmethod def __len__(self): raise NotImplementedError class CIFAR10Partitioner(DataPartitioner): """CIFAR10 data partitioner. Partition CIFAR10 given specific client number. Currently 6 supported partition schemes can be achieved by passing different combination of parameters in initialization: - ``balance=None`` - ``partition="dirichlet"``: non-iid partition used in `Bayesian Nonparametric Federated Learning of Neural Networks <https://arxiv.org/abs/1905.12022>`_ and `Federated Learning with Matched Averaging <https://arxiv.org/abs/2002.06440>`_. Refer to :func:`fedlab.utils.dataset.functional.hetero_dir_partition` for more information. - ``partition="shards"``: non-iid method used in FedAvg `paper <https://arxiv.org/abs/1602.05629>`_. Refer to :func:`fedlab.utils.dataset.functional.shards_partition` for more information. - ``balance=True``: "Balance" refers to FL scenario that sample numbers for different clients are the same. Refer to :func:`fedlab.utils.dataset.functional.balance_partition` for more information. - ``partition="iid"``: Random select samples from complete dataset given sample number for each client. - ``partition="dirichlet"``: Refer to :func:`fedlab.utils.dataset.functional.client_inner_dirichlet_partition` for more information. - ``balance=False``: "Unbalance" refers to FL scenario that sample numbers for different clients are different. For unbalance method, sample number for each client is drown from Log-Normal distribution with variance ``unbalanced_sgm``. When ``unbalanced_sgm=0``, partition is balanced. Refer to :func:`fedlab.utils.dataset.functional.lognormal_unbalance_partition` for more information. The method is from paper `Federated Learning Based on Dynamic Regularization <https://openreview.net/forum?id=B7v4QMR6Z9w>`_. - ``partition="iid"``: Random select samples from complete dataset given sample number for each client. - ``partition="dirichlet"``: Refer to :func:`fedlab.utils.dataset.functional.client_inner_dirichlet_partition` for more information. Args: targets (list or numpy.ndarray): Targets of dataset for partition. Each element is in range of [0, 1, ..., 9]. num_clients (int): Number of clients for data partition. balance (bool, optional): Balanced partition over all clients or not. Default as ``True``. partition (str, optional): Partition type, only ``"iid"``, ``shards``, ``"dirichlet"`` are supported. Default as ``"iid"``. unbalance_sgm (float, optional): Log-normal distribution variance for unbalanced data partition over clients. Default as ``0`` for balanced partition. num_shards (int, optional): Number of shards in non-iid ``"shards"`` partition. Only works if ``partition="shards"``. Default as ``None``. dir_alpha (float, optional): Dirichlet distribution parameter for non-iid partition. Only works if ``partition="dirichlet"``. Default as ``None``. verbose (bool, optional): Whether to print partition process. Default as ``True``. seed (int, optional): Random seed. Default as ``None``. """ num_classes = 10 def __init__(self, targets, num_clients, balance=True, partition="iid", unbalance_sgm=0, num_shards=None, dir_alpha=None, verbose=True, seed=None): self.targets = np.array(targets) # with shape (num_samples,) self.num_samples = self.targets.shape[0] self.num_clients = num_clients self.client_dict = dict() self.partition = partition self.balance = balance self.dir_alpha = dir_alpha self.num_shards = num_shards self.unbalance_sgm = unbalance_sgm self.verbose = verbose # self.rng = np.random.default_rng(seed) # rng currently not supports randint np.random.seed(seed) # partition scheme check if balance is None: assert partition in ["dirichlet", "shards"], f"When balance=None, 'partition' only " \ f"accepts 'dirichlet' and 'shards'." elif isinstance(balance, bool): assert partition in ["iid", "dirichlet"], f"When balance is bool, 'partition' only " \ f"accepts 'dirichlet' and 'iid'." else: raise ValueError(f"'balance' can only be NoneType or bool, not {type(balance)}.") # perform partition according to setting self.client_dict = self._perform_partition() # get sample number count for each client self.client_sample_count = F.samples_num_count(self.client_dict, self.num_clients) def _perform_partition(self): if self.balance is None: if self.partition == "dirichlet": client_dict = F.hetero_dir_partition(self.targets, self.num_clients, self.num_classes, self.dir_alpha, min_require_size=10) else: # partition is 'shards' client_dict = F.shards_partition(self.targets, self.num_clients, self.num_shards) else: # if balance is True or False # perform sample number balance/unbalance partition over all clients if self.balance is True: client_sample_nums = F.balance_split(self.num_clients, self.num_samples) else: client_sample_nums = F.lognormal_unbalance_split(self.num_clients, self.num_samples, self.unbalance_sgm) # perform iid/dirichlet partition for each client if self.partition == "iid": client_dict = F.homo_partition(client_sample_nums, self.num_samples) else: # for dirichlet client_dict = F.client_inner_dirichlet_partition(self.targets, self.num_clients, self.num_classes, self.dir_alpha, client_sample_nums, self.verbose) return client_dict def __getitem__(self, index): """Obtain sample indices for client ``index``. Args: index (int): Client ID. Returns: list: List of sample indices for client ID ``index``. """ return self.client_dict[index] def __len__(self): """Usually equals to number of clients.""" return len(self.client_dict) class CIFAR100Partitioner(CIFAR10Partitioner): """CIFAR100 data partitioner. This is a subclass of the :class:`CIFAR10Partitioner`. """ num_classes = 100 class BasicPartitioner(DataPartitioner): """ - label-distribution-skew:quantity-based - label-distribution-skew:distributed-based (Dirichlet) - quantity-skew (Dirichlet) - IID Args: targets: num_clients: partition: dir_alpha: major_classes_num: verbose: seed: """ num_classes = 2 def __init__(self, targets, num_clients, partition='iid', dir_alpha=None, major_classes_num=1, verbose=True, seed=None): self.targets = np.array(targets) # with shape (num_samples,) self.num_samples = self.targets.shape[0] self.num_clients = num_clients self.client_dict = dict() self.partition = partition self.dir_alpha = dir_alpha self.verbose = verbose # self.rng = np.random.default_rng(seed) # rng currently not supports randint np.random.seed(seed) if partition == "noniid-#label": # label-distribution-skew:quantity-based assert isinstance(major_classes_num, int), f"'major_classes_num' should be integer, " \ f"not {type(major_classes_num)}." assert major_classes_num > 0, f"'major_classes_num' should be positive." assert major_classes_num < self.num_classes, f"'major_classes_num' for each client " \ f"should be less than number of total " \ f"classes {self.num_classes}." self.major_classes_num = major_classes_num elif partition in ["noniid-labeldir", "unbalance"]: # label-distribution-skew:distributed-based (Dirichlet) and quantity-skew (Dirichlet) assert dir_alpha > 0, f"Parameter 'dir_alpha' for Dirichlet distribution should be " \ f"positive." elif partition == "iid": # IID pass else: raise ValueError( f"tabular data partition only supports 'noniid-#label', 'noniid-labeldir', " f"'unbalance', 'iid'. {partition} is not supported.") self.client_dict = self._perform_partition() # get sample number count for each client self.client_sample_count = F.samples_num_count(self.client_dict, self.num_clients) def _perform_partition(self): if self.partition == "noniid-#label": # label-distribution-skew:quantity-based client_dict = F.label_skew_quantity_based_partition(self.targets, self.num_clients, self.num_classes, self.major_classes_num) elif self.partition == "noniid-labeldir": # label-distribution-skew:distributed-based (Dirichlet) client_dict = F.hetero_dir_partition(self.targets, self.num_clients, self.num_classes, self.dir_alpha, min_require_size=10) elif self.partition == "unbalance": # quantity-skew (Dirichlet) client_sample_nums = F.dirichlet_unbalance_split(self.num_clients, self.num_samples, self.dir_alpha) client_dict = F.homo_partition(client_sample_nums, self.num_samples) else: # IID client_sample_nums = F.balance_split(self.num_clients, self.num_samples) client_dict = F.homo_partition(client_sample_nums, self.num_samples) return client_dict def __getitem__(self, index): return self.client_dict[index] def __len__(self): return len(self.client_dict) class VisionPartitioner(BasicPartitioner): num_classes = 10 def __init__(self, targets, num_clients, partition='iid', dir_alpha=None, major_classes_num=None, verbose=True, seed=None): super(VisionPartitioner, self).__init__(targets=targets, num_clients=num_clients, partition=partition, dir_alpha=dir_alpha, major_classes_num=major_classes_num, verbose=verbose, seed=seed) class MNISTPartitioner(VisionPartitioner): num_features = 784 class FMNISTPartitioner(VisionPartitioner): num_features = 784 class SVHNPartitioner(VisionPartitioner): num_features = 1024 # class FEMNISTPartitioner(DataPartitioner): # def __init__(self): # """ # - feature-distribution-skew:real-world # - IID # """ # # num_classes = # pass # # def _perform_partition(self): # pass # # def __getitem__(self, index): # return self.client_dict[index] # # def __len__(self): # return len(self.client_dict) class FCUBEPartitioner(DataPartitioner): """FCUBE data partitioner. FCUBE is a synthetic dataset for research in non-IID scenario with feature imbalance. This dataset and its partition methods are proposed in `Federated Learning on Non-IID Data Silos: An Experimental Study <https://arxiv.org/abs/2102.02079>`_. Supported partition methods for FCUBE: - feature-distribution-skew:synthetic - IID For more details, please refer to Section (IV-B-b) of original paper. Args: data (numpy.ndarray): Data of dataset :class:`FCUBE`. """ num_classes = 2 num_clients = 4 # only accept partition for 4 clients def __init__(self, data, partition): if partition not in ['synthetic', 'iid']: raise ValueError( f"FCUBE only supports 'synthetic' and 'iid' partition, not {partition}.") self.partition = partition self.data = data if isinstance(data, np.ndarray): self.num_samples = data.shape[0] else: self.num_samples = len(data) self.client_dict = self._perform_partition() def _perform_partition(self): if self.partition == 'synthetic': # feature-distribution-skew:synthetic client_dict = F.fcube_synthetic_partition(self.data) else: # IID partition client_sample_nums = F.balance_split(self.num_clients, self.num_samples) client_dict = F.homo_partition(client_sample_nums, self.num_samples) return client_dict def __getitem__(self, index): return self.client_dict[index] def __len__(self): return self.num_clients class AdultPartitioner(BasicPartitioner): num_features = 123 num_classes = 2 class RCV1Partitioner(BasicPartitioner): num_features = 47236 num_classes = 2 class CovtypePartitioner(BasicPartitioner): num_features = 54 num_classes = 2
StarcoderdataPython
6613364
class BubbleSort: def __init__(self,a): self.a = a def result(self): for i in range(len(self.a)): for j in range(i+1,len(self.a)): if self.a[i] > self.a[j]: self.a[i],self.a[j] = self.a[j],self.a[i] return self.a
StarcoderdataPython
1979663
"""Simple multi-layer perception neural network on MNIST.""" import argparse import os.path import struct import time import numpy as real_numpy import minpy.core as core import minpy.numpy as np from minpy.nn import io from minpy.nn import layers import minpy.nn.model import minpy.nn.solver from minpy.utils.minprof import minprof # Please uncomment following if you have GPU-enabled MXNet installed. from minpy.context import set_context, gpu set_context(gpu(0)) # set the global context as gpu(0) #import logging #logging.getLogger('minpy.array').setLevel(logging.DEBUG) #logging.getLogger('minpy.core').setLevel(logging.DEBUG) #logging.getLogger('minpy.primitive').setLevel(logging.DEBUG) #logging.getLogger('minpy.dispatch.policy').setLevel(logging.DEBUG) num_cold = 5 class TwoLayerNet(minpy.nn.model.ModelBase): def __init__(self, args): super(TwoLayerNet, self).__init__() self.add_param(name='wi', shape=(784, args.hidden_size)) \ .add_param(name='bi', shape=(args.hidden_size,)) for i in range(args.num_hidden - 1): self.add_param(name='w%d' % i, shape=(args.hidden_size, args.hidden_size)) \ .add_param(name='b%d' % i, shape=(args.hidden_size,)) self.add_param(name='wo', shape=(args.hidden_size, 10)) \ .add_param(name='bo', shape=(10,)) self.batch_size = args.batch_size self.num_hidden = args.num_hidden def forward(self, X, mode): # Flatten the input data to matrix. X = np.reshape(X, (self.batch_size, 784)) # First affine layer (fully-connected layer). y1 = layers.affine(X, self.params['wi'], self.params['bi']) # ReLU activation. y2 = layers.relu(y1) # Hidden layers. for i in range(self.num_hidden - 1): y2 = layers.affine(y2, self.params['w%d' % i], self.params['b%d' % i]) y2 = layers.relu(y2) # Second affine layer. y3 = layers.affine(y2, self.params['wo'], self.params['bo']) return y3 def loss(self, predict, y): # Compute softmax loss between the output and the label. return layers.softmax_loss(predict, y) def main(args): # Create model. model = TwoLayerNet(args) for k, v in model.param_configs.items(): model.params[k] = np.zeros(v['shape']) img = np.zeros((args.batch_size, 784)) label = np.zeros((args.batch_size,)) for l in range(args.num_loops): if l == num_cold: start = time.time() def loss_func(*params): f = model.forward(img, 'train') return model.loss(f, label) if args.only_forward: loss = loss_func() loss.asnumpy() else: param_arrays = list(model.params.values()) param_keys = list(model.params.keys()) grad_and_loss_func = core.grad_and_loss( loss_func, argnum=range(len(param_arrays))) grad_arrays, loss = grad_and_loss_func(*param_arrays) for g in grad_arrays: g.get_data(minpy.array_variants.ArrayType.MXNET).wait_to_read() dur = time.time() - start print('Per Loop Time: %.6f' % (dur / (args.num_loops - num_cold))) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--only-forward', default=False, action='store_true') parser.add_argument('--batch-size', default=256, type=int) parser.add_argument('--hidden-size', default=256, type=int) parser.add_argument('--num-hidden', default=1, type=int) parser.add_argument('--num-loops', default=20, type=int) #import profile #profile.run('main(parser.parse_args())') main(parser.parse_args())
StarcoderdataPython
3254999
""" Library Features: Name: lib_gsmap_time Author(s): <NAME> (<EMAIL>) Date: '20200302' Version: '1.5.0' """ ####################################################################################### # Library import logging import pandas as pd from src.hyde.algorithm.settings.satellite.gsmap.lib_gsmap_args import logger_name # Logging log_stream = logging.getLogger(logger_name) ####################################################################################### # ------------------------------------------------------------------------------------- # Class data object class DataObj(dict): pass # ------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- # Method to compute time steps def getVarTime(time_period): time_size = time_period.size time_start = pd.Timestamp(time_period.values[0]) time_end = pd.Timestamp(time_period.values[-1]) time_period = pd.date_range(start=time_start, end=time_end, periods=time_size) time_scale = (time_end - time_start) / (time_size - 1) time_delta = time_scale.seconds time_resolution = time_scale.resolution time_obj = DataObj time_obj.time_size = time_size time_obj.time_start = time_start time_obj.time_end = time_end time_obj.time_period = time_period time_obj.time_scale = time_scale time_obj.time_delta = time_delta time_obj.time_resolution = time_resolution return time_obj # -------------------------------------------------------------------------------------
StarcoderdataPython
8190469
<reponame>ghsecuritylab/project-powerline #!/usr/bin/env python3 # -*- coding: utf-8 -*- import threading import atexit import logging class powerline_prototype(threading.Thread): def __init__(self, dbScoped, semCtrl, semNext): super(powerline_prototype, self).__init__(name='prototype') self.log = logging.getLogger("MasterLog") self.dbScoped = dbScoped self.dbSession = self.dbScoped() self.semCtrl = semCtrl atexit.register(self.cleanup) def run(self): while True: self.semCtrl.acquire(True) session = self.dbSession # TODO: CODE HERE self.semNext.release() def cleanup(self): self.dbScoped.remove()
StarcoderdataPython
9740884
<filename>shapes.py from functions import * import constants as const from math import sin,cos,radians,pi from visualization import arr2png, png2arr,rotate from random import randint as ri class Square: ''' Give side in milli-meter( mm ) and angle in degrees( ° ) ''' def __init__(self,side,angle=0): self.uid = ri(0,1000000000000000000000) self.myShape="square" self.length = side self.surfaceArea = side*side self.angle = 0 self.cornerCompatible = 1 self.triangleCompatible = 0 self.__generateShapeMatrix__(side,angle) def regenerateSelf(self): self.__generateShapeMatrix__(self.length,self.angle) def __repr__(self): return(f"Object Shape \t: {self.myShape}\nSide Length \t: {self.length} mm\nShape Tilt \t: {self.angle} °\nshapeFrameDimension \t: {self.shapeFrameDimension}") def print(self): ''' Prints Object parameters to console ''' print(repr(self)) def tilt(self,angle): self.angle += angle self.shapeMatrix=rotate(evenize(self.shapeMatrix),angle) self.shapeFrameDimension = [len(self.shapeMatrix[0]),len(self.shapeMatrix)] def printShape(self): ''' Prints shape to console in binary #### Warning : CPU intensive task ''' temp = "" for li in self.shapeMatrix: for num in li: temp+=str(num) temp+="\n" print(temp) def displayShape(self): ''' Displays shape as a image ''' (arr2png(self.shapeMatrix)).show() def __generateShapeMatrix__(self,side,angle=0): ''' Generates 2D binary shape matrix ''' self.dimensions=[self.length*const.sampl,self.angle,'dm,°'] # only angle of dimension changes on tilting siu = side*const.sampl # sim => side in micrometers (u kind of looks like Mu) self.shapeMatrix = [[1]*siu]*siu self.shapeFrameDimension = [siu,siu] # shapeFrameDimension changes on tilting if(angle==0 or angle%90==0): pass else: self.tilt(angle) class Rectangle: ''' Give length and height in milli-meter( mm ) and angle in degrees( ° ) ''' def __init__(self,length,height,angle=0): self.uid = ri(0,1000000000000000000000) self.myShape="rectangle" self.length = length self.height = height self.angle = 0 self.cornerCompatible = 1 self.surfaceArea = length*height self.triangleCompatible = 0 self.__generateShapeMatrix__(length,height,angle) def regenerateSelf(self): self.__generateShapeMatrix__(self.length,self.height,self.angle) def __repr__(self): return(f"Object Shape \t: {self.myShape}\nSide Length \t: {self.length} mm\nSide Height \t: {self.height} mm\nShape Tilt \t: {self.angle} °\nshapeFrameDimension \t: {self.shapeFrameDimension}") def print(self): ''' Prints Object parameters to console ''' print(repr(self)) def tilt(self,angle): self.angle += angle self.shapeMatrix=rotate(evenize(self.shapeMatrix),angle) self.shapeFrameDimension = [len(self.shapeMatrix[0]),len(self.shapeMatrix)] def printShape(self): ''' Prints shape to console in binary #### Warning : CPU intensive task ''' temp = "" for li in self.shapeMatrix: for num in li: temp+=str(num) temp+="\n" print(temp) def displayShape(self): ''' Displays shape as a image ''' (arr2png(self.shapeMatrix)).show() def __generateShapeMatrix__(self,length,height,angle=0): ''' Generates 2D binary shape matrix ''' self.dimensions=[self.length*const.sampl,self.height*const.sampl,self.angle,'dm,dm,°'] # only angle of dimension changes on tilting liu = length*const.sampl # liu => length in micrometers (u kind of looks like Mu) hiu = height*const.sampl # hiu => height in micrometers (u kind of looks like Mu) self.shapeMatrix = [[1]*liu]*hiu self.shapeFrameDimension = [liu,hiu] # shapeFrameDimension changes on tilting if(angle==0 or angle%180==0): pass else: self.tilt(angle) class Circle: ''' Give radius in milli-meter( mm ) ''' def __init__(self,radius): self.uid = ri(0,1000000000000000000000) self.myShape="circle" self.radius = radius self.cornerCompatible = 0 self.triangleCompatible = 1 self.surfaceArea = pi*radius*radius self.__generateShapeMatrix__(radius) def regenerateSelf(self): self.__generateShapeMatrix__(self.radius) def __repr__(self): return(f"Object Shape \t: {self.myShape}\nShape Radius \t: {self.radius} mm\nshapeFrameDimension \t: {self.shapeFrameDimension}") def print(self): ''' Prints Object parameters to console ''' print(repr(self)) def printShape(self): ''' Prints shape to console in binary #### Warning : CPU intensive task ''' temp = "" for li in self.shapeMatrix: for num in li: temp+=str(num) temp+="\n" print(temp) def displayShape(self): ''' Displays shape as a image ''' (arr2png(self.shapeMatrix)).show() def isPointInCircle(self,ptX,ptY,radius): if( (ptX-radius)**2 + (ptY-radius)**2 <= radius**2 ): return(True) else: return(False) def __generateShapeMatrix__(self,radius): ''' Generates 2D binary shape matrix ''' self.dimensions=[self.radius*const.sampl,'dm'] # only angle of dimension changes on tilting diu = 2*radius*const.sampl # diu => diameter in micrometers (u kind of looks like Mu) self.shapeFrameDimension = [diu,diu] # shapeFrameDimension changes on tilting shapeSkeleton = [[0]*diu for _ in range(diu)] for i in range(diu): for j in range(diu): if(self.isPointInCircle(i,j,diu/2)): shapeSkeleton[i][j]=1 self.shapeMatrix=shapeSkeleton class Cone: ''' Give cone-height & cone-radius in milli-meter( mm ) ''' def __init__(self,cone_height,cone_radius,angle=0): self.uid = ri(0,1000000000000000000000) self.myShape="cone" self.angle = 0 self.cone_radius = round(cone_radius) self.cone_height = round(cone_height) self.slantHeight = round((cone_radius**2 + cone_height**2)**0.5) self.theta = 2*180*cone_radius/self.slantHeight self.surfaceArea = pi*(self.slantHeight**2)*self.theta/360 self.cornerCompatible = 0 self.flatAngle = ((180 - self.theta)/2)+self.theta #print('theta = ',self.theta) if(self.theta>=360): raise Exception("Illegal cone dimensions.") return(0) self.cone_type = 1 if self.theta<=180 else 2 self.triangleCompatible = 3 if self.cone_type==1 else 2 #print('Cone type : ',self.cone_type) self.__generateShapeMatrix__(self.slantHeight,self.cone_type,angle) def regenerateSelf(self): self.__generateShapeMatrix__(self.slantHeight,self.cone_type,self.angle) def __repr__(self): return(f"Object Shape \t: {self.myShape}\nShape Radius \t: {self.cone_radius} mm\nShape Height \t: {self.cone_height} mm\nshapeFrameDimension \t: {self.shapeFrameDimension}") def tilt(self,angle): self.angle = angle self.shapeMatrix=rotate(evenize(self.shapeMatrix),angle) self.shapeFrameDimension = [len(self.shapeMatrix[0]),len(self.shapeMatrix)] def flaTilt(self,direction=1): self.shapeMatrix = evenize(self.shapeMatrix) if(self.cone_type==1): self.tilt((direction/abs(direction))*self.flatAngle) else: self.tilt(180) def print(self): ''' Prints Object parameters to console ''' print(repr(self)) def printShape(self): ''' Prints shape to console in binary #### Warning : CPU intensive task ''' temp = "" for li in self.shapeMatrix: for num in li: temp+=str(num) temp+="\n" print(temp) def displayShape(self): ''' Displays shape as a image ''' (arr2png(self.shapeMatrix)).show() def isPointInCircle(self,ptX,ptY,radius): if( (ptX-radius)**2 + (ptY-(self.width*const.sampl/2))**2 <= radius**2 ): return(True) else: return(False) def __generateShapeMatrix__(self,radius,type,angle): ''' Generates 2D binary shape matrix ''' riu = radius*const.sampl # riu => radius in micrometers (u kind of looks like Mu) # type 1 cone # here, radius and height are the same if(type==1): halfWidth = sin(radians(self.theta/2)) * self.slantHeight self.width = round(2 * halfWidth) hiu = riu # hiu => height in micrometers (u kind of looks like Mu) wiu = self.width*const.sampl # wiu => width in micrometers (u kind of looks like Mu) self.shapeFrameDimension = [wiu,hiu] # shapeFrameDimension changes on tilting shapeSkeleton = [[0]*wiu for _ in range(hiu)] xh = round(((riu*riu) - (wiu/2)**2)**0.5) pointy = [wiu/2,-hiu] Intercept_1 = [0,-hiu+xh] Intercept_2 = [wiu,-hiu+xh] for i in range(hiu): for j in range(wiu): currentPoint = [j,-i] if(self.isPointInCircle(i,j,riu)): shapeSkeleton[i][j]=1 if(pospl(pointy,Intercept_1,currentPoint)==1): shapeSkeleton[i][j]=0 if(pospl(pointy,Intercept_2,currentPoint)==-1): shapeSkeleton[i][j]=0 else: # type 2 cone here dh = -1*cos(radians(self.theta/2))*riu h = riu wiu = round(2*riu) self.width = 2*radius hiu = round(h+dh) # actual height of the frame self.shapeFrameDimension = [wiu,hiu] # shapeFrameDimension changes on tilting shapeSkeleton = [[0]*wiu for _ in range(hiu)] phi = 360-self.theta dw = round(riu*sin(radians(phi/2))) pointy = [wiu/2,-riu] Intercept_1 = [(wiu/2)-dw,-hiu] Intercept_2 = [(wiu/2)+dw,-hiu] for i in range(hiu): for j in range(wiu): currentPoint = [j,-i] if(self.isPointInCircle(i,j,riu)): shapeSkeleton[i][j]=1 if(pospl(pointy,Intercept_1,currentPoint)==1 and pospl(pointy,Intercept_2,currentPoint)==-1): shapeSkeleton[i][j]=0 self.dimensions=[self.cone_height*const.sampl,self.cone_radius*const.sampl,'dm,dm'] # only angle of dimension changes on tilting self.shapeMatrix = shapeSkeleton if(angle!=0): self.tilt(angle) class Canvas: ''' Give length and height in milli-meter( mm ) ''' def __init__(self,length,height): self.uid = ri(0,1000000000000000000000) self.myShape="CANVAS" self.length = length self.height = height self.surfaceArea = length*height self.__generateShapeMatrix__(length,height) def regenerateSelf(self): self.__generateShapeMatrix__(self.length,self.height) def __repr__(self): return(f"Object Shape \t: {self.myShape}\nSide Length \t: {self.length} mm\nSide Height \t: {self.height} mm\nshapeFrameDimension \t: {self.shapeFrameDimension}") def print(self): ''' Prints Object parameters to console ''' print(repr(self)) def printShape(self): ''' Prints shape to console in binary #### Warning : CPU intensive task ''' temp = "" for li in self.shapeMatrix: for num in li: temp+=str(num) temp+="\n" print(temp) def displayShape(self): ''' Displays shape as a image ''' (arr2png(self.shapeMatrix)).show() def __generateShapeMatrix__(self,length,height,angle=0): ''' Generates 2D binary shape matrix ''' self.dimensions=[self.length*const.sampl,self.height*const.sampl,'dm,dm'] liu = length*const.sampl # liu => length in micrometers (u kind of looks like Mu) hiu = height*const.sampl # hiu => height in micrometers (u kind of looks like Mu) self.shapeMatrix = [[0]*liu]*hiu self.shapeFrameDimension = [liu,hiu] # shapeFrameDimension changes on tilting class customShape: ''' Give side in milli-meter( mm ) and angle in degrees( ° ) ''' def __init__(self,filepath,shapename,angle=0,cornerCompatible=1,triangleCompatible=0): self.uid = ri(0,1000000000000000000000) self.myShape=shapename self.angle = 0 self.cornerCompatible = cornerCompatible self.triangleCompatible = triangleCompatible self.__generateShapeMatrix__(filepath,angle) def regenerateSelf(self): self.__generateShapeMatrix__(self.length,self.angle) def __repr__(self): return(f"Object Shape \t: {self.myShape}\nShape Tilt \t: {self.angle} °\nshapeFrameDimension \t: {self.shapeFrameDimension}") def print(self): ''' Prints Object parameters to console ''' print(repr(self)) def tilt(self,angle): self.angle += angle self.shapeMatrix=rotate(evenize(self.shapeMatrix),angle) self.shapeFrameDimension = [len(self.shapeMatrix[0]),len(self.shapeMatrix)] def printShape(self): ''' Prints shape to console in binary #### Warning : CPU intensive task ''' temp = "" for li in self.shapeMatrix: for num in li: temp+=str(num) temp+="\n" print(temp) def displayShape(self): ''' Displays shape as a image ''' (arr2png(self.shapeMatrix)).show() def __generateShapeMatrix__(self,filepath,angle=0): ''' Generates 2D binary shape matrix ''' self.shapeMatrix = imgTrim(png2arr(filepath)) arr2png(self.shapeMatrix,filepath.replace(".png","")) if(angle==0 or angle%360==0): pass else: self.tilt(angle)
StarcoderdataPython
8005180
from django.db import models from django.utils.safestring import mark_safe class Identity(models.Model): first_name = models.CharField(max_length=30, null=True) last_name = models.CharField(max_length=30, null=True, help_text=mark_safe("<strong>Here's some HTML!</strong>")) class Person(models.Model): identity = models.OneToOneField(Identity, related_name='person', on_delete=models.PROTECT)
StarcoderdataPython
3641
<gh_stars>10-100 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ An `image.layer` is a set of `feature` with some additional parameters. Its purpose to materialize those `feature`s as a btrfs subvolume in the per-repo `buck-image/out/volume/targets`. We call the subvolume a "layer" because it can be built on top of a snapshot of its `parent_layer`, and thus can be represented as a btrfs send-stream for more efficient storage & distribution. The Buck output of an `image.layer` target is a JSON file with information on how to find the resulting layer in the per-repo `buck-image/out/volume/targets`. See `SubvolumeOnDisk.to_json_file`. ## Implementation notes The implementation of this converter deliberately minimizes the amount of business logic in its command. The converter must include **only** our interactions with the buck target graph. Everything else should be delegated to subcommands. ### Command In composing the `bash` command, our core maxim is: make it a hermetic function of the converter's inputs -- do not read data from disk, do not insert disk paths into the command, do not do anything that might cause the bytes of the command to vary between machines or between runs. To achieve this, we use Buck macros to resolve all paths, including those to helper scripts. We rely on environment variables or pipes to pass data between the helper scripts. Another reason to keep this converter minimal is that `buck test` cannot make assertions about targets that fail to build. Since we only have the ability to test the "good" targets, it behooves us to put most logic in external scripts, so that we can unit-test its successes **and** failures thoroughly. ### Output We mark `image.layer` uncacheable, because there's no easy way to teach Buck to serialize a btrfs subvolume (for that, we have `package.new`). That said, we should still follow best practices to avoid problems if e.g. the user renames their repo, or similar. These practices include: - The output JSON must store no absolute paths. - Store Buck target paths instead of paths into the output directory. ### Dependency resolution An `image.layer` consumes a set of `feature` outputs to decide what to put into the btrfs subvolume. These outputs are actually just JSON files that reference other targets, and do not contain the data to be written into the image. Therefore, `image.layer` has to explicitly tell buck that it needs all direct dependencies of its `feature`s to be present on disk -- see our `attrfilter` queries below. Without this, Buck would merrily fetch the just the `feature` JSONs from its cache, and not provide us with any of the buid artifacts that comprise the image. We do NOT need the direct dependencies of the parent layer's features, because we treat the parent layer as a black box -- whatever it has laid down in the image, that's what it provides (and we don't care about how). The consequences of this information hiding are: - Better Buck cache efficiency -- we don't have to download the dependencies of the ancestor layers' features. Doing that would be wasteful, since those bits are redundant with what's in the parent. - Ability to use genrule image layers / apply non-pure post-processing to a layer. In terms of engineering, both of these non-pure approaches are a terrible idea and a maintainability headache, but they do provide a useful bridge for transitioning to Buck image builds from legacy imperative systems. - The image compiler needs a litte extra code to walk the parent layer and determine what it provides. - We cannot have "unobservable" dependencies between features. Since feature dependencies are expected to routinely cross layer boundaries, feature implementations are forced only to depend on data that can be inferred from the filesystem -- since this is all that the parent layer implementation can do. NB: This is easy to relax in the future by writing a manifest with additional metadata into each layer, and using that metadata during compilation. """ load(":compile_image_features.bzl", "compile_image_features") load(":image_layer_utils.bzl", "image_layer_utils") load(":image_utils.bzl", "image_utils") def image_layer( name, parent_layer = None, features = None, flavor = None, flavor_config_override = None, antlir_rule = "user-internal", **image_layer_kwargs): """ Arguments - `parent_layer`: The name of another `image_layer` target, on top of which the current layer will install its features. - `features`: List of `feature` target paths and/or nameless structs from `feature.new`. - `flavor`: Picks default build options for the layer, including `build_appliance`, RPM installer, and others. See `flavor_helpers.bzl` for details. - `flavor_config_override`: A struct that can override the default values fetched from `REPO_CFG[flavor].flavor_to_config`. - `mount_config`: Specifies how this layer is mounted in the `mounts` field of a `feature` of a parent layer. See the field in `_image_layer_impl` in `image_layer_utils.bzl` - `runtime`: A list of desired helper buck targets to be emitted. `container` is always included in the list by default. See the field in `_image_layer_impl` in `image_layer_utils.bzl` and the [docs](/docs/tutorials/helper-buck-targets#imagelayer) for the list of possible helpers, their respective behaviours, and how to invoke them. """ image_layer_utils.image_layer_impl( _rule_type = "image_layer", _layer_name = name, # Build a new layer. It may be empty. _make_subvol_cmd = compile_image_features( name = name, current_target = image_utils.current_target(name), parent_layer = parent_layer, features = features, flavor = flavor, flavor_config_override = flavor_config_override, ), antlir_rule = antlir_rule, **image_layer_kwargs )
StarcoderdataPython
11235848
# If you want to use IPv6, then: # - replace AF_INET with AF_INET6 everywhere # - use the hostname "2.pool.ntp.org" # (see: https://news.ntppool.org/2011/06/continuing-ipv6-deployment/) import trio import struct import datetime def make_query_packet(): """Construct a UDP packet suitable for querying an NTP server to ask for the current time.""" # The structure of an NTP packet is described here: # https://tools.ietf.org/html/rfc5905#page-19 # They're always 48 bytes long, unless you're using extensions, which we # aren't. packet = bytearray(48) # The first byte contains 3 subfields: # first 2 bits: 11, leap second status unknown # next 3 bits: 100, NTP version indicator, 0b100 == 4 = version 4 # last 3 bits: 011, NTP mode indicator, 0b011 == 3 == "client" packet[0] = 0b11100011 # For an outgoing request, all other fields can be left as zeros. return packet def extract_transmit_timestamp(ntp_packet): """Given an NTP packet, extract the "transmit timestamp" field, as a Python datetime.""" # The transmit timestamp is the time that the server sent its response. # It's stored in bytes 40-47 of the NTP packet. See: # https://tools.ietf.org/html/rfc5905#page-19 encoded_transmit_timestamp = ntp_packet[40:48] # The timestamp is stored in the "NTP timestamp format", which is a 32 # byte count of whole seconds, followed by a 32 byte count of fractions of # a second. See: # https://tools.ietf.org/html/rfc5905#page-13 seconds, fraction = struct.unpack("!II", encoded_transmit_timestamp) # The timestamp is the number of seconds since January 1, 1900 (ignoring # leap seconds). To convert it to a datetime object, we do some simple # datetime arithmetic: base_time = datetime.datetime(1900, 1, 1) offset = datetime.timedelta(seconds=seconds + fraction / 2**32) return base_time + offset async def main(): print("Our clock currently reads (in UTC):", datetime.datetime.utcnow()) # Look up some random NTP servers. # (See www.pool.ntp.org for information about the NTP pool.) servers = await trio.socket.getaddrinfo( "pool.ntp.org", # host "ntp", # port family=trio.socket.AF_INET, # IPv4 type=trio.socket.SOCK_DGRAM, # UDP ) # Construct an NTP query packet. query_packet = make_query_packet() # Create a UDP socket udp_sock = trio.socket.socket( family=trio.socket.AF_INET, # IPv4 type=trio.socket.SOCK_DGRAM, # UDP ) # Use the socket to send the query packet to each of the servers. print("-- Sending queries --") for server in servers: address = server[-1] print("Sending to:", address) await udp_sock.sendto(query_packet, address) # Read responses from the socket. print("-- Reading responses (for 10 seconds) --") with trio.move_on_after(10): while True: # We accept packets up to 1024 bytes long (though in practice NTP # packets will be much shorter). data, address = await udp_sock.recvfrom(1024) print("Got response from:", address) transmit_timestamp = extract_transmit_timestamp(data) print("Their clock read (in UTC):", transmit_timestamp) trio.run(main)
StarcoderdataPython
1706223
"""Contains a batch class to segmentation task.""" import numpy as np from PIL import Image from batchflow import ImagesBatch, action, inbatch_parallel class MnistBatch(ImagesBatch): """ Batch can create images with specified size and noisy with parts of other digits. """ components = 'images', 'labels', 'masks', 'big_img' @inbatch_parallel(init='indices') def _paste_img(self, ix, coord, size, src, dst): img = self.get(ix, src) if src != 'labels' else Image.new('L', (28, 28), color=1) img.thumbnail(size, Image.ANTIALIAS) new_img = Image.new("L", size, "black") i = self.get_pos(None, src, ix) new_img.paste(img, [*coord[i]]) getattr(self, dst)[i] = new_img @action def create_big_img(self, coord, shape, src='images', dst='big_img'): """Creation image with specified size and put the image from batch to a random place. Parameters ---------- coord : list with size 2 x and y cooridates of image position shape : int or list crated image's shape src : str component's name from which the data will be obtained dst : str component's name into which the data will be stored Returns ------- self """ shape = [shape]*2 if isinstance(shape, int) else shape for sour, dest in zip(src, dst): if getattr(self, dest) is None: setattr(self, dest, np.array([None] * len(self.index))) self._paste_img(coord, shape, sour, dest) return self @action @inbatch_parallel(init='indices') def add_noize(self, ix, num_parts=80, src='big_img', dst='big_img'): """Adding the parts of numbers to the image. Parameters ---------- num_parts : int The number of the image's parts src : str component's name from which the data will be obtained dst : str component's name into which the data will be stored """ img = self.get(ix, src) ind = np.random.choice(self.indices, num_parts) hight, width = np.random.randint(1, 5, 2) coord_f = np.array([np.random.randint(10, 28-hight, len(ind)), \ np.random.randint(10, 28-width, len(ind))]) coord_t = np.array([np.random.randint(0, img.size[0]-hight, len(ind)), \ np.random.randint(0, img.size[1]-width, len(ind))]) for i, num_img in enumerate(np.array(ind)): crop_img = self.get(num_img, 'images') crop_img = crop_img.crop([coord_f[0][i], coord_f[1][i], \ coord_f[0][i]+hight, coord_f[1][i]+width]) img.paste(crop_img, list(coord_t[:, i])) local_ix = self.get_pos(None, dst, ix) getattr(self, dst)[local_ix] = img
StarcoderdataPython
11374098
<filename>aoc20181203a.py def parse(line): id, __, pos, size = line.split() return ( id[1:], [int(x) for x in pos[:-1].split(",")], [int(x) for x in size.split("x")], ) def aoc(data): cloth = {} for _, [x, y], [dx, dy] in [parse(cut) for cut in data.split("\n")]: for ddx in range(dx): for ddy in range(dy): cloth[(x + ddx, y + ddy)] = cloth.get((x + ddx, y + ddy), 0) + 1 total = 0 for cord in cloth.values(): if cord > 1: total += 1 return total
StarcoderdataPython
1774650
#!/usr/bin/env/python # -*- coding: utf-8 -*- # flake8: noqa __title__ = 'ciscoipphone' __version__ = '0.1.0' __author__ = '<NAME>' __license__ = 'MIT License' __copyright__ = 'Copyright 2015 <NAME>' # from . import base, services, utils # # __all__ = [base, services, utils] # Set default logging handler to avoid "No handler found" warnings. import logging try: # Python 2.7+ from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass logging.getLogger(__name__).addHandler(NullHandler())
StarcoderdataPython
5054837
<gh_stars>0 from collections import defaultdict import sys class Graph: def __init__(self, V): self.V = V self.graph=defaultdict(list) self.indegree = [0]*(self.V) self.outdegree = [0]*(self.V) def Check(self): for ele in range(self.V): if(self.indegree[ele]!=self.outdegree[ele]): print("No euler path found.") sys.exit() def addEdge(self, u, v): self.graph[u].append(v) self.indegree[v]+=1 self.outdegree[u]+=1 def DFSUtil(self, Visited, Stack, i): Visited[i]=True for k in self.graph[i]: if(Visited[k]==False): self.DFSUtil(Visited, Stack, k) Stack.insert(0, i) def DFS(self): Visited=[False]*(self.V) Stack=[] for i in range(self.V): if(Visited[i]==False): self.DFSUtil(Visited, Stack, i) self.Transpose(Stack) def Transpose(self, Stack): g = Graph(self.V) for u in range(self.V): for v in self.graph[u]: g.addEdge(v, u) self.SCC(g, Stack) def FindSCC(self, ele, Visited): Visited[ele]=True #print(ele, end=" ") for i in self.graph[ele]: if(Visited[i]==False): self.FindSCC(i, Visited) def SCC(self, g, Stack): Visited=[False]*(self.V) count=0 for ele in Stack: if(Visited[ele]==False): count+=1 if(count<=1): g.FindSCC(ele, Visited) else: print("No Euler Path") sys.exit() print("Yes") g=Graph(5) g.addEdge(1,0) g.addEdge(0,2) g.addEdge(2,1) g.addEdge(0,3) g.addEdge(3,4) g.addEdge(4,0) g.Check() g.DFS()
StarcoderdataPython
121831
<filename>zbarcam/zbarcam.py<gh_stars>0 import os from collections import namedtuple import PIL import zbarlight from kivy.app import App from kivy.clock import Clock from kivy.lang import Builder from kivy.properties import ListProperty from kivy.uix.anchorlayout import AnchorLayout from kivy.utils import platform # Pillow is not currently available for Android: # https://github.com/kivy/python-for-android/pull/786 try: # Pillow PIL.Image.frombytes PIL.Image.Image.tobytes except AttributeError: # PIL PIL.Image.frombytes = PIL.Image.frombuffer PIL.Image.Image.tobytes = PIL.Image.Image.tostring MODULE_DIRECTORY = os.path.dirname(os.path.realpath(__file__)) Builder.load_file(os.path.join(MODULE_DIRECTORY, "zbarcam.kv")) class ZBarCam(AnchorLayout): """ Widget that use the Camera and zbar to detect qrcode. When found, the `symbols` will be updated. """ resolution = ListProperty([640, 480]) symbols = ListProperty([]) Symbol = namedtuple('Symbol', ['type', 'data']) # checking all possible types by default code_types = ListProperty(zbarlight.Symbologies.keys()) # TODO: handle code types def __init__(self, **kwargs): super(ZBarCam, self).__init__(**kwargs) Clock.schedule_once(lambda dt: self._setup()) def _setup(self): """ Postpones some setup tasks that require self.ids dictionary. """ self._remove_shoot_button() self._enable_android_autofocus() self.xcamera._camera.bind(on_texture=self._on_texture) # self.add_widget(self.xcamera) def _remove_shoot_button(self): """ Removes the "shoot button", see: https://github.com/kivy-garden/garden.xcamera/pull/3 """ xcamera = self.xcamera shoot_button = xcamera.children[0] xcamera.remove_widget(shoot_button) def _enable_android_autofocus(self): """ Enables autofocus on Android. """ if not self.is_android(): return camera = self.xcamera._camera._android_camera params = camera.getParameters() params.setFocusMode('continuous-video') camera.setParameters(params) def _on_texture(self, instance): self._detect_qrcode_frame( instance=None, camera=instance, texture=instance.texture) def _detect_qrcode_frame(self, instance, camera, texture): image_data = texture.pixels size = texture.size fmt = texture.colorfmt.upper() pil_image = PIL.Image.frombytes(mode=fmt, size=size, data=image_data) # calling `zbarlight.scan_codes()` for every single `code_type`, # zbarlight doesn't yet provide a more efficient way to do this, see: # https://github.com/Polyconseil/zbarlight/issues/23 symbols = [] for code_type in self.code_types: codes = zbarlight.scan_codes(code_type, pil_image) or [] for code in codes: symbol = ZBarCam.Symbol(type=code_type, data=code) symbols.append(symbol) self.symbols = symbols @property def xcamera(self): return self.ids['xcamera'] def start(self): self.xcamera.play = True def stop(self): self.xcamera.play = False def is_android(self): return platform == 'android' DEMO_APP_KV_LANG = """ BoxLayout: orientation: 'vertical' ZBarCam: id: zbarcam code_types: 'qrcode', 'ean13' Label: size_hint: None, None size: self.texture_size[0], 50 text: ', '.join([str(symbol.data) for symbol in zbarcam.symbols]) """ class DemoApp(App): def build(self): return Builder.load_string(DEMO_APP_KV_LANG) if __name__ == '__main__': DemoApp().run()
StarcoderdataPython
6534661
<reponame>deepakkt/aasaan # -*- coding: utf-8 -*- """ Create ORS programs for newly defined programs in Aasaan """ from datetime import date import json from collections import Counter from django.core.management.base import BaseCommand from schedulemaster.models import ProgramSchedule, ProgramScheduleCounts, \ ProgramCountMaster, ProgramReceiptAmounts from config.ors.ors import ORSInterface from config.models import get_configuration from django.conf import settings from utils.datedeux import DateDeux def _return_category(category_name, category_set): for each_category in category_set: if each_category.category.count_category == category_name: return each_category return None def _create_or_update(fields, values, schedule): _counts, _amounts = values categories = schedule.programreceiptamounts_set.all() for field in fields: _base_cat = ProgramCountMaster.objects.get(count_category=field) _model_cat = _return_category(field, categories) or ProgramReceiptAmounts() _model_cat.program = schedule _model_cat.category = _base_cat _model_cat.receipt_count = _counts[field] _model_cat.receipt_amount = _amounts[field] _model_cat.save() class Command(BaseCommand): help = "Sync ereceipts amounts" def add_arguments(self, parser): parser.add_argument('start_date', nargs='?', type=str) def handle(self, *args, **options): _fields_to_update = ["Online Receipts", "Cash Receipts", "Cheque Receipts", "Creditcard Receipts"] if options['start_date']: _start_date = DateDeux.fromisodate(options['start_date']) print('Using start date of ', _start_date) _schedules = ProgramSchedule.objects.filter(start_date__gte=_start_date) else: reference_date = DateDeux.today() - 50 print('Using start date of ', reference_date) _schedules = ProgramSchedule.objects.filter(start_date__gte=reference_date) for each_schedule in _schedules: _counts = Counter() _amounts = Counter() print(each_schedule.id, each_schedule) try: _receipts = json.loads(each_schedule.receipts) except: _receipts = [] if not _receipts: print("No receipts found") continue for receipt in _receipts: _mode = receipt.get("mode", "Unknown") _mode = _mode.title() + " Receipts" _amount = receipt.get("amount", 0) _counts[_mode] += 1 _amounts[_mode] += _amount print(_counts, _amounts) _create_or_update(_fields_to_update, (_counts, _amounts), each_schedule)
StarcoderdataPython
9706782
<gh_stars>1-10 import datetime import pytest import edera.helpers from edera import routine from edera import Timer from edera.consumers import BasicConsumer from edera.exceptions import StorageOperationError from edera.invokers import MultiThreadedInvoker from edera.monitoring import MonitoringAgent from edera.monitoring import MonitoringUI from edera.monitoring import MonitorWatcher from edera.monitoring.snapshot import TaskLogUpdate from edera.monitoring.snapshot import TaskStatusUpdate from edera.monitoring.snapshot import WorkflowUpdate from edera.storages import InMemoryStorage @pytest.fixture def monitor(): return InMemoryStorage() @pytest.fixture def consumer(monitor): return BasicConsumer(lambda kv: monitor.put(*kv)) @pytest.fixture def agent(monitor, consumer): result = MonitoringAgent("agent", monitor, consumer) result.register() result.push(WorkflowUpdate({"X": {"O"}, "Y": {"O"}, "O": set()}, {"X"}, {})) timestamp = edera.helpers.now() result.push(TaskStatusUpdate("O", "running", timestamp)) result.push(TaskLogUpdate("O", "https://example.com", timestamp)) result.push(TaskStatusUpdate("O", "completed", timestamp + datetime.timedelta(days=1, hours=2, minutes=3, seconds=4))) return result @pytest.fixture def watcher(monitor, agent): @routine def watch(): yield result.run.defer(delay=datetime.timedelta(milliseconds=10)) result = MonitorWatcher(monitor) timer = Timer(datetime.timedelta(milliseconds=200)) try: MultiThreadedInvoker({"w": watch}).invoke[timer]() except Timer.Timeout: pass return result @pytest.fixture def broken_watcher(mocker, watcher): mocker.patch.object(MonitoringAgent, "pull", side_effect=StorageOperationError) return watcher @pytest.yield_fixture def ui(watcher): application = MonitoringUI("caption", watcher) with application.test_client() as result: yield result @pytest.fixture def void_ui(): monitor = InMemoryStorage() watcher = MonitorWatcher(monitor) application = MonitoringUI("caption", watcher) with application.test_client() as result: yield result
StarcoderdataPython
1669675
""" Checks each line of a file for valid emails. Use Django's email validator regex. Store the result in one of 2 files: 1. valid emails. 2. invalid emails. NOTE: This project still fails on a case when the email has a trailing string. This is because the re.match() method only matches the beginning of the string. We should match the whole string. """ import re rough_email_validator = r'([^@|\s]+@[^@]+\.[^@|\s]+)' email_validator_re = re.compile(rough_email_validator) def build_emails_from_sample_file(filename): """ """ with open(filename, 'r') as f: l = list() for line in f: l.append(line.rstrip()) if len(l) < 1: raise Exception, "The file had no data." return l def write_list_to_file(mylist, output_filename): """ """ import json # move this to the top with open(output_filename, 'w') as f: json.dump(mylist, f) if __name__ == '__main__': """ Run tests for our module. """ SAMPLE_SOURCE_FILE = "source.txt" VALID_OUTPUT_FILE = "valid.txt" INVALID_OUTPUT_FILE = "invalid.txt" VALID_EMAILS = list() INVALID_EMAILS = list() for email in build_emails_from_sample_file(SAMPLE_SOURCE_FILE): if email_validator_re.match(email): print "Valid email: {}".format(email) VALID_EMAILS.append(email) else: print "Not a valid email: {}".format(email) INVALID_EMAILS.append(email) write_list_to_file(VALID_EMAILS, VALID_OUTPUT_FILE) write_list_to_file(INVALID_EMAILS, INVALID_OUTPUT_FILE)
StarcoderdataPython
1827616
<filename>ssseg/modules/models/segmentors/isanet/isanet.py ''' Function: Implementation of ISANet Author: <NAME> ''' import copy import math import torch import torch.nn as nn import torch.nn.functional as F from ..base import BaseModel from ..base import SelfAttentionBlock as _SelfAttentionBlock from ...backbones import BuildActivation, BuildNormalization '''Self-Attention Module''' class SelfAttentionBlock(_SelfAttentionBlock): def __init__(self, in_channels, feats_channels, norm_cfg, act_cfg, **kwargs): super(SelfAttentionBlock, self).__init__( key_in_channels=in_channels, query_in_channels=in_channels, transform_channels=feats_channels, out_channels=in_channels, share_key_query=False, query_downsample=None, key_downsample=None, key_query_num_convs=2, key_query_norm=True, value_out_num_convs=1, value_out_norm=False, matmul_norm=True, with_out_project=False, norm_cfg=copy.deepcopy(norm_cfg), act_cfg=copy.deepcopy(act_cfg) ) self.output_project = self.buildproject( in_channels=in_channels, out_channels=in_channels, num_convs=1, use_norm=True, norm_cfg=copy.deepcopy(norm_cfg), act_cfg=copy.deepcopy(act_cfg), ) '''forward''' def forward(self, x): context = super(SelfAttentionBlock, self).forward(x, x) return self.output_project(context) '''ISANet''' class ISANet(BaseModel): def __init__(self, cfg, **kwargs): super(ISANet, self).__init__(cfg, **kwargs) align_corners, norm_cfg, act_cfg = self.align_corners, self.norm_cfg, self.act_cfg # build isa module isa_cfg = cfg['isa'] self.down_factor = isa_cfg['down_factor'] self.in_conv = nn.Sequential( nn.Conv2d(isa_cfg['in_channels'], isa_cfg['feats_channels'], kernel_size=3, stride=1, padding=1, bias=False), BuildNormalization(norm_cfg['type'], (isa_cfg['feats_channels'], norm_cfg['opts'])), BuildActivation(act_cfg['type'], **act_cfg['opts']), ) self.global_relation = SelfAttentionBlock( in_channels=isa_cfg['feats_channels'], feats_channels=isa_cfg['isa_channels'], norm_cfg=copy.deepcopy(norm_cfg), act_cfg=copy.deepcopy(act_cfg) ) self.local_relation = SelfAttentionBlock( in_channels=isa_cfg['feats_channels'], feats_channels=isa_cfg['isa_channels'], norm_cfg=copy.deepcopy(norm_cfg), act_cfg=copy.deepcopy(act_cfg) ) self.out_conv = nn.Sequential( nn.Conv2d(isa_cfg['feats_channels'] * 2, isa_cfg['feats_channels'], kernel_size=3, stride=1, padding=1, bias=False), BuildNormalization(norm_cfg['type'], (isa_cfg['feats_channels'], norm_cfg['opts'])), BuildActivation(act_cfg['type'], **act_cfg['opts']), ) # build decoder decoder_cfg = cfg['decoder'] self.decoder = nn.Sequential( nn.Dropout2d(decoder_cfg['dropout']), nn.Conv2d(decoder_cfg['in_channels'], cfg['num_classes'], kernel_size=1, stride=1, padding=0) ) # build auxiliary decoder self.setauxiliarydecoder(cfg['auxiliary']) # freeze normalization layer if necessary if cfg.get('is_freeze_norm', False): self.freezenormalization() '''forward''' def forward(self, x, targets=None, losses_cfg=None): img_size = x.size(2), x.size(3) # feed to backbone network backbone_outputs = self.transforminputs(self.backbone_net(x), selected_indices=self.cfg['backbone'].get('selected_indices')) # feed to isa module feats = self.in_conv(backbone_outputs[-1]) residual = feats n, c, h, w = feats.size() loc_h, loc_w = self.down_factor glb_h, glb_w = math.ceil(h / loc_h), math.ceil(w / loc_w) pad_h, pad_w = glb_h * loc_h - h, glb_w * loc_w - w if pad_h > 0 or pad_w > 0: padding = (pad_w // 2, pad_w - pad_w // 2, pad_h // 2, pad_h - pad_h // 2) feats = F.pad(feats, padding) # --global relation feats = feats.view(n, c, glb_h, loc_h, glb_w, loc_w) # ----do permutation to gather global group feats = feats.permute(0, 3, 5, 1, 2, 4) feats = feats.reshape(-1, c, glb_h, glb_w) # ----apply attention within each global group feats = self.global_relation(feats) # --local relation feats = feats.view(n, loc_h, loc_w, c, glb_h, glb_w) # ----do permutation to gather local group feats = feats.permute(0, 4, 5, 3, 1, 2) feats = feats.reshape(-1, c, loc_h, loc_w) # ----apply attention within each local group feats = self.local_relation(feats) # --permute each pixel back to its original position feats = feats.view(n, glb_h, glb_w, c, loc_h, loc_w) feats = feats.permute(0, 3, 1, 4, 2, 5) feats = feats.reshape(n, c, glb_h * loc_h, glb_w * loc_w) if pad_h > 0 or pad_w > 0: feats = feats[:, :, pad_h//2: pad_h//2+h, pad_w//2: pad_w//2+w] feats = self.out_conv(torch.cat([feats, residual], dim=1)) # feed to decoder predictions = self.decoder(feats) # return according to the mode if self.mode == 'TRAIN': loss, losses_log_dict = self.forwardtrain( predictions=predictions, targets=targets, backbone_outputs=backbone_outputs, losses_cfg=losses_cfg, img_size=img_size, ) return loss, losses_log_dict return predictions '''return all layers''' def alllayers(self): all_layers = { 'backbone_net': self.backbone_net, 'in_conv': self.in_conv, 'global_relation': self.global_relation, 'local_relation': self.local_relation, 'out_conv': self.out_conv, 'decoder': self.decoder, } if hasattr(self, 'auxiliary_decoder'): all_layers['auxiliary_decoder'] = self.auxiliary_decoder return all_layers
StarcoderdataPython
3432138
<gh_stars>1-10 from django.conf.urls import include, patterns, url from django.views.decorators.cache import never_cache from . import views services_patterns = patterns( '', url('^paypal$', never_cache(views.paypal), name='amo.paypal'), ) urlpatterns = patterns( '', ('', include(services_patterns)), )
StarcoderdataPython
8105528
########################################################################## # NSAp - Copyright (C) CEA, 2013 - 2018 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html # for details. ########################################################################## """ A module with common functions. """ # System import import sys import getpass if sys.version_info[0] > 2: raw_input = input def logo(): """ Logo is ascii art using dancing font. Returns ------- logo: str the pisap logo. """ logo = """ ____ ____ ____ U ___ u ____ U _____ u ____ U /"___| __ __U | __")uU | _"\\ u \\/"_ \\/__ __ / __"| u\\| ___"|/U | _"\\ u \\| | u \\"\\ /"/ \\| _ \\/ \\| |_) |/ | | | |\\"\\ /"/<\\___ \\/ | _|" \\| |_) |/ | |/__ /\\ \\ /\\ / /\\ | |_) | | _ <.-,_| |_| |/\\ \\ /\\ / /\\ u___) | | |___ | _ < \\____|U \\ V V / U |____/ |_| \\_\\\\_)-\\___/U \\ V V / U|____/>> |_____| |_| \\_\\ _// \\\\ .-,_\\ /\\ /_,-._|| \\\\_ // \\\\_ \\\\ .-,_\\ /\\ /_,-. )( (__)<< >> // \\\\_ (__)(__) \\_)-' '-(_/(__) (__) (__) (__) (__) \\_)-' '-(_/ (__) (__) (__) (__) (__) """ return logo def ask_credential(login=None, password=None): """ Ask for a login and a password when not specified. Parameters ---------- login: str, default None a login. password: str, defualt None a password. Returns ------- login: str, default None a login. password: str, defualt None a password. """ if login is None: login = raw_input("Login:") if password is None: password = <PASSWORD>("Password for " + login + ":") return login, password
StarcoderdataPython
5150924
<reponame>iamrajee/ROS<filename>panda/scripts/pick_and_place_simple.py<gh_stars>10-100 #!/usr/bin/env python import rospy from moveit_python import * from moveit_msgs.msg import Grasp, PlaceLocation object_name="my_cube" # object_name="my_box1" rospy.init_node("moveit_py") s = PlanningSceneInterface("panda_link0") s.is_diff="true" # s.RobotState.is_diff="true" # eef_link="panda_leftfinger" eef_link="panda_link0" print "\n\n\n=============== Press `Enter` to add Box ==============\n" raw_input() cube_size=0.1 #s.addCube(object_name, 0.1, 1, 0, 0.5)# add a cube of 0.1m size, at [1, 0, 0.5] in the base_link frame cube_x=1 cube_y=0 cube_z=0.5 s.addBox(object_name, cube_size,cube_size,cube_size, cube_x, cube_y, cube_z) print "\n\n\n=============== Press `Enter` to list of object ==============\n" raw_input() for name in s.getKnownCollisionObjects(): print(name) print "\n\n\n=============== Press `Enter` to attach Box ==============\n" raw_input() s.attachBox(object_name, cube_size, cube_size, cube_size,cube_x, cube_y, cube_z, eef_link) print "\n\n\n=============== Press `Enter` to list of object ==============\n" raw_input() for name in s.getKnownCollisionObjects(): print(name) print "\n\n\n=============== Press `Enter` to list of attached object ==============\n" raw_input() for name in s.getKnownAttachedObjects(): print(name) if len(s.getKnownCollisionObjects() + s.getKnownAttachedObjects()) == 0: print("No objects in planning scene.") print "\n\n\n=============== Press `Enter` to pick cube ==============\n" raw_input() pp = PickPlaceInterface("panda_arm", "hand")# also takes a third parameter "plan_only" which defaults to False g = Grasp()# fill in g print(g) pp.pickup(object_name, [g, ], support_name = "supporting_surface") l = PlaceLocation()# fill in l print(l) pp.place(object_name, [l, ], goal_is_eef = True, support_name = "supporting_surface") print "\n\n\n=============== Press `Enter` to De-attach Box ==============\n" raw_input() s.removeAttachedObject(object_name) print "\n\n\n=============== Press `Enter` to remove cube ==============\n" raw_input() s.removeCollisionObject(object_name)# remove the cube
StarcoderdataPython
1852194
<reponame>tactlabs/randum def test_unique_clears(testdir): """Successive uses of the `randum` pytest fixture have the generated unique values cleared between functions.""" testdir.makepyfile( """ import pytest from randum.exceptions import UniquenessException NUM_SAMPLES = 100 def test_fully_exhaust_unique_booleans(randum): _dummy = [randum.boolean() for _ in range(NUM_SAMPLES)] randum.unique.boolean() randum.unique.boolean() with pytest.raises(UniquenessException): randum.unique.boolean() _dummy = [randum.boolean() for _ in range(NUM_SAMPLES)] def test_do_not_exhaust_booleans(randum): randum.unique.boolean() def test_fully_exhaust_unique_booleans_again(randum): _dummy = [randum.boolean() for _ in range(NUM_SAMPLES)] randum.unique.boolean() randum.unique.boolean() with pytest.raises(UniquenessException): randum.unique.boolean() _dummy = [randum.boolean() for _ in range(NUM_SAMPLES)] """, ) result = testdir.runpytest() result.assert_outcomes(passed=3)
StarcoderdataPython
9708761
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '.\multimatte_interface.ui' # # Created: Fri Jan 22 08:18:32 2016 # by: pyside-uic 0.2.15 running on PySide 1.2.4 # # WARNING! All changes made in this file will be lost! from PySide import QtCore, QtGui class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(360, 373) self.horizontalLayout_4 = QtGui.QHBoxLayout(Form) self.horizontalLayout_4.setObjectName("horizontalLayout_4") spacerItem = QtGui.QSpacerItem(57, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_4.addItem(spacerItem) self.verticalLayout_2 = QtGui.QVBoxLayout() self.verticalLayout_2.setObjectName("verticalLayout_2") spacerItem1 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.verticalLayout_2.addItem(spacerItem1) self.verticalLayout = QtGui.QVBoxLayout() self.verticalLayout.setObjectName("verticalLayout") self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.mmValRadio = QtGui.QRadioButton(Form) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.mmValRadio.sizePolicy().hasHeightForWidth()) self.mmValRadio.setSizePolicy(sizePolicy) self.mmValRadio.setObjectName("mmValRadio") self.horizontalLayout.addWidget(self.mmValRadio) self.matRadio = QtGui.QRadioButton(Form) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.matRadio.sizePolicy().hasHeightForWidth()) self.matRadio.setSizePolicy(sizePolicy) self.matRadio.setChecked(True) self.matRadio.setObjectName("matRadio") self.horizontalLayout.addWidget(self.matRadio) self.animCheckBox = QtGui.QCheckBox(Form) self.animCheckBox.setObjectName("animCheckBox") self.horizontalLayout.addWidget(self.animCheckBox) self.verticalLayout.addLayout(self.horizontalLayout) self.horizontalLayout_3 = QtGui.QHBoxLayout() self.horizontalLayout_3.setObjectName("horizontalLayout_3") self.mmValBox = QtGui.QSpinBox(Form) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.mmValBox.sizePolicy().hasHeightForWidth()) self.mmValBox.setSizePolicy(sizePolicy) self.mmValBox.setObjectName("mmValBox") self.horizontalLayout_3.addWidget(self.mmValBox) self.mmValButton = QtGui.QPushButton(Form) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.mmValButton.sizePolicy().hasHeightForWidth()) self.mmValButton.setSizePolicy(sizePolicy) self.mmValButton.setObjectName("mmValButton") self.horizontalLayout_3.addWidget(self.mmValButton) self.randButton = QtGui.QPushButton(Form) self.randButton.setObjectName("randButton") self.horizontalLayout_3.addWidget(self.randButton) self.verticalLayout.addLayout(self.horizontalLayout_3) spacerItem2 = QtGui.QSpacerItem(20, 10, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed) self.verticalLayout.addItem(spacerItem2) self.line = QtGui.QFrame(Form) self.line.setFrameShape(QtGui.QFrame.HLine) self.line.setFrameShadow(QtGui.QFrame.Sunken) self.line.setObjectName("line") self.verticalLayout.addWidget(self.line) spacerItem3 = QtGui.QSpacerItem(20, 10, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed) self.verticalLayout.addItem(spacerItem3) self.horizontalLayout_2 = QtGui.QHBoxLayout() self.horizontalLayout_2.setObjectName("horizontalLayout_2") spacerItem4 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_2.addItem(spacerItem4) self.renderButton = QtGui.QPushButton(Form) self.renderButton.setObjectName("renderButton") self.horizontalLayout_2.addWidget(self.renderButton) spacerItem5 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_2.addItem(spacerItem5) self.verticalLayout.addLayout(self.horizontalLayout_2) self.verticalLayout_2.addLayout(self.verticalLayout) spacerItem6 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.verticalLayout_2.addItem(spacerItem6) self.horizontalLayout_4.addLayout(self.verticalLayout_2) spacerItem7 = QtGui.QSpacerItem(57, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_4.addItem(spacerItem7) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8)) self.mmValRadio.setText(QtGui.QApplication.translate("Form", "mmVal", None, QtGui.QApplication.UnicodeUTF8)) self.matRadio.setText(QtGui.QApplication.translate("Form", "Material", None, QtGui.QApplication.UnicodeUTF8)) self.animCheckBox.setText(QtGui.QApplication.translate("Form", "Animation", None, QtGui.QApplication.UnicodeUTF8)) self.mmValButton.setText(QtGui.QApplication.translate("Form", "Set mmVal", None, QtGui.QApplication.UnicodeUTF8)) self.randButton.setText(QtGui.QApplication.translate("Form", "Randomize", None, QtGui.QApplication.UnicodeUTF8)) self.renderButton.setText(QtGui.QApplication.translate("Form", "Render", None, QtGui.QApplication.UnicodeUTF8))
StarcoderdataPython
6553435
<reponame>georgsp/mdmTerminal2<filename>scripts/tester.py #!/usr/bin/env python3 import base64 import cmd as cmd__ import hashlib import json import socket import time from threading import Thread, Lock ERRORS = (BrokenPipeError, ConnectionResetError, ConnectionRefusedError, OSError) CRLF = b'\r\n' class Client: def __init__(self, address: tuple, token, chunk_size=1024, threading=False, is_logger=False, api=True): self.chunk_size = chunk_size self.work, self.connect = False, False self.address = address self.is_logger = is_logger self.api = api self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.client.settimeout(10 if not (is_logger or threading) else None) self.token = token self.thread = Thread(target=self._run) if threading else None self._lock = Lock() self.api_list = dict() self._results = dict() try: self.client.connect(address) except ERRORS as err: print('Ошибка подключения к {}:{}. {}: {}'.format(*address, err.errno, err.strerror)) else: self.connect = True print('Подключено к {}:{}'.format(*address)) if self.connect and self.thread: self.work = True self.thread.start() if self.connect: self._auth() def _run(self): try: self._read_loop() finally: print('Отключено от {}:{}'.format(*self.address)) self.work = False self.connect = False self.client.close() def _auth(self): if self.token: cmd = json.dumps({ 'method': 'authorization', 'params': [hashlib.sha512(self.token.encode()).hexdigest()], 'id': 'authorization', }).encode() self._send(cmd) def send(self, cmd): self._send('\r\n'.join(cmd.replace('\\n', '\n').split('\n')).encode() + (CRLF if not self.thread else b'')) if self.connect and not self.thread: self._run() def _send(self, data: bytes): if not self.connect: return try: with self._lock: self.client.send(data + CRLF) except ERRORS as e: print('Write error {}:{}:{}'.format(*self.address, e)) self.connect = False def _read_loop(self): data = b'' stage = 1 while self.connect: try: chunk = self.client.recv(self.chunk_size) except ERRORS: break if not chunk: break data += chunk while CRLF in data: line, data = data.split(CRLF, 1) if not line: return line = line.decode() if self.is_logger: print(line) continue if self.thread and self.token and stage: stage = self._handshake(line, stage) if stage < 0: return continue if line.startswith('{') and line.endswith('}'): # json? json! result = self.parse_json(line) if result: self._send(result.encode()) continue print('Ответ: {}'.format(line)) def _handshake(self, line: str, stage: int): try: data = json.loads(line) if not isinstance(data, dict): raise TypeError('Data must be dict type') except (json.decoder.JSONDecodeError, TypeError, ValueError) as e: print('Ошибка декодирования: {}'.format(e)) return -1 if 'result' in data and data.get('id') == 'upgrade duplex': params = ['cmd', 'talking', 'record', 'updater', 'backup', 'manual_backup'] self._send(json.dumps({'method': 'subscribe', 'params': params}, ensure_ascii=False).encode()) id_ = hashlib.sha256(str(time.time()).encode()).hexdigest() self._send(json.dumps({'method': 'info', 'params': ['*'], 'id': id_}, ensure_ascii=False).encode()) self._results[id_] = self.api_list return 0 return stage def stop(self): if self.thread and self.work: self.work = False self.connect = False self.client.shutdown(socket.SHUT_RD) self.client.close() self.thread.join(10) def parse_json(self, data: str): try: data = json.loads(data) if not isinstance(data, dict): raise TypeError('Data must be dict type') except (json.decoder.JSONDecodeError, TypeError) as e: return print('Ошибка декодирования: {}'.format(e)) if 'error' in data: result = (data.get('id', 'null'), data['error'].get('code'), data['error'].get('message')) print('Терминал сообщил об ошибке {} [{}]: {}'.format(*result)) if result[0] != 'null': self._results.pop(result[0], None) return if 'method' in data: if isinstance(data['method'], str) and data['method'].startswith('notify.') and self.api: notify = data['method'].split('.', 1)[1] info = data.get('params') if isinstance(info, dict): args = info.get('args') kwargs = info.get('kwargs') if isinstance(args, list) and len(args) == 1 and not kwargs: info = args[0] if isinstance(info, bool): info = 'ON' if info else 'OFF' elif isinstance(kwargs, dict) and not args: info = kwargs print('Уведомление: {}: {}'.format(notify, info)) if notify == 'cmd': tts = data.get('params', {}).get('kwargs', {}).get('qry', '') if tts: return json.dumps({'method': 'tts', 'params': {'text': tts}}, ensure_ascii=False) return cmd = data.get('id') data = data.get('result') if isinstance(data, dict): result = parse_dict(cmd, data) elif isinstance(data, str): result = parse_str(cmd, data) else: result = data if data is not None else 'null' if result is not None: line = None if cmd == 'ping': line = parse_ping(result) elif cmd == 'backup.list' and isinstance(result, list): line = parse_backup_list(result) elif cmd in self._results: ok = isinstance(result[1], dict) and isinstance(result[1].get('cmd'), dict) if ok: self._results[cmd].clear() self._results[cmd].update(result[1]['cmd']) if ok: return None line = line or 'Ответ на {}: {}'.format(repr(cmd), result) print(line) class TestShell(cmd__.Cmd): intro = 'Welcome to the test shell. Type help or ? to list commands.\n' prompt = '~# ' def __init__(self): super().__init__() self._ip = '127.0.0.1' self._port = 7999 self._token = '' self.chunk_size = 1024 self._client = None self._api = True def __del__(self): self._duplex_off() def _send_json(self, cmd: str, data='', is_logger=False): self._send(json.dumps({'method': cmd, 'params': [data], 'id': cmd}, ensure_ascii=False), is_logger) def _send_true_json(self, cmd: str, data: dict or list): self._send(json.dumps({'method': cmd, 'params': data, 'id': cmd}, ensure_ascii=False)) def _send(self, cmd: str, is_logger=False): if self._client: if not self._client.connect or is_logger: self._duplex_off() else: self._client.send(cmd) else: client = Client((self._ip, self._port), self._token, self.chunk_size, is_logger=is_logger, api=self._api) client.send(cmd) def _duplex_off(self): if self._client: self._client.stop() self._client = None print('Stop duplex') def _duplex(self): if self._client and self._client.work: self._duplex_off() else: print('Start duplex') self._client = Client((self._ip, self._port), self._token, self.chunk_size, True, api=self._api) def _is_duplex(self) -> bool: return self._client and not self._client.is_logger and self._client.work and self._client.connect def _send_says(self, cmd: str, data: str): test = data.rsplit('~', 1) if len(test) == 2 and len(test[1]) > 3: self._send_true_json(cmd, {'text': test[0], 'provider': test[1]}) else: self._send(cmd + ':' + data) def do_connect(self, arg): """Проверяет подключение к терминалу и позволяет задать его адрес. Аргументы: IP:PORT""" if arg: cmd = arg.split(':') if len(cmd) != 2: cmd = arg.split(' ') if len(cmd) > 2: return print('Ошибка парсинга. Аргументы: IP:PORT or IP or PORT') if len(cmd) == 1: cmd = cmd[0] if cmd.isdigit(): cmd = [self._ip, cmd] else: cmd = [cmd, self._port] try: self._port = int(cmd[1]) except ValueError: return print('Ошибка парсинга - порт не число: {}'.format(cmd[1])) self._ip = cmd[0] self._duplex_off() self._send('pause:') @staticmethod def do_exit(_): """Выход из оболочки""" print('Выход.') return True def do_voice(self, _): """Отправляет voice:.""" self._send('voice:') def do_tts(self, arg): """Отправляет фразу терминалу. Аргументы: фраза или фраза~провайдер""" if not arg: print('Добавьте фразу') else: self._send_says('tts', arg) def do_ttss(self, arg): """Отправляет фразы терминалу. Аргументы: фразы""" if not arg: print('Добавьте фразы') else: result = [{'method': 'tts', 'params': {'text': text}} for text in arg.split(' ')] self._send(json.dumps(result, ensure_ascii=False)) def do_ask(self, arg): """Отправляет ask терминалу. Аргументы: фраза или фраза~провайдер""" if not arg: print('Добавьте фразу') else: self._send_says('ask', arg) def do_api(self, _): """Отключить/включить показ уведомлений, для duplex mode""" self._api = not self._api if self._client: self._client.api = self._api print('Уведомления {}.'.format('включены' if self._api else 'отключены')) def do_pause(self, _): """Отправляет pause:.""" self._send('pause:') def do_save(self, _): """Отправляет команду на перезагрузку""" self._send('rec:save_1_1') def do_record(self, arg): """Запись образца для фразы. Аргументы: [Номер фразы (1-6)] [Номер образца (1-3)]""" cmd = get_params(arg, '[Номер фразы (1-6)] [Номер образца (1-3)]') if not cmd or not num_check(cmd): return self._send('rec:rec_{}_{}'.format(*cmd)) def do_play(self, arg): """Воспроизводит записанный образец. Аргументы: [Номер фразы (1-6)] [Номер образца (1-3)]""" cmd = get_params(arg, '[Номер фразы (1-6)] [Номер образца (1-3)]') if not cmd or not num_check(cmd): return self._send('rec:play_{}_{}'.format(*cmd)) def do_compile(self, arg): """Компилирует фразу. Аргументы: [Номер фразы (1-6)]""" cmd = get_params(arg, '[Номер фразы (1-6)]', count=1) if not cmd: return cmd = cmd[0] if num_check([cmd, 1]): self._send('rec:compile_{0}_{0}'.format(cmd)) def do_del(self, arg): """Удаляет модель. Аргументы: [Номер модели (1-6)]""" cmd = get_params(arg, '[Номер модели (1-6)]', count=1) if not cmd: return cmd = cmd[0] if num_check([cmd, 1]): self._send('rec:del_{0}_{0}'.format(cmd)) def do_update(self, _): """Обновить терминал. Аргументы: нет""" self._send('rec:update_0_0') def do_rollback(self, _): """Откатывает последнее обновление. Аргументы: нет""" self._send('rec:rollback_0_0') def do_ping(self, _): """Пинг. Аргументы: нет""" self._send_json('ping', str(time.time())) def do_list_models(self, _): """Список моделей. Аргументы: нет""" self._send_json('list_models') def do_recv_model(self, filename): """Запросить модель у терминала. Аргументы: имя файла""" self.chunk_size = 1024 * 1024 self._send_json('recv_model', filename) def do_log(self, _): """Подключает удаленного логгера к терминалу. Аргументы: нет""" self._send('remote_log', is_logger=True) def do_duplex(self, _): """Один сокет для всего. Включает и выключает""" self._duplex() if self._client: self._send_json('upgrade duplex') def do_raw(self, arg): """Отправляет терминалу любые данные. Аргументы: что угодно""" if not arg: print('Вы забыли данные') else: self._send(arg) def do_token(self, token: str): """Задать токен для авторизации. Аргументы: токен""" self._token = token def do_test_record(self, arg): """[filename] [phrase_time_limit]""" arg = arg.rsplit(' ', 1) if not arg[0]: print('Use [filename] [phrase_time_limit](optional)') return data = {'file': arg[0]} if len(arg) == 2: try: data['limit'] = float(arg[1]) except ValueError as e: print('limit must be numeric: {}'.format(e)) return self._send_true_json('test.record', data=data) def do_test_play(self, arg): """[file1,file2..fileN]""" self._send_true_json('test.play', data={'files': str_to_list(arg)}) def do_test_delete(self, arg): """[file1,file2..fileN]""" self._send_true_json('test.delete', data={'files': str_to_list(arg)}) def do_test_test(self, arg): """[provider1,provider2..providerN] [file1,file2..fileN]""" cmd = get_params(arg, '[provider1,provider2..providerN] [file1,file2..fileN]', to_type=None) if not cmd: return self._send_true_json('test.test', data={'providers': str_to_list(cmd[0]), 'files': str_to_list(cmd[1])}) def do_test_list(self, _): self._send_true_json('test.list', data={}) def do_info(self, arg): """Информация о команде""" self._send_json('info', data=arg) def do_events_list(self, _): """Список событий имеющих подписчиков""" if not self._is_duplex(): return print('Duplex must be active!') self._send_true_json('events_list', data=[]) def do_backup(self, _): """Создать бэкап""" self._send_json('backup.manual') def do_restore(self, filename): """Восстановить из бэкапа: filename""" if not filename: return print('Empty filename') self._send_json('backup.restore', filename) def do_backup_list(self, _): """Список бэкапов""" self._send_json('backup.list') def do_sre(self, text): """Обработает текст так, как если бы он был успешно распознан: текст""" self._send_json('sre', text) def do_r2(self, line): """ Улучшенный raw: method [params] [<] params - dict или строка. < - терминал не пришлет ответ. """ if not self._is_duplex(): return print('Duplex must be active!') try: result = self._r2_parser(line) except Exception as e: print(e) else: self._send(json.dumps(result, ensure_ascii=False)) def _r2_parser(self, line: str): if not line: raise RuntimeError('Empty line') line = line.split(' ', 1) method, line = line[0], line[1:] if method not in self._client.api_list: raise RuntimeError('Wrong method {}, allow: {}'.format(method, ', '.join(self._client.api_list.keys()))) if not line: return {'method': method, 'id': method} line = line[0] id_ = None if line.endswith(' <') : line = line[:-2] elif line == '<' or line.endswith('}<'): line = line[:-1] else: id_ = method if not line: return {'method': method, 'id': id_} if line.startswith('{') and line.endswith('}'): line = eval(line) if not isinstance(line, (dict, str)): raise RuntimeError('params must be dict or str') if isinstance(line, str) and self._client.api_list[method][1]: raise RuntimeError('{} accept only JSON-RPC'.format(method)) if not (self._client.api_list[method][0] or self._client.api_list[method][1]) and isinstance(line, dict): raise RuntimeError('{} accept only string params'.format(method)) line = [line] if isinstance(line, str) else line return {'method': method, 'params': line, 'id': id_} def str_to_list(line) -> list: return [el.strip() for el in line.split(',')] def num_check(cmd): if 6 <= cmd[0] <= 1: print('Номер фразы 1-6, не {}'.format(cmd[0])) return False if 3 <= cmd[1] <= 1: print('Номер образца 1-3, не {}'.format(cmd[1])) return False return True def get_params(arg, helps, seps=None, to_type=int or None, count=2): def err(): return print('Ошибка парсинга \'{}\'. Используйте: {}'.format(arg, helps)) seps = seps or [' '] for sep in seps: cmd = arg.split(sep) if len(cmd) == count: if to_type is not None: try: cmd = [to_type(test) for test in cmd] except ValueError: return err() return cmd return err() def base64_to_bytes(data): try: return base64.b64decode(data) except (ValueError, TypeError) as e: raise RuntimeError(e) def parse_dict(cmd, data): if cmd == 'recv_model': for key in ('filename', 'data'): if key not in data: return print('Не хватает ключа: {}'.format(key)) try: file_size = len(base64_to_bytes(data['data'])) except RuntimeError as e: return print('Ошибка декодирования data: {}'.format(e)) optional = ', '.join(['{}={}'.format(k, repr(data[k])) for k in ('username', 'phrase') if k in data]) result = 'Получен файл {}; данные: {}; размер {} байт'.format(data['filename'], optional, file_size) elif cmd == 'list_models': if len([k for k in ('models', 'allow') if isinstance(data.get(k, ''), list)]) < 2: return print('Недопустимое body: {}'.format(repr(data))) result = 'Все модели: {}; разрешенные: {}'.format( ', '.join(data['models']), ', '.join(data['allow']) ) elif cmd == 'info': for key in ('cmd', 'msg'): if key not in data: return print('Не хватает ключа в body: {}'.format(key)) flags = None if isinstance(data['cmd'], (list, dict)): data['cmd'] = ', '.join(x for x in data['cmd']) if isinstance(data['msg'], str) and '\n' in data['msg']: data['msg'] = '\n' + data['msg'] if isinstance(data.get('flags'), list) and data['flags']: flags = ', '.join(data['flags']) print('\nINFO: {}'.format(data['cmd'])) print('MSG: {}\n'.format(data['msg'])) if flags: print('FLAGS: {}\n'.format(flags)) return else: return cmd, data return result def parse_str(cmd, data): if cmd == 'ping': try: diff = time.time() - float(data) except (ValueError, TypeError): pass else: print('ping {} ms'.format(int(diff * 1000))) return return cmd, data def parse_ping(data): try: diff = time.time() - float(data[0]) except (ValueError, TypeError, IndexError): return None else: return 'ping {} ms'.format(int(diff * 1000)) def parse_backup_list(data: list): try: data = [[time.strftime('%Y.%m.%d %H:%M:%S', time.localtime(e['timestamp'])), e['filename']] for e in data] except (ValueError, KeyError, TypeError) as e: print('\nError parsing {}: {}\n'.format(data, e)) return None result = [ '\nbackup_list:', 'Timestamp:{} Filename:'.format(' ' * 12) ] + [' {} {}'.format(a, b) for (a, b) in data] if len(result) > 2: result[2] = '{} (last)'.format(result[2]) result.append('') return '\n'.join(result) if __name__ == '__main__': TestShell().cmdloop()
StarcoderdataPython
4863310
<filename>checa.py # Funções auxiliares que transformam posições entre coordenadas # (andar, linha, coluna) e número inteiro (entre 1 e 64) def posicao( pos_int ): """ Transforma a posição, dada em termos de um número inteiro entre 1 e 64, e uma tupla de coordenadas. """ pos_int -= 1 posi = int(pos_int/16) #"andar" posj = int((pos_int%16)/4) #linha posk = int((pos_int%16)%4) #coluna return posi, posj, posk def pos_inteiro( posi, posj, posk ): """ Transforma a posição, dada em termos de uma tupla de coordenadas, em um número inteiro. """ return posi*16 + posj*4 + posk + 1 # Funções de checagem def checaLinha( tabuleiro ): """ Checa se todos os elementos da linha são iguais a 'X' ou 'O', retornando o caractere em caso afirmativo e retornando '' caso contrário """ for andar in range(4): for linha in range(4): if tabuleiro[andar][linha][0] == 'X' and tabuleiro[andar][linha][1] == 'X' and tabuleiro[andar][linha][2] == 'X' and tabuleiro[andar][linha][3] == 'X': return 'X', 0, [andar,linha] if tabuleiro[andar][linha][0] == 'O' and tabuleiro[andar][linha][1] == 'O' and tabuleiro[andar][linha][2] == 'O' and tabuleiro[andar][linha][3] == 'O': return 'O', 0, [andar,linha] return '' def checaColuna( tabuleiro ): """ Checa se todos os elementos da coluna são iguais a 'X' ou 'O', retornando o caractere em caso afirmativo e retornando '' caso contrário """ for andar in range(4): for coluna in range(4): if tabuleiro[andar][0][coluna] == 'X' and tabuleiro[andar][1][coluna] == 'X' and tabuleiro[andar][2][coluna] == 'X' and tabuleiro[andar][3][coluna] == 'X': return 'X', 1, [andar,coluna] if tabuleiro[andar][0][coluna] == 'O' and tabuleiro[andar][1][coluna] == 'O' and tabuleiro[andar][2][coluna] == 'O' and tabuleiro[andar][3][coluna] == 'O': return 'O', 1, [andar,coluna] return '' def checaDiagonal1( tabuleiro ): """ Checa se todos os elementos da diagonal 1 (decrescente) são iguais a 'X' ou 'O', retornando o caractere em caso afirmativo e retornando '' caso contrário """ for andar in range(4): if tabuleiro[andar][0][0] == 'X' and tabuleiro[andar][1][1] == 'X' and tabuleiro[andar][2][2] == 'X' and tabuleiro[andar][3][3] == 'X': return 'X', 2, [andar] if tabuleiro[andar][0][0] == 'O' and tabuleiro[andar][1][1] == 'O' and tabuleiro[andar][2][2] == 'O' and tabuleiro[andar][3][3] == 'O': return 'O', 2, [andar] return '' def checaDiagonal2( tabuleiro ): """ Checa se todos os elementos da diagonal 2 (crescente) são iguais a 'X' ou 'O', retornando o caractere em caso afirmativo e retornando '' caso contrário """ for andar in range(4): if tabuleiro[andar][3][0] == 'X' and tabuleiro[andar][2][1] == 'X' and tabuleiro[andar][1][2] == 'X' and tabuleiro[andar][0][3] == 'X': return 'X', 3, [andar] if tabuleiro[andar][3][0] == 'O' and tabuleiro[andar][2][1] == 'O' and tabuleiro[andar][1][2] == 'O' and tabuleiro[andar][0][3] == 'O': return 'O', 3, [andar] return '' def checaLinha3D1( tabuleiro ): """ Checa se todos os elementos da linha 3D 1 (decrescente) são iguais a 'X' ou 'O', retornando o caractere em caso afirmativo e retornando '' caso contrário """ for linha in range(4): if tabuleiro[0][linha][0] == 'X' and tabuleiro[1][linha][1] == 'X' and tabuleiro[2][linha][2] == 'X' and tabuleiro[3][linha][3] == 'X': return 'X', 4, [linha] if tabuleiro[0][linha][0] == 'O' and tabuleiro[1][linha][1] == 'O' and tabuleiro[2][linha][2] == 'O' and tabuleiro[3][linha][3] == 'O': return 'O', 4, [linha] return '' def checaLinha3D2( tabuleiro ): """ Checa se todos os elementos da linha 3D 2 (crescente) são iguais a 'X' ou 'O', retornando o caractere em caso afirmativo e retornando '' caso contrário """ for linha in range(4): if tabuleiro[3][linha][0] == 'X' and tabuleiro[2][linha][1] == 'X' and tabuleiro[1][linha][2] == 'X' and tabuleiro[0][linha][3] == 'X': return 'X', 5, [linha] if tabuleiro[3][linha][0] == 'O' and tabuleiro[2][linha][1] == 'O' and tabuleiro[1][linha][2] == 'O' and tabuleiro[0][linha][3] == 'O': return 'O', 5, [linha] return '' def checaColuna3D1( tabuleiro ): """ Checa se todos os elementos da coluna 3D 1 (decrescente) são iguais a 'X' ou 'O', retornando o caractere em caso afirmativo e retornando '' caso contrário """ for coluna in range(4): if tabuleiro[0][0][coluna] == 'X' and tabuleiro[1][1][coluna] == 'X' and tabuleiro[2][2][coluna] == 'X' and tabuleiro[3][3][coluna] == 'X': return 'X', 6, [coluna] if tabuleiro[0][0][coluna] == 'O' and tabuleiro[1][1][coluna] == 'O' and tabuleiro[2][2][coluna] == 'O' and tabuleiro[3][3][coluna] == 'O': return 'O', 6, [coluna] return '' def checaColuna3D2( tabuleiro ): """ Checa se todos os elementos da coluna 3D 2 (crescente) são iguais a 'X' ou 'O', retornando o caractere em caso afirmativo e retornando '' caso contrário """ for coluna in range(4): if tabuleiro[3][0][coluna] == 'X' and tabuleiro[2][1][coluna] == 'X' and tabuleiro[1][2][coluna] == 'X' and tabuleiro[0][3][coluna] == 'X': return 'X', 7, [coluna] if tabuleiro[3][0][coluna] == 'O' and tabuleiro[2][1][coluna] == 'O' and tabuleiro[1][2][coluna] == 'O' and tabuleiro[0][3][coluna] == 'O': return 'O', 7, [coluna] return '' def checaPilar( tabuleiro ): """ Checa se todos os elementos da coluna são iguais a 'X' ou 'O', retornando o caractere em caso afirmativo e retornando '' caso contrário """ for linha in range(4): for coluna in range(4): if tabuleiro[0][linha][coluna] == 'X' and tabuleiro[1][linha][coluna] == 'X' and tabuleiro[2][linha][coluna] == 'X' and tabuleiro[3][linha][coluna] == 'X': return 'X', 8, [linha,coluna] if tabuleiro[0][linha][coluna] == 'O' and tabuleiro[1][linha][coluna] == 'O' and tabuleiro[2][linha][coluna] == 'O' and tabuleiro[3][linha][coluna] == 'O': return 'O', 8, [linha,coluna] return '' def checaDiagonal3D1( tabuleiro ): """ Checa se todos os elementos da diagonal 3D 1 (decrescente|decrescente) são iguais a 'X' ou 'O', retornando o caractere em caso afirmativo e retornando '' caso contrário """ if tabuleiro[0][0][0] == 'X' and tabuleiro[1][1][1] == 'X' and tabuleiro[2][2][2] == 'X' and tabuleiro[3][3][3] == 'X': return 'X', 9 if tabuleiro[0][0][0] == 'O' and tabuleiro[1][1][1] == 'O' and tabuleiro[2][2][2] == 'O' and tabuleiro[3][3][3] == 'O': return 'O', 9 return '' def checaDiagonal3D2( tabuleiro ): """ Checa se todos os elementos da diagonal 3D 2 (crescente|crescente) são iguais a 'X' ou 'O', retornando o caractere em caso afirmativo e retornando '' caso contrário """ if tabuleiro[3][3][0] == 'X' and tabuleiro[2][2][1] == 'X' and tabuleiro[1][1][2] == 'X' and tabuleiro[0][0][3] == 'X': return 'X', 10 if tabuleiro[3][3][0] == 'O' and tabuleiro[2][2][1] == 'O' and tabuleiro[1][1][2] == 'O' and tabuleiro[0][0][3] == 'O': return 'O', 10 return '' def checaDiagonal3D3( tabuleiro ): """ Checa se todos os elementos da diagonal 3D 3 (crescente|decrescente) são iguais a 'X' ou 'O', retornando o caractere em caso afirmativo e retornando '' caso contrário """ if tabuleiro[3][0][0] == 'X' and tabuleiro[2][1][1] == 'X' and tabuleiro[1][2][2] == 'X' and tabuleiro[0][3][3] == 'X': return 'X', 11 if tabuleiro[3][0][0] == 'O' and tabuleiro[2][1][1] == 'O' and tabuleiro[1][2][2] == 'O' and tabuleiro[0][3][3] == 'O': return 'O', 11 return '' def checaDiagonal3D4( tabuleiro ): """ Checa se todos os elementos da diagonal 3D 4 (decrescente|crescente) são iguais a 'X' ou 'O', retornando o caractere em caso afirmativo e retornando '' caso contrário """ if tabuleiro[0][3][0] == 'X' and tabuleiro[1][2][1] == 'X' and tabuleiro[2][1][2] == 'X' and tabuleiro[3][0][3] == 'X': return 'X', 12 if tabuleiro[0][3][0] == 'O' and tabuleiro[1][2][1] == 'O' and tabuleiro[2][1][2] == 'O' and tabuleiro[3][0][3] == 'O': return 'O', 12 return '' def checagem( n, tabuleiro ): """ Dicionario de funções de checagem """ dicionario_checagem = { 0: checaLinha(tabuleiro), 1: checaColuna(tabuleiro), 2: checaDiagonal1(tabuleiro), 3: checaDiagonal2(tabuleiro), 4: checaLinha3D1(tabuleiro), 5: checaLinha3D2(tabuleiro), 6: checaColuna3D1(tabuleiro), 7: checaColuna3D2(tabuleiro), 8: checaPilar(tabuleiro), 9: checaDiagonal3D1(tabuleiro), 10: checaDiagonal3D2(tabuleiro), 11: checaDiagonal3D3(tabuleiro), 12: checaDiagonal3D4(tabuleiro) } return dicionario_checagem.get(n) def sequenciaVencedora( tipo, arg='' ): """ Função que devolve as posições da sequência vencedora """ dicionario_sequencias = { 0: [pos_inteiro(arg[0],arg[1],0),pos_inteiro(arg[0],arg[1],1),pos_inteiro(arg[0],arg[1],2),pos_inteiro(arg[0],arg[1],3)], 1: [pos_inteiro(arg[0],0,arg[1]),pos_inteiro(arg[0],1,arg[1]),pos_inteiro(arg[0],2,arg[1]),pos_inteiro(arg[0],3,arg[1])], 2: [pos_inteiro(arg[0],0,0),pos_inteiro(arg[0],1,1),pos_inteiro(arg[0],2,2),pos_inteiro(arg[0],3,3)], 3: [pos_inteiro(arg[0],3,0),pos_inteiro(arg[0],2,1),pos_inteiro(arg[0],1,2),pos_inteiro(arg[0],0,3)], 4: [pos_inteiro(0,arg[0],0),pos_inteiro(1,arg[0],1),pos_inteiro(2,arg[0],2),pos_inteiro(3,arg[0],3)], 5: [pos_inteiro(3,arg[0],0),pos_inteiro(2,arg[0],1),pos_inteiro(1,arg[0],2),pos_inteiro(0,arg[0],3)], 6: [pos_inteiro(0,0,arg[0]),pos_inteiro(1,1,arg[0]),pos_inteiro(2,2,arg[0]),pos_inteiro(3,3,arg[0])], 7: [pos_inteiro(3,0,arg[0]),pos_inteiro(2,1,arg[0]),pos_inteiro(1,2,arg[0]),pos_inteiro(0,3,arg[0])], 8: [pos_inteiro(0,arg[0],arg[1]),pos_inteiro(1,arg[0],arg[1]),pos_inteiro(2,arg[0],arg[1]),pos_inteiro(3,arg[0],arg[1])], 9: [pos_inteiro(0,0,0),pos_inteiro(1,1,1),pos_inteiro(2,2,2),pos_inteiro(3,3,3)], 10: [pos_inteiro(3,3,0),pos_inteiro(2,2,1),pos_inteiro(1,1,2),pos_inteiro(0,0,3)], 11: [pos_inteiro(3,0,0),pos_inteiro(2,1,1),pos_inteiro(1,2,2),pos_inteiro(0,3,3)], 12: [pos_inteiro(0,3,0),pos_inteiro(1,2,1),pos_inteiro(2,1,2),pos_inteiro(3,0,3)] } return dicionario_sequencias.get(tipo) def checa_tabuleiro( tabuleiro ): n = 0 resultado = '' while resultado == '': resultado = checagem(n,tabuleiro) n += 1 if resultado != None: if resultado[1] < 2: return resultado[0], sequenciaVencedora(resultado[1],resultado[2]) if resultado[1] < 8: return resultado[0], sequenciaVencedora(resultado[1],[resultado[2][0],0]) if resultado[1] == 8: return resultado[0], sequenciaVencedora(resultado[1],resultado[2]) else: return resultado[0], sequenciaVencedora(resultado[1],[0,0]) return resultado
StarcoderdataPython
9789480
<reponame>Mishuni/Collect_Environ_Data from city_air_collector import CityAirCollector from city_weather_collector import CityWeatherCollector from influxdb_management.influx_crud import InfluxCRUD import influxdb_management.influx_setting as ifs import datetime, time import urllib3, logging def log_setup(): formatter = logging.Formatter('%(asctime)s - %(message)s') termlog_handler = logging.StreamHandler() termlog_handler.setFormatter(formatter) logger = logging.getLogger() logger.addHandler(termlog_handler) logger.setLevel(logging.INFO) if __name__ == "__main__": log_setup() urllib3.disable_warnings() delta_hour = -1 logging.info("Start to Collect") mydb = InfluxCRUD(ifs.host_, ifs.port_, ifs.user_, ifs.pass_, 'TEST', ifs.protocol) # Set Each Collector air_collector = CityAirCollector(ifs.air_api_key,mydb) weather_collector = CityWeatherCollector(ifs.weather_api_key,mydb) CITY_DB = {'OUTDOOR_AIR': air_collector, 'OUTDOOR_WEATHER': weather_collector} city_id_list = ['seoul', 'sangju'] while True: now = datetime.datetime.now().replace(tzinfo=None) now_hour = now.hour now_minute = now.minute if delta_hour != now_hour and now_minute > 30: logging.info("Current HOUR : "+ str(now_hour)) try: # OUTDOOR for db_name in CITY_DB.keys(): mydb.change_db(db_name) for id_ in city_id_list: CITY_DB[db_name].set_table(id_) CITY_DB[db_name].collect() delta_hour = now_hour except Exception as e: logging.error("There are some errors : "+str(e)) else: logging.info("PASS") time.sleep(600) # 600 seconds
StarcoderdataPython
11331377
""" Created at 07.11.19 19:12 @author: gregor """ from setuptools import setup from torch.utils import cpp_extension setup(name='sandbox_cuda', ext_modules=[cpp_extension.CUDAExtension('sandbox', ['src/sandbox.cpp', 'src/sandbox_cuda.cu'])], cmdclass={'build_ext': cpp_extension.BuildExtension})
StarcoderdataPython
9611202
# coding: utf-8 # In[1]: import pandas as pd import numpy as np from over_sample import smote # In[2]: def reduce_mem_usage(df): """ iterate through all the columns of a dataframe and modify the data type to reduce memory usage. """ start_mem = df.memory_usage().sum() / 1024**2 print('Memory usage of dataframe is {:.2f} MB'.format(start_mem)) for col in df.columns: col_type = df[col].dtype if col_type != object: c_min = df[col].min() c_max = df[col].max() if str(col_type)[:3] == 'int': if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max: df[col] = df[col].astype(np.int8) elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max: df[col] = df[col].astype(np.int16) elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max: df[col] = df[col].astype(np.int32) elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max: df[col] = df[col].astype(np.int64) else: if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max: df[col] = df[col].astype(np.float16) elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max: df[col] = df[col].astype(np.float32) else: df[col] = df[col].astype(np.float64) else: df[col] = df[col].astype('category') end_mem = df.memory_usage().sum() / 1024**2 print('Memory usage after optimization is: {:.2f} MB'.format(end_mem)) print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem)) return df def reduce(): print('reduce memory usage...'.center(50, '*')) train, test, y, val_x, val_y, features = smote() train = pd.DataFrame(train) val_x = pd.DataFrame(val_x) test = pd.DataFrame(test) train = reduce_mem_usage(train) val_x = reduce_mem_usage(val_x) test = reduce_mem_usage(test) feats = [f_ for f_ in features if f_ not in ['SK_ID_CURR']] y = pd.DataFrame(y) val_y = pd.DataFrame(val_y) train.columns = features train = train[feats] test.columns = features train.to_csv('../data/train_.csv', index=False) y.to_csv('../data/y_.csv', index=False) test.to_csv('../data/test_.csv', index=False) #train.to_csv('../data/train_.csv') val_x.to_csv('../data/val_x_.csv', index=False) val_y.to_csv('../data/val_y_.csv', index=False) return train, test, y,val_x, val_y, features, feats train, test, y,val_x, val_y, features, feats = reduce()
StarcoderdataPython
1610159
<reponame>polycart/polycart<filename>PolyCart/server/goodsdb.py import sqlite3 class GoodsDataBase: def __init__(self): self.database = sqlite3.connect('goods.db', check_same_thread = False) self.c = self.database.cursor() try: self.c.execute("""create table goods (code text primary key, name text, name1 text, image text, weight real, price real, pos_x real, pos_y real, number integer)""") except: pass def insert(self, code, name, name1, image, weight, price, pos_x, pos_y): try: self.c.execute("insert into goods values (?, ?, ?, ?, ?, ?, ?, ?, ?)",(code, name, name1, image, weight, price, pos_x, pos_y, 0)) self.database.commit() except Exception as e: print(str(e)) return False else: return True def select(self, code): try: self.c.execute("select code, name, image, price, pos_x, pos_y, number, weight from goods where code = ?", (code,)) except: return None else: return self.c.fetchone() def search(self, name1): name1 = '%' + name1 + '%' try: self.c.execute("select name, image, price, pos_x, pos_y from goods where name1 like ?", (name1,)) except: return [] else: reslist = self.c.fetchall() return reslist def has(self, code): if self.select(code) != None: return True else: return False def modify_number(self, code, new_number): try: self.c.execute("select name from goods where code = ?", (code,)) if self.c.fetchone() == None: return False self.c.execute("update goods set number = ? where code = ?", (new_number, code)) self.database.commit() except: return False else: return True def modify_name(self, code, new_name): try: self.c.execute("select name from goods where code = ?", (code,)) if self.c.fetchone() == None: return False self.c.execute("update goods set name = ? where code = ?", (new_name, code)) self.database.commit() except: return False else: return True def modify_price(self, code, new_price): try: self.c.execute("select name from goods where code = ?", (code,)) if self.c.fetchone() == None: return False self.c.execute("update goods set price = ? where code = ?", (new_price, code)) self.database.commit() except: return False else: return True def modify_pos(self, code, new_pos): try: self.c.execute("select name from goods where code = ?", (code,)) if self.c.fetchone() == None: return False self.c.execute("update goods set pos_x = ?, pos_y = ? where code = ?", (new_pos[0], new_pos[1], code)) self.database.commit() except: return False else: return True def modify_image(self, code, new_image): try: self.c.execute("select name from goods where code = ?", (code,)) if self.c.fetchone() == None: return False self.c.execute("update goods set image = ? where code = ?", (new_image, code)) self.database.commit() except: return False else: return True def delete(self, code): try: self.c.execute("select name from goods where code = ?", (code,)) if self.c.fetchone() == None: return True self.c.execute("delete from goods where code = ?", (code,)) self.database.commit() except: return False else: return True def close(self): self.database.commit() self.database.close() pass ''' db = GoodsDataBase() print(db.search('Chen')) print(db.insert('3127546', 'Chen_Py', 'cd.jpg', 3.5, 2, 2)) print(db.insert('3127547', 'Chen', 'cd.jpg', 3.5, 2, 2)) print(db.insert('3127548', 'aha_Chen_Py_CCCpy', 'cd.jpg', 3.5, 2, 2)) print(db.insert('3127549', 'CPY', 'cd.jpg', 3.5, 2, 2)) '''
StarcoderdataPython
3292814
<gh_stars>0 from django.contrib import admin from django.urls import reverse from django.utils.translation import gettext as _ from django.template.defaultfilters import safe from .models import Scope, Key def get_event_ical_link(obj): if not obj.scopes.filter(name="export_ical").exists(): return _("Missing scope 'export_ical'") uri = "{}?token={}".format(reverse("event-ical-list"), obj.token) return safe('<a href="{}">{}</a>'.format(uri, _("View calendar"))) get_event_ical_link.short_description = "Calendar" class KeyAdmin(admin.ModelAdmin): list_display = [ "pk", "user", get_event_ical_link, "used_on", "created_on", "modified_on", ] exclude = ("token",) def get_queryset(self, request): qs = super().get_queryset(request) if not request.user.is_superuser: qs = qs.filter(user=request.user) return qs admin.site.register(Scope) admin.site.register(Key, KeyAdmin)
StarcoderdataPython
1704443
<gh_stars>1-10 import controllers.config as cfg import pymongo from flask import g from pymongo.mongo_client import MongoClient client = None def get_db(): if 'db' not in g: g.db = client.get_database(cfg.APP_CONFIG_DB_NAME) return g.db def init_db(): global client client = MongoClient(cfg.APP_CONFIG_MONGO_URL) # Create indexes on api start db = client.get_database(name=cfg.APP_CONFIG_DB_NAME) app_configs = db[cfg.APP_CONFIGS_COLLECTION] app_configs.create_index([("mobileAppVersion", pymongo.DESCENDING)], unique=True)
StarcoderdataPython
5184266
""" Django settings for server project. Generated by 'django-admin startproject' using Django 2.0.4. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os import json # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES_DIRS = [os.path.join(BASE_DIR, 'templates'), ] # Get AlphaVantage API Key from env AV_API_KEY = os.environ.get("AV_API_KEY") # Get ticker data TICKER_DATA_FILE = "tickerdata/ticker.json" try: TICKER_DATA = json.loads(open(TICKER_DATA_FILE).read()) except: raise FileNotFoundError("%s not found" % TICKER_DATA_FILE) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # TODO: Use https://gist.github.com/ndarville/3452907 to generate proper secret key # for production and add it to heroku env variables SECRET_KEY = '<KEY>*(nh_l)r%fqd)z@z$&ac_qr)quriizg==@&y-5' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'investor.apps.InvestorConfig', 'symbols.apps.SymbolsConfig', 'stocks.apps.StocksConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'server.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': TEMPLATES_DIRS, 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'server.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases # Set up database for Heroku import dj_database_url DATABASES = { 'default': dj_database_url.config ( default='sqlite:////{0}'.format(os.path.join(BASE_DIR, 'db.sqlite3')) ) } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LOGIN_URL = '/u/login/' LOGIN_REDIRECT_URL = '/' # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' # Activate Django-Heroku. import django_heroku django_heroku.settings(locals())
StarcoderdataPython
8134167
import asyncio import re from datetime import datetime from logging import getLogger from os import makedirs from os.path import exists, join from typing import Any, Dict, List, Optional, TYPE_CHECKING, Tuple from aiohttp import ClientError from .abc import GenericModelList, Model from .group import Group from .mixins import DatetimeMixin from .user import User from ..constants import invalid_folder_name_regex, routes from ..utils import copy_key_to_attribute logger = getLogger(__name__) if TYPE_CHECKING: from .manga import Manga from ..client import MangadexClient class Chapter(Model, DatetimeMixin): """A :class:`.Model` representing an individual chapter. .. versionadded:: 0.3 """ volume: Optional[str] """The volume of the chapter. ``None`` if the chapter belongs to no volumes.""" number: Optional[str] """The number of the chapter. ``None`` if the chapter is un-numbered (such as in an anthology). .. note:: A chapter can have a number, a title, or both. If a chapter's number is ``None``, it must have a title. """ title: Optional[str] """The title of the chapter. ``None`` if the chapter does not have a title. .. note:: A chapter can have a number, a title, or both. If a chapter's title is ``None``, it must have a number. """ language: str """The language of the chapter.""" hash: str """The chapter's hash.""" page_names: List[str] """A list of strings containing the filenames of the pages. .. seealso:: :attr:`.data_saver_page_names` """ data_saver_page_names: List[str] """A list of strings containing the filenames of the data saver pages. .. seealso:: :attr:`.page_names` """ publish_time: datetime """A :class:`datetime.datetime` representing the time the chapter was published. .. seealso:: :attr:`.created_at` .. note:: The datetime is **timezone aware** as it is parsed from an ISO-8601 string. """ manga: "Manga" """The manga that this chapter belongs to.""" user: User """The user that uploaded this chapter.""" groups: GenericModelList[Group] """The groups that uploaded this chapter.""" read: bool """Whether or not the chapter is read.""" def __init__( self, client: "MangadexClient", *, id: Optional[str] = None, version: int = 0, data: Optional[Dict[str, Any]] = None, ): self.read = False super().__init__(client, id=id, version=version, data=data) @property def name(self) -> str: """Returns a nicely formatted name based on available fields. Includes the volume number, chapter number, and chapter title if any one or more of them exist. :return: Formatted name :rtype: str """ if self.number: constructed = "" if self.volume: constructed += f"Volume {self.volume} " if self.number.isdecimal(): num_rep = float(self.number) if num_rep.is_integer(): num_rep = int(num_rep) else: num_rep = self.number constructed += f"Chapter {num_rep}" if self.title: constructed += f": {self.title}" return constructed else: return self.title @property def sorting_number(self) -> float: """Returns ``0`` if the chapter does not have a number, otherwise returns the chapter's number. :return: A number usable for sorting. :rtype: float """ return float(self.number) if self.number.isdecimal() else -1 async def pages(self, *, data_saver: bool = False, ssl_only: bool = False) -> List[str]: """Get fully formatted page URLs. .. note:: The given page URLs are only valid for a short timeframe. These URLs cannot be used for hotlinking. :param data_saver: Whether or not to return the pages for the data saver URLs. Defaults to ``False``. :type data_saver: bool :param ssl_only: Whether or not the given URL has port ``443``. Useful if your firewall blocks outbound connections to ports that are not port ``443``. Defaults to ``False``. .. note:: This will lower the pool of available clients and can cause higher latencies. :type ssl_only: bool :return: A list of valid URLs in the order of the pages. :rtype: List[str] """ if not hasattr(self, "page_names"): await self.fetch() r = await self.client.request( "GET", routes["md@h"].format(chapterId=self.id), params={"forcePort443": ssl_only} ) base_url = (await r.json())["baseUrl"] r.close() return [ f"{base_url}/{'data-saver' if data_saver else 'data'}/{self.hash}/{filename}" for filename in (self.data_saver_page_names if data_saver else self.page_names) ] async def download_chapter( self, *, folder_format: str = "{manga}/{chapter_num}{separator}{title}", file_format: str = "{num}", as_bytes_list: bool = False, overwrite: bool = True, retries: int = 3, use_data_saver: bool = False, ssl_only: bool = False, ) -> Optional[List[bytes]]: """Download all of the pages of the chapter and either save them locally to the filesystem or return the raw bytes. :param folder_format: The format of the folder to create for the chapter. The folder can already be existing. The default format is ``{manga}/{chapter_num}{separator}{chapter_title}``. .. note:: Specify ``.`` if you want to save the pages in the current folder. Available variables: * ``{manga}``: The name of the manga. If the chapter's manga object does not contain a title object, it will be fetched. * ``{chapter_num}``: The number of the chapter, if it exists. * ``{separator}``: A separator if both the chapter's number and title exists. * ``{title}``: The title of the chapter, if it exists. :type folder_format: str :param file_format: The format of the individual image file names. The default format is ``{num}``. .. note:: The file extension is applied automatically from the real file name. There is no need to include it. Available variables: * ``{num}``: The numbering of the image files starting from 1. This respects the order the images are in inside of :attr:`.page_names`. * ``{num0}``: The same as ``{num}`` but starting from 0. * ``{name}``: The actual filename of the image from :attr:`.page_names`, without the file extension. :type file_format: str :param as_bytes_list: Whether or not to return the pages as a list of raw bytes. Setting this parameter to ``True`` will ignore the value of the ``folder_format`` parameter. :type as_bytes_list: bool :param overwrite: Whether or not to override existing files with the same name as the page. Defaults to ``True``. :type overwrite: bool :param retries: How many times to retry a chapter if a MD@H node does not let us download the pages. Defaults to ``3``. :type retries: int :param use_data_saver: Whether or not to use the data saver pages or the normal pages. Defaults to ``False``. :type use_data_saver: bool :param ssl_only: Whether or not the given URL has port ``443``. Useful if your firewall blocks outbound connections to ports that are not port ``443``. Defaults to ``False``. .. note:: This will lower the pool of available clients and can cause higher download times. :type ssl_only: bool :raises: :class:`aiohttp.ClientResponseError` if there is an error after all retries are exhausted. :return: A list of byte strings if ``as_bytes_list`` is ``True`` else None. :rtype: Optional[List[bytes]] """ if not hasattr(self, "page_names"): await self.fetch() pages = await self.pages(data_saver=use_data_saver, ssl_only=ssl_only) try: items = await asyncio.gather(*[self.client.get_page(url) for url in pages]) except ClientError as e: if retries > 0: logger.warning("Retrying download of chapter %s due to %s: %s", self.id, type(e).__name__, e) return await self.download_chapter( folder_format=folder_format, as_bytes_list=as_bytes_list, overwrite=overwrite, retries=retries - 1, use_data_saver=use_data_saver, ssl_only=ssl_only, ) else: raise else: byte_list = await asyncio.gather(*[item.read() for item in items]) [item.close() for item in items] if as_bytes_list: return byte_list # NOQA: ignore; This is needed because for whatever reason PyCharm cannot guess the # output of asyncio.gather() else: base = "" if not as_bytes_list: chapter_num = self.number or "" separator = " - " if self.number and self.title else "" title = ( re.sub("_{2,}", "_", invalid_folder_name_regex.sub("_", self.title.strip())) if self.title else "" ) # This replaces invalid characters with underscores then deletes duplicate underscores in a # series. This # means that a name of ``ex___ample`` becomes ``ex_ample``. if not self.manga.titles: await self.manga.fetch() manga_title = self.manga.titles[self.language].primary or ( self.manga.titles.first().primary if self.manga.titles else self.manga.id ) manga_title = re.sub("_{2,}", "_", invalid_folder_name_regex.sub("_", manga_title.strip())) base = folder_format.format( manga=manga_title, chapter_num=chapter_num, separator=separator, title=title ) makedirs(base, exist_ok=True) for original_file_name, (num, item) in zip( self.data_saver_page_names if use_data_saver else self.page_names, enumerate(byte_list, start=1) ): filename = ( file_format.format(num=num, num0=num - 1, name=original_file_name) + "." + original_file_name.rpartition(".")[-1] ) full_path = join(base, filename) if not (exists(full_path) and overwrite): with open(full_path, "wb") as fp: fp.write(item) @staticmethod def _get_number_from_chapter_string(chapter_str: str) -> Tuple[Optional[float], Optional[str]]: if not chapter_str: return None, None elif chapter_str.isdecimal(): return float(chapter_str), None else: # Unfortunately for us some people decided to enter in garbage data, which means that we cannot cleanly # convert to a float. Attempt to try to get something vaguely resembling a number or return a null # chapter number and set the title as the value for the chapter number. match = re.search(r"[\d.]+", chapter_str) return None if not match else float(match.group(0)), chapter_str def parse(self, data: Dict[str, Any]): super().parse(data) if "data" in data and "attributes" in data["data"]: attributes = data["data"]["attributes"] copy_key_to_attribute(attributes, "volume", self) copy_key_to_attribute(attributes, "title", self) copy_key_to_attribute(attributes, "chapter", self, "number") copy_key_to_attribute(attributes, "translatedLanguage", self, "language") copy_key_to_attribute(attributes, "hash", self) copy_key_to_attribute(attributes, "data", self, "page_names") copy_key_to_attribute(attributes, "dataSaver", self, "data_saver_page_names") self._process_times(attributes) self._parse_relationships(data) if hasattr(self, "_users"): self.user = self._users[0] del self._users if hasattr(self, "mangas"): # This is needed to move the list of Mangas created by the parse_relationships function into a # singular manga, since there can never be >1 manga per chapter. self.mangas: List[Manga] self.manga = self.mangas[0] del self.mangas def _process_times(self, attributes: Dict[str, str]): super()._process_times(attributes) copy_key_to_attribute( attributes, "publishAt", self, "publish_time", transformation=lambda attrib: datetime.fromisoformat(attrib) if attrib else attrib, ) async def fetch(self): """Fetch data about the chapter. |permission| ``chapter.view`` :raises: :class:`.InvalidID` if a chapter with the ID does not exist. """ await self._fetch("chapter.view", "chapter") async def load_groups(self): """Shortcut method that calls :meth:`.MangadexClient.batch_groups` with the groups that belong to the group. Roughly equivalent to: .. code-block:: python await client.batch_groups(*user.groups) """ await self.client.batch_groups(*self.groups) async def mark_read(self): """Mark the chapter as read. |auth| .. versionadded:: 0.5 """ self.client.raise_exception_if_not_authenticated("GET", routes["read"]) r = await self.client.request("POST", routes["read"].format(id=self.id)) self.read = True r.close() async def mark_unread(self): """Mark the chapter as unread. |auth| .. versionadded:: 0.5 """ self.client.raise_exception_if_not_authenticated("GET", routes["read"]) r = await self.client.request("DELETE", routes["read"].format(id=self.id)) self.read = False r.close() async def toggle_read(self): """Toggle a chapter between being read and unread. Requires authentication. .. versionadded:: 0.5 .. note:: This requires the read status of the chapter to be known. See :meth:`.get_read_status` or :meth:`.ChapterList.get_read`. :raises: :class:`.Unauthorized` is authentication is missing. """ if self.read: await self.mark_unread() else: await self.mark_read() async def get_read(self): """Gets whether or not the chapter is read. The read status can then be viewed in :attr:`.read`. .. versionadded:: 0.5 """ r = await self.client.request("GET", routes["manga_read"].format(id=self.manga.id)) self.manga._check_404(r) json = await r.json() r.close() self.read = self.id in json["data"]
StarcoderdataPython
1627137
<reponame>kkauder/spack # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Cleverleaf(CMakePackage): """CleverLeaf is a hydrodynamics mini-app that extends CloverLeaf with Adaptive Mesh Refinement using the SAMRAI toolkit from Lawrence Livermore National Laboratory. The primary goal of CleverLeaf is to evaluate the application of AMR to the Lagrangian-Eulerian hydrodynamics scheme used by CloverLeaf. """ homepage = "http://uk-mac.github.io/CleverLeaf/" git = "https://github.com/UK-MAC/CleverLeaf_ref.git" version('develop', branch='develop') depends_on('samrai@3.8.0:') depends_on('hdf5+mpi') depends_on('boost') depends_on('cmake@3.1:', type='build') # The Fujitsu compiler requires the '--linkfortran' # option to combine C++ and Fortran programs. patch('fujitsu_add_link_flags.patch', when='%fj') def flag_handler(self, name, flags): if self.spec.satisfies('%intel') and name in ['cppflags', 'cxxflags']: flags.append(self.compiler.cxx11_flag) return (None, None, flags)
StarcoderdataPython
171889
<filename>test/setup.py import os def before_each(): # blank file open('blank', 'w').close() # with headers and comments with open('headers', 'w') as headers: headers.write('total,date\n') headers.write('00:15:00,00:15:00,900,900,1970-01-01T00:00:00\n') headers.write('this is a comment\n') # with one entry with open('single', 'w') as headers: headers.write('00:15:00,00:15:00,900,900,1970-01-01T00:00:00\n') # with one entry (negative) with open('negative', 'w') as headers: headers.write('-00:27:00,-00:27:00,-1620,-1620,1970-01-01T00:00:00\n') def after_each(): os.remove('blank') os.remove('headers') os.remove('single') os.remove('negative')
StarcoderdataPython
295584
<filename>cyborg_enhancement/mitaka_version/cyborg/cyborg/objects/physical_function.py # Copyright 2018 Huawei Technologies Co.,LTD. # 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. import copy from oslo_log import log as logging from oslo_versionedobjects import base as object_base from cyborg.common import exception from cyborg.db import api as dbapi from cyborg.objects import base from cyborg.objects import fields as object_fields from cyborg.objects.deployable import Deployable from cyborg.objects.virtual_function import VirtualFunction LOG = logging.getLogger(__name__) @base.CyborgObjectRegistry.register class PhysicalFunction(Deployable): # Version 1.0: Initial version VERSION = '1.0' virtual_function_list = [] def create(self, context): # To ensure the creating type is PF if self.type != 'pf': raise exception.InvalidDeployType() super(PhysicalFunction, self).create(context) def save(self, context): """In addition to save the pf, it should also save the vfs associated with this pf """ # To ensure the saving type is PF if self.type != 'pf': raise exception.InvalidDeployType() for exist_vf in self.virtual_function_list: exist_vf.save(context) super(PhysicalFunction, self).save(context) def add_vf(self, vf): """add a vf object to the virtual_function_list. If the vf already exists, it will ignore, otherwise, the vf will be appended to the list """ if not isinstance(vf, VirtualFunction) or vf.type != 'vf': raise exception.InvalidDeployType() for exist_vf in self.virtual_function_list: if base.obj_equal_prims(vf, exist_vf): LOG.warning("The vf already exists") return None vf.parent_uuid = self.uuid vf.root_uuid = self.root_uuid vf_copy = copy.deepcopy(vf) self.virtual_function_list.append(vf_copy) def delete_vf(self, context, vf): """remove a vf from the virtual_function_list if the vf does not exist, ignore it """ for idx, exist_vf in self.virtual_function_list: if base.obj_equal_prims(vf, exist_vf): removed_vf = self.virtual_function_list.pop(idx) removed_vf.destroy(context) return LOG.warning("The removing vf does not exist!") def destroy(self, context): """Delete a the pf from the DB.""" del self.virtual_function_list[:] super(PhysicalFunction, self).destroy(context) @classmethod def get(cls, context, uuid): """Find a DB Physical Function and return an Obj Physical Function. In addition, it will also finds all the Virtual Functions associated with this Physical Function and place them in virtual_function_list """ db_pf = cls.dbapi.deployable_get(context, uuid) obj_pf = cls._from_db_object(cls(context), db_pf) pf_uuid = obj_pf.uuid query = {"parent_uuid": pf_uuid, "type": "vf"} db_vf_list = cls.dbapi.deployable_get_by_filters(context, query) for db_vf in db_vf_list: obj_vf = VirtualFunction.get(context, db_vf.uuid) obj_pf.virtual_function_list.append(obj_vf) return obj_pf @classmethod def get_by_filter(cls, context, filters, sort_key='created_at', sort_dir='desc', limit=None, marker=None, join=None): obj_dpl_list = [] filters['type'] = 'pf' db_dpl_list = cls.dbapi.deployable_get_by_filters(context, filters, sort_key=sort_key, sort_dir=sort_dir, limit=limit, marker=marker, join_columns=join) for db_dpl in db_dpl_list: obj_dpl = cls._from_db_object(cls(context), db_dpl) query = {"parent_uuid": obj_dpl.uuid} vf_get_list = VirtualFunction.get_by_filter(context, query) obj_dpl.virtual_function_list = vf_get_list obj_dpl_list.append(obj_dpl) return obj_dpl_list @classmethod def _from_db_object(cls, obj, db_obj): """Converts a physical function to a formal object. :param obj: An object of the class. :param db_obj: A DB model of the object :return: The object of the class with the database entity added """ obj = Deployable._from_db_object(obj, db_obj) if cls is PhysicalFunction: obj.virtual_function_list = [] return obj
StarcoderdataPython
9625855
<reponame>gatsinski/investments<filename>investments/contrib/payments/models.py import uuid from django.contrib.auth import get_user_model from django.core import validators from django.db import models from django.utils.translation import gettext from django.utils.translation import gettext_lazy as _ from investments.models import TimestampedModel from . import constants UserModel = get_user_model() class Payment(TimestampedModel): uuid = models.UUIDField(default=uuid.uuid4, primary_key=True) recorded_on = models.DateField(_("Recorded on")) tags = models.ManyToManyField( "tags.Tag", related_name="dividend_payments", verbose_name=_("Tags"), blank=True, ) class Meta: verbose_name = _("Payment") verbose_name_plural = _("Payments") def __str__(self): return gettext(f"Payment {self.uuid}") class DividendPayment(Payment): amount = models.DecimalField( _("Amount"), max_digits=12, decimal_places=2, validators=[validators.MinValueValidator(0)], ) type = models.CharField( _("Type"), max_length=254, choices=constants.DIVIDEND_TYPES, blank=True ) position = models.ForeignKey( "positions.Position", related_name="dividend_payments", on_delete=models.CASCADE ) notes = models.CharField(_("Notes"), max_length=1024, blank=True) class Meta: verbose_name = _("Dividend Payment") verbose_name_plural = _("Dividend Payments") def __str__(self): return gettext( f"Dividend Payment, position {self.position.position_id}, {self.position.security}" ) class InterestPayment(Payment): amount = models.DecimalField( _("Amount"), max_digits=12, decimal_places=2, validators=[validators.MinValueValidator(0)], ) position = models.ForeignKey( "positions.Position", related_name="interest_payments", on_delete=models.CASCADE ) notes = models.CharField(_("Notes"), max_length=1024, blank=True) class Meta: verbose_name = _("Interest Payment") verbose_name_plural = _("Interest Payments") def __str__(self): return gettext( f"Interest Payment, position {self.position.position_id}, {self.position.security}" )
StarcoderdataPython
5075439
<reponame>Pondorasti/BEW-1.2<filename>Class Work/final-project/final_app/config.py import os from dotenv import load_dotenv load_dotenv() class Config(object): SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL') SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY = os.getenv('SECRET_KEY')
StarcoderdataPython
3375448
# coding: utf-8 """ Jamf Pro API ## Overview This is a sample Jamf Pro server which allows for usage without any authentication. The Jamf Pro environment which supports the Try it Out functionality does not run the current beta version of Jamf Pro, thus any newly added endpoints will result in an error and should be used soley for documentation purposes. # noqa: E501 The version of the OpenAPI document: 10.25.0 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from jamf.configuration import Configuration class CacheSettings(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'id': 'str', 'name': 'str', 'cache_type': 'str', 'time_to_live_seconds': 'int', 'time_to_idle_seconds': 'int', 'ehcache_max_bytes_local_heap': 'str', 'cache_unique_id': 'str', 'elasticache': 'bool', 'memcached_endpoints': 'list[MemcachedEndpoints]' } attribute_map = { 'id': 'id', 'name': 'name', 'cache_type': 'cacheType', 'time_to_live_seconds': 'timeToLiveSeconds', 'time_to_idle_seconds': 'timeToIdleSeconds', 'ehcache_max_bytes_local_heap': 'ehcacheMaxBytesLocalHeap', 'cache_unique_id': 'cacheUniqueId', 'elasticache': 'elasticache', 'memcached_endpoints': 'memcachedEndpoints' } def __init__(self, id='0', name='cache configuration', cache_type=None, time_to_live_seconds=None, time_to_idle_seconds=None, ehcache_max_bytes_local_heap='null', cache_unique_id=None, elasticache=False, memcached_endpoints=None, local_vars_configuration=None): # noqa: E501 """CacheSettings - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._id = None self._name = None self._cache_type = None self._time_to_live_seconds = None self._time_to_idle_seconds = None self._ehcache_max_bytes_local_heap = None self._cache_unique_id = None self._elasticache = None self._memcached_endpoints = None self.discriminator = None if id is not None: self.id = id if name is not None: self.name = name self.cache_type = cache_type self.time_to_live_seconds = time_to_live_seconds if time_to_idle_seconds is not None: self.time_to_idle_seconds = time_to_idle_seconds if ehcache_max_bytes_local_heap is not None: self.ehcache_max_bytes_local_heap = ehcache_max_bytes_local_heap self.cache_unique_id = cache_unique_id if elasticache is not None: self.elasticache = elasticache self.memcached_endpoints = memcached_endpoints @property def id(self): """Gets the id of this CacheSettings. # noqa: E501 :return: The id of this CacheSettings. # noqa: E501 :rtype: str """ return self._id @id.setter def id(self, id): """Sets the id of this CacheSettings. :param id: The id of this CacheSettings. # noqa: E501 :type id: str """ self._id = id @property def name(self): """Gets the name of this CacheSettings. # noqa: E501 :return: The name of this CacheSettings. # noqa: E501 :rtype: str """ return self._name @name.setter def name(self, name): """Sets the name of this CacheSettings. :param name: The name of this CacheSettings. # noqa: E501 :type name: str """ self._name = name @property def cache_type(self): """Gets the cache_type of this CacheSettings. # noqa: E501 :return: The cache_type of this CacheSettings. # noqa: E501 :rtype: str """ return self._cache_type @cache_type.setter def cache_type(self, cache_type): """Sets the cache_type of this CacheSettings. :param cache_type: The cache_type of this CacheSettings. # noqa: E501 :type cache_type: str """ if self.local_vars_configuration.client_side_validation and cache_type is None: # noqa: E501 raise ValueError("Invalid value for `cache_type`, must not be `None`") # noqa: E501 self._cache_type = cache_type @property def time_to_live_seconds(self): """Gets the time_to_live_seconds of this CacheSettings. # noqa: E501 :return: The time_to_live_seconds of this CacheSettings. # noqa: E501 :rtype: int """ return self._time_to_live_seconds @time_to_live_seconds.setter def time_to_live_seconds(self, time_to_live_seconds): """Sets the time_to_live_seconds of this CacheSettings. :param time_to_live_seconds: The time_to_live_seconds of this CacheSettings. # noqa: E501 :type time_to_live_seconds: int """ if self.local_vars_configuration.client_side_validation and time_to_live_seconds is None: # noqa: E501 raise ValueError("Invalid value for `time_to_live_seconds`, must not be `None`") # noqa: E501 self._time_to_live_seconds = time_to_live_seconds @property def time_to_idle_seconds(self): """Gets the time_to_idle_seconds of this CacheSettings. # noqa: E501 :return: The time_to_idle_seconds of this CacheSettings. # noqa: E501 :rtype: int """ return self._time_to_idle_seconds @time_to_idle_seconds.setter def time_to_idle_seconds(self, time_to_idle_seconds): """Sets the time_to_idle_seconds of this CacheSettings. :param time_to_idle_seconds: The time_to_idle_seconds of this CacheSettings. # noqa: E501 :type time_to_idle_seconds: int """ self._time_to_idle_seconds = time_to_idle_seconds @property def ehcache_max_bytes_local_heap(self): """Gets the ehcache_max_bytes_local_heap of this CacheSettings. # noqa: E501 :return: The ehcache_max_bytes_local_heap of this CacheSettings. # noqa: E501 :rtype: str """ return self._ehcache_max_bytes_local_heap @ehcache_max_bytes_local_heap.setter def ehcache_max_bytes_local_heap(self, ehcache_max_bytes_local_heap): """Sets the ehcache_max_bytes_local_heap of this CacheSettings. :param ehcache_max_bytes_local_heap: The ehcache_max_bytes_local_heap of this CacheSettings. # noqa: E501 :type ehcache_max_bytes_local_heap: str """ self._ehcache_max_bytes_local_heap = ehcache_max_bytes_local_heap @property def cache_unique_id(self): """Gets the cache_unique_id of this CacheSettings. # noqa: E501 The default is for Jamf Pro to generate a UUID, so we can only give an example instead. # noqa: E501 :return: The cache_unique_id of this CacheSettings. # noqa: E501 :rtype: str """ return self._cache_unique_id @cache_unique_id.setter def cache_unique_id(self, cache_unique_id): """Sets the cache_unique_id of this CacheSettings. The default is for Jamf Pro to generate a UUID, so we can only give an example instead. # noqa: E501 :param cache_unique_id: The cache_unique_id of this CacheSettings. # noqa: E501 :type cache_unique_id: str """ if self.local_vars_configuration.client_side_validation and cache_unique_id is None: # noqa: E501 raise ValueError("Invalid value for `cache_unique_id`, must not be `None`") # noqa: E501 self._cache_unique_id = cache_unique_id @property def elasticache(self): """Gets the elasticache of this CacheSettings. # noqa: E501 :return: The elasticache of this CacheSettings. # noqa: E501 :rtype: bool """ return self._elasticache @elasticache.setter def elasticache(self, elasticache): """Sets the elasticache of this CacheSettings. :param elasticache: The elasticache of this CacheSettings. # noqa: E501 :type elasticache: bool """ self._elasticache = elasticache @property def memcached_endpoints(self): """Gets the memcached_endpoints of this CacheSettings. # noqa: E501 :return: The memcached_endpoints of this CacheSettings. # noqa: E501 :rtype: list[MemcachedEndpoints] """ return self._memcached_endpoints @memcached_endpoints.setter def memcached_endpoints(self, memcached_endpoints): """Sets the memcached_endpoints of this CacheSettings. :param memcached_endpoints: The memcached_endpoints of this CacheSettings. # noqa: E501 :type memcached_endpoints: list[MemcachedEndpoints] """ if self.local_vars_configuration.client_side_validation and memcached_endpoints is None: # noqa: E501 raise ValueError("Invalid value for `memcached_endpoints`, must not be `None`") # noqa: E501 self._memcached_endpoints = memcached_endpoints def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, CacheSettings): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, CacheSettings): return True return self.to_dict() != other.to_dict()
StarcoderdataPython
6424013
<filename>PupilDetector.py # Eye Centre Localisation using Means of Gradients # Implementation of paper by <NAME> and <NAME> # "Accurate Eye Centre Localisation by Means of Gradients" # Author: <NAME> # Increase speed of locate by increasing the accuracy variable # The algorithm takes a sample ones every accuracy*accuracy pixels # After this it takes a closer look around the best sample # Increase speed of track by decreasing radius and distance # Radius is half the width and height around the previous location (py, px) # The whole pupil should still be visible in this area # Distance is the maximum amount of pixels between the new and old location import numpy as np from scipy.ndimage.filters import gaussian_filter class GradientIntersect: def createGrid(self, Y, X): # create grid vectors grid = np.array([[y,x] for y in range(1-Y,Y) for x in range (1-X,X)], dtype='float') # normalize grid vectors grid2 = np.sqrt(np.einsum('ij,ij->i',grid,grid)) grid2[grid2==0] = 1 grid /= grid2[:,np.newaxis] # reshape grid for easier displacement selection grid = grid.reshape(Y*2-1,X*2-1,2) return grid def createGradient(self, image): # get image size Y, X = image.shape # calculate gradients gy, gx = np.gradient(image) gx = np.reshape(gx, (X*Y,1)) gy = np.reshape(gy, (X*Y,1)) gradient = np.hstack((gy,gx)) # normalize gradients gradient2 = np.sqrt(np.einsum('ij,ij->i',gradient,gradient)) gradient2[gradient2==0] = 1 gradient /= gradient2[:,np.newaxis] return gradient def locate(self, image, sigma = 2, accuracy = 1): # get image size Y, X = image.shape # get grid grid = self.createGrid(Y, X) # create empty score matrix scores = np.zeros((Y,X)) # normalize image image = (image.astype('float') - np.min(image)) / np.max(image) # blur image blurred = gaussian_filter(image, sigma=sigma) # get gradient gradient = self.createGradient(image) # loop through all pixels for cy in range(0,Y,accuracy): for cx in range(0,X,accuracy): # select displacement displacement = grid[Y-cy-1:Y*2-cy-1,X-cx-1:X*2-cx-1,:] displacement = np.reshape(displacement,(X*Y,2)) # calculate score score = np.einsum('ij,ij->i', displacement, gradient) score = np.einsum('i,i->', score, score) scores[cy,cx] = score # multiply with the blurred darkness scores = scores * (1-blurred) # if we skipped pixels, get more accurate around the best pixel if accuracy>1: # get maximum value index (yval,xval) = np.unravel_index(np.argmax(scores),scores.shape) # prevent maximum value index from being close to 0 or max yval = min(max(yval,accuracy), Y-accuracy-1) xval = min(max(xval,accuracy), X-accuracy-1) # loop through new pixels for cy in range(yval-accuracy,yval+accuracy+1): for cx in range(xval-accuracy,xval+accuracy+1): # select displacement displacement = grid[Y-cy-1:Y*2-cy-1,X-cx-1:X*2-cx-1,:] displacement = np.reshape(displacement,(X*Y,2)) # calculate score score = np.einsum('ij,ij->i', displacement, gradient) score = np.einsum('i,i->', score, score) scores[cy,cx] = score * (1-blurred[cy,cx]) # get maximum value index (yval,xval) = np.unravel_index(np.argmax(scores),scores.shape) # return values return (yval, xval) def track(self, image, prev, sigma = 2, radius=50, distance = 10): py, px = prev # select image image = image[py-radius:py+radius+1, px-radius:px+radius+1] # get image size Y, X = image.shape # get grid grid = self.createGrid(Y, X) # create empty score matrix scores = np.zeros((Y,X)) # normalize image image = (image.astype('float') - np.min(image)) / np.max(image) # blur image blurred = gaussian_filter(image, sigma=sigma) # get gradient gradient = self.createGradient(image) # loop through all pixels for cy in range(radius-distance, radius+distance+1): for cx in range(radius-distance, radius+distance+1): # select displacement displacement = grid[Y-cy-1:Y*2-cy-1,X-cx-1:X*2-cx-1,:] displacement = np.reshape(displacement,(X*Y,2)) # calculate score score = np.einsum('ij,ij->i', displacement, gradient) score = np.einsum('i,i->', score, score) scores[cy,cx] = score # multiply with the blurred darkness scores = scores * (1-blurred) # get maximum value index (yval,xval) = np.unravel_index(np.argmax(scores),scores.shape) # return values return (py+yval-radius, px+xval-radius) class IsophoteCurvature: def __init__(self, blur = 3, minrad = 2, maxrad = 20): self.blur = blur self.minrad = minrad self.maxrad = maxrad def locate(self, image): # normalize image image = gaussian_filter(image, sigma=self.blur) image = (image.astype('float') - np.min(image)) image = image / np.max(image) # calculate gradients Ly, Lx = np.gradient(image) Lyy, Lyx = np.gradient(Ly) Lxy, Lxx = np.gradient(Lx) Lvv = Ly**2 * Lxx - 2*Lx * Lxy * Ly + Lx**2 * Lyy Lw = Lx**2 + Ly**2 Lw[Lw==0] = 0.001 Lvv[Lvv==0] = 0.001 k = - Lvv / (Lw**1.5) # calculate displacement Dx = -Lx * (Lw / Lvv) Dy = -Ly * (Lw / Lvv) displacement = np.sqrt(Dx**2 + Dy**2) # calculate curvedness curvedness = np.absolute(np.sqrt(Lxx**2 + 2 * Lxy**2 + Lyy**2)) center_map = np.zeros(image.shape, image.dtype) (height, width)=center_map.shape for y in range(height): for x in range(width): if Dx[y][x] == 0 and Dy[y][x] == 0: continue if (x + Dx[y][x])>0 and (y + Dy[y][x])>0: if (x + Dx[y][x]) < center_map.shape[1] and (y + Dy[y][x]) < center_map.shape[0] and k[y][x]<0: if displacement[y][x] >= self.minrad and displacement[y][x] <= self.maxrad: center_map[int(y+Dy[y][x])][int(x+Dx[y][x])] += curvedness[y][x] center_map = gaussian_filter(center_map, sigma=self.blur) blurred = gaussian_filter(image, sigma=self.blur) center_map = center_map * (1-blurred) # return maximum location in center_map position = np.unravel_index(np.argmax(center_map), center_map.shape) return position
StarcoderdataPython
6462820
<gh_stars>1-10 from .common import ILElement, split_tokens from .parameter import ILParameter from .fragment import CFragment, CVectorizedString, CVectorizedArray, CBlock from .local import ILLocal from .block import ILBlock class ILMethod(ILElement): next_label_number = 0 def __init__(self, lines, start): decl_parts = split_tokens(lines[start][1:], ['(', ')']) ILElement.__init__(self, decl_parts[0], { 0: 'type', 1: 'name' }, ['private', 'hidebysig', 'static', 'default', 'cil', 'managed']) self.parameters = list(ILParameter(t) for t in split_tokens(decl_parts[1], [','])) \ if decl_parts[1] != [] \ else [] self.block = ILBlock(lines, start + 1) self.locals = self.block.locals self.end = self.block.end def as_c_fragment(self, assembly, class_id, id): return CFragment( text=""" { .name = %0s, .type = %1s, .parameters = %2s, .locals = %3s .body = %0x } """, fn_defs='call_result_t %0x(call_stack_t stack) { %4s }', format_vars=[ CVectorizedString(self.name), assembly.get_type_by_name(self.type), CVectorizedArray( 'field_vector_t', list(p.as_c_fragment(assembly) for p in self.parameters)), CVectorizedArray( 'field_vector_t', list(l.as_c_fragment(assembly) for l in self.locals)), self.block.as_c_fragment(class_id, id) ])
StarcoderdataPython
6542454
<reponame>jason-neal/companion_simulations # coding: utf-8 # # Interpolate wavelength on multiple dimensions # # <NAME> - 19th July 2017 # To try and interpolate N-D data along the first axis. # # This is to be able to perfrom chisquare analsysis for many parameters. # In[ ]: import numpy as np import scipy as sp from scipy.stats import chisquare import matplotlib.pyplot as plt get_ipython().magic('matplotlib inline') # The model we have is obs (w, f), and model (wm, fm). # # the model is combined (x + (y*a)*v) * gamma two doppler shifts of v and gamma. # # We either need to be able to perform broadcasting inside Pyastronomy.dopplershift, or do it ourselves and interpolate. # # In[ ]: w = np.arange(20) A = 1.7 S = 1.1 f = A * np.sin(w) + S plt.plot(w, f, label="data") plt.legend() plt.show() # In[ ]: wm = np.linspace(-3,23, 50) fm = np.sin(wm) plt.plot(wm, fm, label="model") plt.plot(w, f, label="data") plt.show() # # Add a second axis for the amplitude # In[ ]: a = np.arange(1.3, 2, 0.05) print(a) a.shape # In[ ]: fma = fm[:, None] * a # Each column is fma.shape # In[ ]: # make wavelength axis also the same wma = wm[:, None] * np.ones_like(a) wma.shape # In[ ]: # Need to interpolate fma from wma to w # np.interp does not work on 2d. w_func = sp.interpolate.interp1d(wm, fma, axis=0, kind="slinear") # In[ ]: fma_interp = w_func(w) #fma_cube = w_func(w) #fma_spl = w_func(w) fma_interp.shape # In[ ]: plt.plot(w, fma_interp) plt.plot(w, f, "--", label="data") plt.legend() plt.show() # In[ ]: chi2 = np.sum((f[:, None] - fma_interp)**2 / fma_interp, axis=0) plt.plot(a, chi2, label="chi2") plt.legend() plt.show() # In[ ]: # Find the minimum value m = np.argmin(chi2) a_min = a[m] a_min # # Add a third axis for a vertical shift # # In[ ]: shift = np.arange(0.1, 1.3, 0.1) print(len(shift)) fmas = fma[:, :, None] + shift fmas.shape # In[ ]: wmas = wma[:, :, None] * np.ones_like(shift) wmas.shape # In[ ]: print(wm.shape) print(fmas.shape) w_sfunc = sp.interpolate.interp1d(wm, fmas, axis=0, kind="slinear") fmas_interp = w_sfunc(w) fmas_interp.shape # In[ ]: plt.plot(w, fmas_interp[:,3, :]) plt.plot(w, f, "--", label="data") plt.legend() plt.show() # In[ ]: chi2s = np.sum((f[:, None, None] - fmas_interp)**2 / fmas_interp, axis=0) plt.plot(a, chi2s, label="chi2") plt.legend() plt.show() # In[ ]: X, Y = np.meshgrid(shift, a) print(X.shape) plt.contourf(X, Y, chi2s) plt.colorbar() plt.plot() plt.show() chi2s.shape # In[ ]: c2min = chi2s.argmin() print(c2min) chi2s[np.unravel_index(c2min, chi2s.shape)] # In[ ]: np.unravel_index(976, (140, 7)) # In[ ]: plt.contour(chi2s) plt.show() # In[ ]: # # Interpolating different wavelength axis. # # Each wl dimension has a dopplershift added. # # In[ ]: c = 500 vc = (1 + np.arange(10) / c) print(wm.shape) print(vc.shape) doppler = wm[:, np.newaxis] * vc print(doppler.shape) #print(doppler) # In[ ]: plt.plot(doppler, fmas[:,:,5]) plt.show() # In[ ]: # doppler_interp = sp.interpolate.interp1d(doppler, fm) print(len(wm)) print(len(vc)) print(fma.shape) # fma includes the amplitude also. # Cannot inperpolate directly for all the different wavelengths at once. Therefore dims = fmas.shape + (len(vc),) # add extra arry to dim print(dims) result = np.empty(dims) print(result.shape) for i, v in enumerate(vc): wm_vc = wm * v # print(wm_vc.shape) # print(fma.shape) func = sp.interpolate.interp1d(wm_vc, fmas, axis=0, bounds_error=False, fill_value=99999) # print(func(wm)) result[:,:, :, i] = func(wm) # In[ ]: print(result) # # This lets me doppler shift the wavelength and return it to wm. # # In the second case for model I will just want to return it to the wavelength values of the observation. # In[ ]: # interp to obs func = sp.interpolate.interp1d(wm, result, axis=0, bounds_error=False, fill_value=np.nan) fmasd = func(w) chi2d = np.sum((f[:, None, None, np.newaxis] - fmasd)**2 / fmasd, axis=0) chi2d # In[ ]: chi2d.shape # In[ ]: fmasd.shape # In[ ]: a.shape # In[ ]: # Try a 3d chisquare x_2 = chisquare(f[:, np.newaxis, np.newaxis, np.newaxis], fmasd, axis=0).statistic x_2.argmin() vals = np.unravel_index(x_2.argmin(), x_2.shape) print("index of min = ", vals) # returns the minimum index location # This provides a framework for chisquare of large arrays. for my simulations # In[ ]: plt.title("shift min") plt.contourf(x_2[:,3,:]) plt.show() plt.contourf(x_2[4,:,:]) plt.title("amplitude min") plt.show() plt.contourf(x_2[:,:,4]) plt.title("doppler min") plt.show() # Currently these plots do not look very informative. I will need to remove the bad interpolation values also. # In[ ]:
StarcoderdataPython
11201062
"""Solutia problemei Reprezentarea unui director ca arbore""" from __future__ import print_function import os def representastree(path_to_dir, depth=0): """Reprezentarea unui director ca arbore""" files_in_dir = os.listdir(path_to_dir) for filename in files_in_dir: print ('\t' * depth, filename) path = os.path.join(path_to_dir, filename) if os.path.isdir(path): representastree(path, depth+1)
StarcoderdataPython
17623
import balanced balanced.configure('ak-test-1o9QKwUCrwstHW<KEY>') order = balanced.Order.fetch('/orders/OR7qAh5x1cFzX0U9hD628LPa')
StarcoderdataPython
238040
<reponame>enyachoke/saleor from enum import Enum from django.conf import settings from django.core.checks import register, Warning TOKEN_PATTERN = ('(?P<token>[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}' '-[0-9a-z]{12})') @register() def check_session_caching(app_configs, **kwargs): # pragma: no cover errors = [] cached_engines = { 'django.contrib.sessions.backends.cache', 'django.contrib.sessions.backends.cached_db'} if ('locmem' in settings.CACHES['default']['BACKEND'] and settings.SESSION_ENGINE in cached_engines): errors.append( Warning( 'Session caching cannot work with locmem backend', 'User sessions need to be globally shared, use a cache server' ' like Redis.', 'saleor.W001')) return errors class TaxRateType(Enum): ACCOMODATION = 'accomodation' ADMISSION_TO_CULTURAL_EVENTS = 'admission to cultural events' ADMISSION_TO_ENTERAINMENT_EVENTS = 'admission to entertainment events' ADMISSION_TO_SPORTING_EVENTS = 'admission to sporting events' ADVERTISING = 'advertising' AGRICULTURAL_SUPPLIES = 'agricultural supplies' BABY_FOODSTUFFS = 'baby foodstuffs' BIKES = 'bikes' BOOKS = 'books' CHILDRENDS_CLOTHING = 'childrens clothing' DOMESTIC_FUEL = 'domestic fuel' DOMESTIC_SERVICES = 'domestic services' E_BOOKS = 'e-books' FOODSTUFFS = 'foodstuffs' HOTELS = 'hotels' MEDICAL = 'medical' NEWSPAPERS = 'newspapers' PASSENGER_TRANSPORT = 'passenger transport' PHARMACEUTICALS = 'pharmaceuticals' PROPERTY_RENOVATIONS = 'property renovations' RESTAURANTS = 'restaurants' SOCIAL_HOUSING = 'social housing' STANDARD = 'standard' WATER = 'water' WINE = 'wine'
StarcoderdataPython
5036283
<reponame>Ekhel/Surya<filename>suryaenv/bin/django-admin.py<gh_stars>0 #!/home/ekhel/Documents/django/Surya/suryaenv/bin/python3 from django.core import management if __name__ == "__main__": management.execute_from_command_line()
StarcoderdataPython
1800431
#!/usr/bin/env python # -*- coding:utf-8 -*- import os import logging logger = logging.getLogger('merge') logger.setLevel(logging.DEBUG) logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG) file_name = ['as', 'cityu', 'msr', 'pku', 'nlpcc'] data_name = "data.txt" current_path = os.path.abspath('.') raw_data = [] sen_count = 0 for item in file_name: file_path = os.path.join(current_path, item) with open(file_path, 'r') as f: sentence = [] for line in f: line = line.strip().split() if len(line) == 0: raw_data.append(sentence) sen_count += 1 sentence = [] if sen_count % 100000 == 0: logger.info("Read %d sentences", sen_count) else: sentence.append(line[0]) data_path = os.path.join(current_path, data_name) sen_count = 0 with open(data_path, 'w') as f: for sen in raw_data: sen_count += 1 if sen_count % 100000 == 0: logger.info("Write %d sentences", sen_count) line = '' for char in sen: line += char + ' ' line += '\n' f.write(line)
StarcoderdataPython
11226728
<reponame>CrisDS81/copulae from abc import ABC from typing import Collection, Tuple, Union import numpy as np from copulae.copula import BaseCopula, Param from copulae.core import EPS, create_cov_matrix, is_psd, near_psd, tri_indices from copulae.utility.annotations import * class AbstractEllipticalCopula(BaseCopula[Param], ABC): """ The abstract base class for Elliptical Copulas """ def __init__(self, dim: int, name: str): super().__init__(dim, name) self._rhos = np.zeros(sum(range(dim))) @cast_input(['x'], optional=True) @squeeze_output def drho(self, x=None): if x is None: x = self._rhos return 6 / (np.pi * np.sqrt(4 - x ** 2)) @cast_input(['x'], optional=True) @squeeze_output def dtau(self, x=None): if x is None: x = self._rhos return 2 / (np.pi * np.sqrt(1 - x ** 2)) @cast_input(['tau']) @squeeze_output def itau(self, tau): return np.sin(np.asarray(tau) * np.pi / 2) def log_lik(self, data: np.ndarray, *, to_pobs=True, ties="average"): if not is_psd(self.sigma): return -np.inf if hasattr(self, '_df') and getattr(self, "_df", 0) <= 0: # t copula return -np.inf return super().log_lik(data, to_pobs=to_pobs, ties=ties) @property def rho(self): return np.arcsin(self._rhos / 2) * 6 / np.pi @property def sigma(self): """ The covariance matrix for the elliptical copula :return: numpy array Covariance matrix for elliptical copula """ return create_cov_matrix(self._rhos) @property def tau(self): return 2 * np.arcsin(self._rhos) / np.pi def __getitem__(self, index: Union[int, Tuple[Union[slice, int], Union[slice, int]], slice]) \ -> Union[np.ndarray, float]: if isinstance(index, slice): return self.sigma elif isinstance(index, int): return self._rhos[index] elif isinstance(index, tuple): if len(index) != 2: raise IndexError('only 2-dimensional indices supported') return self.sigma[index] raise IndexError("invalid index type") def __setitem__(self, index: Union[int, Tuple[Union[slice, int], Union[slice, int]], slice], value: Union[float, Collection[float], np.ndarray]): d = self.dim if np.isscalar(value): if value < -1 or value > 1: raise ValueError("correlation value must be between -1 and 1") else: value = np.asarray(value) if not np.all((value >= -1 - EPS) & (value <= 1 + EPS)): raise ValueError("correlation value must be between -1 and 1") if isinstance(index, slice): value = near_psd(value) if value.shape != (d, d): raise ValueError(f"The value being set should be a matrix of dimension ({d}, {d})") self._rhos = value[tri_indices(d, 1, 'lower')] return if isinstance(index, int): self._rhos[index] = value else: index = tuple(index) if len(index) != 2: raise IndexError('index can only be 1 or 2-dimensional') x, y = index # having 2 slices for indices is equivalent to self[:] if isinstance(x, slice) and isinstance(y, slice): self[:] = value return elif isinstance(x, slice) or isinstance(y, slice): value = np.repeat(value, d) if np.isscalar(value) else np.asarray(value) if len(value) != d: raise ValueError(f"value must be a scalar or be a vector with length {d}") # one of the item is for i, v in enumerate(value): idx = (i, y) if isinstance(x, slice) else (x, i) if idx[0] == idx[1]: # skip diagonals continue idx = _get_rho_index(d, idx) self._rhos[idx] = v else: # both are integers idx = _get_rho_index(d, index) self._rhos[idx] = float(value) self._force_psd() def _force_psd(self): """ Forces covariance matrix to be positive semi-definite. This is useful when user is overwriting covariance parameters """ cov = near_psd(self.sigma) self._rhos = cov[tri_indices(self.dim, 1, 'lower')] def _get_rho_index(dim: int, index: Tuple[int, int]) -> int: x, y = index if x < 0 or y < 0: raise IndexError('Only positive indices are supported') elif x >= dim or y >= dim: raise IndexError('Index cannot be greater than dimension of copula') elif x == y: raise IndexError('Cannot set values along the diagonal') for j, v in enumerate(zip(*tri_indices(dim, 1, 'upper' if x < y else 'lower'))): if (x, y) == v: return j raise IndexError(f"Unable to find index {(x, y)}")
StarcoderdataPython
11279840
from flask import request, flash, url_for from conekt.extensions import admin_required from werkzeug.exceptions import abort from werkzeug.utils import redirect from conekt.controllers.admin.controls import admin_controls from conekt.forms.admin.add_expression_specificity import AddConditionSpecificityForm, AddTissueSpecificityForm from conekt.models.condition_tissue import ConditionTissue from conekt.models.expression.specificity import ExpressionSpecificityMethod @admin_controls.route('/add/condition_specificity', methods=['POST']) @admin_required def add_condition_specificity(): form = AddConditionSpecificityForm(request.form) form.populate_species() if request.method == 'POST' and form.validate(): species_id = int(request.form.get('species_id')) description = request.form.get('description') ExpressionSpecificityMethod.calculate_specificities(species_id, description, False) flash('Calculated condition specificities for species %d' % species_id, 'success') return redirect(url_for('admin.index')) else: if not form.validate(): flash('Unable to validate data, potentially missing fields', 'danger') return redirect(url_for('admin.index')) else: abort(405) @admin_controls.route('/add/tissue_specificity', methods=['POST']) @admin_required def add_tissue_specificity(): form = AddTissueSpecificityForm(request.form) form.populate_species() if request.method == 'POST' and form.validate(): species_id = int(request.form.get('species_id')) description = request.form.get('description') file = request.files[form.file.name].read() if file != b'': data = file.decode("utf-8").replace("\r\n", "\n").splitlines() #S.Dash(Feb-13-2019):data = file.decode("utf-8").replace("\r\n", "\n").split('\n') print(data) #Sdash debug order = [] colors = [] conditions = [] condition_tissue = {} for d in data: condition, tissue, color = d.split("\t") conditions.append(condition) condition_tissue[condition] = tissue if tissue not in order: order.append(tissue) colors.append(color) specificity_method_id = ExpressionSpecificityMethod.calculate_tissue_specificities(species_id, description, condition_tissue, conditions, use_max=True, remove_background=False) ConditionTissue.add(species_id, condition_tissue, order, colors, specificity_method_id) flash('Calculated tissue specificities for species %d' % species_id, 'success') return redirect(url_for('admin.index')) else: if not form.validate(): flash('Unable to validate data, potentially missing fields', 'danger') return redirect(url_for('admin.index')) else: abort(405)
StarcoderdataPython
5084120
# -*- coding: utf-8 -*- """This module contains the RepoComment class.""" from __future__ import unicode_literals from .. import models from .. import users from ..decorators import requires_auth class _RepoComment(models.GitHubCore): """The :class:`RepoComment <RepoComment>` object. This stores the information about a comment on a file in a repository. Two comment instances can be checked like so:: c1 == c2 c1 != c2 And is equivalent to:: c1.id == c2.id c1.id != c2.id """ class_name = '_RepoComment' def _update_attributes(self, comment): self._api = comment['url'] self.author_association = comment['author_association'] self.body = comment['body'] self.commit_id = comment['commit_id'] self.created_at = self._strptime(comment['created_at']) self.html_url = comment['html_url'] self.id = comment['id'] self.line = comment['line'] self.path = comment['path'] self.position = comment['position'] self.updated_at = self._strptime(comment['updated_at']) self.user = users.ShortUser(comment['user'], self) def _repr(self): return '<{0} [{1}/{2}]>'.format( self.class_name, self.commit_id[:7], self.user.login or '' ) @requires_auth def delete(self): """Delete this comment. :returns: True if successfully deleted, False otherwise :rtype: bool """ return self._boolean(self._delete(self._api), 204, 404) @requires_auth def edit(self, body): """Edit this comment. :param str body: (required), new body of the comment, Markdown formatted :returns: True if successful, False otherwise :rtype: bool """ if body: json = self._json(self._patch(self._api, json={'body': body}), 200) if json: self._update_attributes(json) return True return False update = edit class RepoComment(_RepoComment): """The representation of the full comment on an object in a repository. This object has the same attributes as a :class:`~github3.repos.comment.ShortComment` as well as the following: .. attribute:: body_html The HTML formatted text of this comment. .. attribute:: body_text The plain-text formatted text of this comment. """ class_name = 'Repository Comment' def _update_attributes(self, comment): super(RepoComment, self)._update_attributes(comment) self.body_text = comment['body_text'] self.body_html = comment['body_html'] class ShortComment(_RepoComment): """The representation of an abridged comment on an object in a repo. This object has the following attributes: .. attribute:: author_association The affiliation the author of this comment has with the repository. .. attribute:: body The Markdown formatted text of this comment. .. attribute:: commit_id The SHA1 associated with this comment. .. attribute:: created_at A :class:`~dateteime.datetime` object representing the date and time when this comment was created. .. attribute:: html_url The URL to view this comment in a browser. .. attribute:: id The unique identifier of this comment. .. attribute:: line The line number where the comment is located. .. attribute:: path The path to the file where this comment was made. .. attribute:: position The position in the diff where the comment was left. .. attribute:: updated_at A :class:`~datetime.datetime` object representing the date and time when this comment was most recently updated. .. attribute:: user A :class:`~github3.users.ShortUser` representing the author of this comment. """ class_name = 'Short Repository Comment' _refresh_to = RepoComment
StarcoderdataPython
1751369
from flask import Flask, request from flask_cors import CORS from flask_restx import Api, Resource from flask_jwt_extended import JWTManager from datetime import timedelta, datetime from pytz import timezone from dotenv import load_dotenv from boto3 import resource from os import getenv from werkzeug.security import generate_password_hash, check_password_hash from flask_jwt_extended import create_access_token, create_refresh_token, get_jwt_identity from .services.auth import auth_verify from .namespaces.users import users as nsUsers load_dotenv() project_name = getenv('PROJECT_NAME') jwt_secret_key = getenv('JWT_SECRET_KEY') dynamodb = resource('dynamodb') table = dynamodb.Table(f'{project_name}-users') app = Flask(__name__) CORS(app) api = Api(app) app.config["JWT_SECRET_KEY"] = jwt_secret_key app.config["JWT_ACCESS_TOKEN_EXPIRES"] = timedelta(days=1) jwt = JWTManager(app) # Namespaces api.add_namespace(nsUsers) @api.route('/login') class Login(Resource): @api.doc('login') def post(self): data = request.get_json() if 'username' not in data: return 'Missing username' elif 'password' not in data: return 'Missing password' else: response = table.get_item( Key={ 'username': data['username'] } ) if 'Item' in response: item = response['Item'] check = check_password_hash(item['password'], data['password']) if check == True: access_token = create_access_token(identity=data['username']) refresh_token = create_refresh_token(identity=data['username']) return {'access_token': access_token, 'refresh_token': refresh_token} else: return 'Password incorrect', 400 else: return 'User not found', 400 @api.route('/change-password') class ChangePassword(Resource): @api.doc('change_password') @auth_verify(api) def put(self): identity = get_jwt_identity() data = request.get_json() if 'new_password' not in data: return 'Missing new password' if 'new_password_confirmation' not in data: return 'Missing new password confirmation' data['updated_at'] = str(datetime.now(timezone('America/Sao_Paulo'))) data['password'] = <PASSWORD>_password_hash(data['new_password']) table.update_item( Key={ 'username': identity }, UpdateExpression='set password=:p, updated_at=:a', ExpressionAttributeValues={ ':p': data['password'], ':a': data['updated_at'] } ) return 'Password changed', 200
StarcoderdataPython
9748711
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('management', '0016_demoresourcedata_validation_result'), ] operations = [ migrations.AlterField( model_name='demoresourcedata', name='ip_address', field=models.GenericIPAddressField(), ), ]
StarcoderdataPython
12834073
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Sep 28 05:39:18 2019 @author: ladvien """ from time import sleep, time """ MOTOR_NUM: X = 0 Y = 1 Z = 2 E0 = 3 E1 = 4 PACKET_TYPES 0x01 = motor_write 0x02 = motor_halt DIRECTION 0x00 = CW 0x01 = CCW MOTOR MOVE PROTOCOL: 0 1 2 3 4 MOTOR_PACKET = PACKET_TYPE DIR STEPS_1 STEPS_2 MICROSECONDS_BETWEEN MOTOR_PACKET = 01 00 03 E8 05 MOTOR_PACKET = 0x 01010003E8050A HALT = 0x0F PACKAGE = PACKET1 PACKET2 PACKET3 PACKET4 PACKET5 PACKAGE_EXAMPLE = 01 00 03 E8 05 01 00 03 E8 05 01 00 03 E8 05 01 00 03 E8 05 01 00 03 E8 05 0 1 2 0 COMPLETED_PACKET = PACKET_TYPE SUCCESS MOTOR_NUM \n 0x01 PACKET_TYPES: MOTOR_FINISHED = 0x01 SUCCESS_TYPES: SUCCESS = 0x06 FAIL = 0x15 Types not motor related, MOTOR_NUM = 0. 01 01 00 FF E8 01 01 02 00 FF E8 01 01 02 00 FF E8 01 01 02 00 FF E8 01 01 02 00 FF E8 01 """ class RAMPS: DRIVE_CMD = 0x01 HALT_CMD = 0x0F DIR_CC = 0x00 DIR_CCW = 0x01 COMPLETED_CMD = 0x07 END_TX = 0x0A ACKNOWLEDGE = 0x06 NEG_ACKNOWLEDGE = 0x15 SUCCESS = 0x06 FAIL = 0x15 MOTOR_X = 0x01 MOTOR_Y = 0x02 MOTOR_Z = 0x03 MOTOR_E1 = 0x04 MOTOR_E2 = 0x05 def __init__(self, ser, debug = False): self.ser = ser self.toggle_debug = debug self.rx_buffer_size = 256 self.serial_delay = 0.1 def toggle_debug(self): self.debug = not self.debug def print_debug(self, message): if self.toggle_debug: print(message) """ COMMUNICATION """ # Prepare for a serial send. def encode_packet(self, values): return bytearray(values) # Prepare a packet the slave will understand def prepare_motor_packet(self, motor_num, direction, steps, milli_between): steps_1 = (steps >> 8) & 0xFF steps_2 = (steps) & 0xFF return [self.DRIVE_CMD, motor_num, direction, steps_1, steps_2, milli_between, self.END_TX] def read_available(self, as_ascii = False): self.print_debug(f'Reading available.') # 1. Get all available data. # 2. Unless buffer exceeded. # 3. Return a list of the data. incoming_data = [] incoming_data_size = 0 while self.ser.in_waiting > 0: incoming_data_size += 1 if incoming_data_size > self.rx_buffer_size: self.print_debug(f'Buffer overflow.') return list('RX buffer overflow.') if as_ascii: incoming_data.append(self.ser.readline().decode('utf-8')) else: incoming_data += self.ser.readline() self.print_debug(f'Completed reading available.') return incoming_data def check_for_confirm(self, command_expected): confirmation = self.read_available() if len(confirmation) > 0: if confirmation[0] == command_expected: return True else: return False """ RAMPS UTILITY """ def reset_ramps(self, print_welcome = False): self.print_debug(f'Reseting Arduino.') # Reset the Arduino Mega. self.ser.setDTR(False) sleep(0.4) self.ser.setDTR(True) sleep(2) # Get welcome message. welcome_message = [] while self.ser.in_waiting > 0: welcome_message.append(self.ser.readline().decode('utf-8') ) self.print_debug(f'Completed reset.') if print_welcome: # Print it for the user. print(''.join(welcome_message)) return else: return """ MOTOR COMMANDS """ def move(self, motor, direction, steps, milli_secs_between_steps): # 1. Create a list containg RAMPs command. # 2. Encode it for serial writing. # 3. Write to serial port. # 4. Check for ACK or NACK. # 5. Poll serial for completed command. packet = self.prepare_motor_packet(motor, direction, steps, milli_secs_between_steps) packet = self.encode_packet(packet) self.print_debug(f'Created move packet: {packet}') self.write_move(packet) # Don't miss ACK to being in a hurry. sleep(self.serial_delay) confirmation = self.read_available() print(confirmation) if confirmation[0] == self.ACKNOWLEDGE: self.print_debug(f'Move command acknowledged.') if(self.wait_for_complete(120)): return True return False def wait_for_complete(self, timeout): # 1. Wait for complete or timeout # 2. Return whether the move was successful. start_time = time() while True: now_time = time() duration = now_time - start_time self.print_debug(duration) if(duration > timeout): return False if self.check_for_confirm(self.COMPLETED_CMD): self.print_debug(f'Move command completed.') return True sleep(self.serial_delay) def write_move(self, packet): self.ser.write(packet) self.print_debug(f'Executed move packet: {packet}')
StarcoderdataPython
193712
<reponame>umyuu/Sample # -*- coding: utf-8 -*- import requests import bs4 import pandas as pd # pandas def main(): html =""" <ul id="front"> <li class="icon-01">乗用車</li> <li class="icon-02">トラック</li> <li class="icon-11">軽自動車</li> </ul> """ soup = bs4.BeautifulSoup(html, "lxml") icon_part = soup.find_all("ul", id="front") car_model = [li_tag.text for ul_tag in icon_part for li_tag in ul_tag.find_all('li')] print(car_model) if __name__ == '__main__': main()
StarcoderdataPython
1894889
<reponame>liusida/thesis-bodies # pick 16 # 801.2.1 All 16*4 robots selected (add a mark to 801.1.results). # 801.2.2 The distribution of learnability per type. (histogram or density plot with y-axis represents the learnability) (add a threshold to show our selection) (add another line to indicate the baseline as a horizontal green dashed line) # Note: this part I trained them with stack_frame=4 # And select bodies based on how quick they pass a threshold. # The main goal is to reduce time of the following experiments. import pickle,os,glob import numpy as np import pandas as pd from common import tflogs2pandas from common import common, colors args = common.args exp_name = "801.2.1.stacked" tensorboard_path = f"output_data/tensorboard/{exp_name}" cache_path = f"output_data/cache/{exp_name}" output_path = f"output_data/plots/" g_baselines = [1442.1541809082032, 1762.0622802734374, 1642.0044189453124, 2381.102606201172] g_cursor = 0 def load_tb(force=0): try: if force: raise FileNotFoundError df = pd.read_pickle(cache_path) except FileNotFoundError: dfs = [] all_jobs = [] use_glob = False try: with open(f"output_data/jobs/{exp_name}.pickle", "rb") as f: all_jobs = pickle.load(f) except: use_glob = True if use_glob: all_jobs = glob.glob(f"{tensorboard_path}/*/PPO_1") for job in all_jobs: if use_glob: tb_path = job else: tb_path = f"{tensorboard_path}/model-399-499-599-699-CustomAlignWrapper-md{job['str_md5']}-sd{job['run_seed']}/PPO_1" print(f"Loading {tb_path}") if not os.path.exists(tb_path): continue df = tflogs2pandas.tflog2pandas(tb_path) df = df[df["metric"].str.startswith("eval/")] if not use_glob: df["alignment_id"] = job["seed"] df["custom_alignment"] = job["custom_alignment"] df["str_md5"] = job["str_md5"] df["vacc_run_seed"] = job['run_seed'] df["label"] = job['label'] dfs.append(df) df = pd.concat(dfs) df.to_pickle(cache_path) # get robot name: df["robot_id"] = df["metric"].str.slice(start=5, stop=8) df["robot"] = df["robot_id"].apply(lambda x: common.gym_interface.template(int(x)).capitalize()) df["Learnability"] = df["value"] return df df = load_tb(args.force_read) print(df) import seaborn as sns import matplotlib.pyplot as plt facet_grid_col_order = ["Walker2d", "Halfcheetah", "Ant", "Hopper"] def check_finished(): sns.countplot(data=df, x="robot") # check every run is here plt.show() plt.close() # check_finished() # exit(0) def plot_learning_curve(title="Default Plot"): g = sns.FacetGrid(data=df, col="robot", col_order=facet_grid_col_order, ylim=[0,3000]) g.map(sns.lineplot, "step", "Learnability", color=colors.plot_color[1]) # def _const_line(data, **kwargs): # plt.axhline(y=1500, color=colors.plot_color[1]) # g.map(_const_line, "Learnability") g.fig.suptitle(title) # g.set(yscale="log") plt.tight_layout() plt.savefig(f"{output_path}/{exp_name}.learning_curve.png") # plot_learning_curve("Train on one variant (N=1)") def density_at_final_step(df, step, title, filename=""): import warnings warnings.simplefilter(action='ignore', category=FutureWarning) # Warning: sns.distplot will be removed in the future version. _df = df[df["step"]==step] g = sns.FacetGrid(data=_df, col="robot", col_order=facet_grid_col_order, ylim=[0,3000]) g.map(sns.distplot, "Learnability", vertical=True, hist=False, rug=True, color=colors.plot_color[1]) # def _const_line(data, **kwargs): # plt.axhline(y=1500, color=colors.plot_color[1]) # plt.locator_params(nbins=3) # g.map(_const_line, "Learnability") g.fig.suptitle(title) g.set_xlabels("Density") g.set_ylabels("Learnability") plt.tight_layout() plt.savefig(f"{output_path}/{exp_name}{filename}.density.png") # density_at_final_step(step=df["step"].max(), title="Random variation in body parameters") def select_by_training_time(df): threshold = 1500 df = df[df["value"]>=threshold] df = df.groupby(by="robot_id").min("step") print("All selected:") dfs = [] for i in [3,4,5,6]: _df = df[df.index.str.startswith(str(i))].sort_values("step", ascending=True)[:20] dfs.append(_df) df = pd.concat(dfs) df = df.reset_index() df["robot"] = df["robot_id"].apply(lambda x: common.gym_interface.template(int(x)).capitalize()) print(df.head(80)) # Copy them to ../input_data/bodies, and re-index them so that 300,400,500,600 is the quickest learner, and then 301,401,501,601, etc. select_by_training_time(df) # def select_top(df,num_selected=20): # _df = df[df["step"]==df["step"].max()] # select the records for at the final step # _df = _df.groupby("robot_id").mean().reset_index() # take average of all 3 seeds # _df["robot"] = _df["robot_id"].apply(lambda x: common.gym_interface.template(int(x)).capitalize()) # bring back "robot" column # dfs = [] # for r in facet_grid_col_order: # _df_1 = _df[_df["robot"]==r] # select one type # _df_1 = _df_1.sort_values("value", ascending=False) # sort by learnability # _df_1 = _df_1[:num_selected] # select top n=20 # selected_ids = _df_1["robot_id"] # dfs.append(df[df["robot_id"].isin(selected_ids)]) # add to outcome # return pd.concat(dfs) # num_selected = 20 # a detail here is if we select top 20 from all 50 # df_selected = select_top(df=df, num_selected=num_selected) # print(df_selected.shape) # n x 4types x 3seeds # density_at_final_step(df=df_selected, step=df["step"].max(), title=f"Selected {num_selected} variants: Density at step {df['step'].max()//1e5/10:.1f}e6 (N=3)", filename="_selected")
StarcoderdataPython
1666870
<filename>pbxplore/structure/loader.py #! /usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import # Local module from .structure import Chain, Atom from .PDB import PDB # Conditional import try: import MDAnalysis except ImportError: IS_MDANALYSIS = False else: IS_MDANALYSIS = True # Create the __all__ keyword according to the conditional import __all__ = ['chains_from_files'] if IS_MDANALYSIS: __all__ += ['chains_from_trajectory'] def chains_from_files(path_list): for pdb_name in path_list: pdb = PDB(pdb_name) for chain in pdb.get_chains(): # build comment comment = pdb_name if chain.model: comment += " | model %s" % (chain.model) if chain.name: comment += " | chain %s" % (chain.name) yield comment, chain def chains_from_trajectory(trajectory, topology): universe = MDAnalysis.Universe(topology, trajectory) selection = universe.select_atoms("backbone") #Initialize structure with the selection structure = Chain() for atm in selection: atom = Atom.read_from_xtc(atm) # append structure with atom structure.add_atom(atom) for ts in universe.trajectory: #Update only with new coordinates structure.set_coordinates(selection.positions) # define structure comment comment = "%s | frame %s" % (trajectory, ts.frame) yield comment, structure
StarcoderdataPython
11326435
"""Configurations fixed for library""" from dataclasses import dataclass from typing import Dict, List import tyaml from ocomone import Resources @dataclass(frozen=True) class BaseConfiguration: """Base configuration class""" name: str params: dict @dataclass(frozen=True) class AlertaConfiguration: """Alerta configuration class""" config_id: int config_name: str alerta_endpoint: str alerta_timeout: int alerta_debug: bool @dataclass(frozen=True) class TopicMap: """Topic map class""" to: str subject: str _CONFIGS = Resources(__file__) def topic_map(topics: list): """Topic map""" map = {} topics = {item[0]: item[1:] for item in topics} for key, value in topics.items(): map.update({key: TopicMap(*value)}) return map def _cfg_load(cfg_file: str, cfg_class): with open(cfg_file, 'r') as src_cfg: configs = tyaml.load(src_cfg, cfg_class) # type: List[BaseConfiguration] result = {cfg.name: cfg for cfg in configs} return result DATABASE: Dict[str, BaseConfiguration] = _cfg_load(_CONFIGS['db_init.yaml'], List[BaseConfiguration])
StarcoderdataPython
252023
<filename>src/python/examples/factor_analysis.py<gh_stars>0 from quipp import * def run(): num_components = 2 point_dim = 5 ComponentsType = Vector(num_components, Double) PointType = Vector(point_dim, Double) get_point = rand_function(ComponentsType, PointType) def sample(): components = [normal(0, 1) for i in range(num_components)] return (components, get_point(components)) return sample run_factor_analysis_example(run)
StarcoderdataPython
6446641
<gh_stars>0 from classes.grid import Hexgrid from classes.hex import Hex from utils.funcs import face_hex_to_cube, cube_line, wedge_hex import numpy as np import matplotlib.pyplot as plt grid_size = 5 grids = [] num_grids = 16 num_cols = 4 num_rows = 4 num_rivers = 1 num_mountains = 2 num_forests = 1 forest_radius = 1 # generate some grids for i in range(num_grids): grid = Hexgrid(grid_size) # Generate rivers for river in range(num_rivers): river_loop = True start_coords = None end_coords = None while(river_loop): # Try these out start_face = np.random.randint(0, 6) start_hex = np.random.randint(0, grid_size) end_face = np.random.randint(0, 6) end_hex = np.random.randint(0, grid_size) if(start_face is end_face): continue # Check if we ended up picking the same hex # This would happen if the cubic distance between them is 0 start_coords = face_hex_to_cube(start_face, start_hex, grid_size) end_coords = face_hex_to_cube(end_face, end_hex, grid_size) if(Hex.cube_distance(Hex(*start_coords), Hex(*end_coords)) < 1): continue # If we are here, we are good river_loop = False # Get all hexes in the line river_hexes = cube_line(Hex(*start_coords), Hex(*end_coords)) # Change the colors of these hexes to be river colored for hex in river_hexes: grid.hexes[hex].color = '#0343df' # Generate Mountains for mountain in range(num_mountains): # First pick a wedge, row, and index wedge = np.random.randint(0, 6) row = np.random.randint(0, 6) index = np.random.randint(0, 6) # Get coordinates mountain_coords = wedge_hex(wedge, row, index, grid_size) print('{} {} {} - {}'.format(wedge, row, index, mountain_coords)) grid.hexes[mountain_coords].color = '#ad8150' # Generate Forests for forest in range(num_forests): # First pick a wedge, row, and index wedge = np.random.randint(0, 6) row = np.random.randint(0, 6) index = np.random.randint(0, 6) # Get forest center coordinates forest_coords = wedge_hex(wedge, row, index, grid_size) # Get all hexes within range of this forest_hexes = Hex.hex_range(Hex(*forest_coords), forest_radius) # Loop through them to add them! for hex in forest_hexes: # Derefernce for convience x,y,z = hex # Check to see if this hex is outside our area if(max(abs(x), abs(y), abs(z)) >= grid_size): # Yep continue grid.hexes[hex].color = '#15b01a' # Add this grid grid.hexes[0,0,0].color = '#ffff14' grids.append(grid) # Lets make the plot and add everything to it fig, axes = plt.subplots(num_rows, num_cols) fig.suptitle('Example Maps') cur_plot = 0 for cur_row in range(num_rows): for cur_col in range(num_cols): ax = axes[cur_row, cur_col] ax = grids[cur_plot].set_axis(ax) cur_plot += 1 plt.show()
StarcoderdataPython
5166960
<gh_stars>1-10 # pylint: disable=missing-docstring,no-self-use,protected-access """ Copyright 2017 ARM Limited 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 unittest import mock from icetea_lib.TestBench.Plugins import Plugins, PluginException class MockArgs(object): # pylint: disable=too-few-public-methods def __init__(self): self.silent = True class MockLogger(object): def __init__(self): pass def warning(self, *args, **kwargs): pass def info(self, *args, **kwargs): pass def error(self, *args, **kwargs): pass class PluginMixerTests(unittest.TestCase): def test_start_external_services(self): mocked_config = { "requirements": { "external": { "apps": [ { "name": "test_app" } ] } } } mixer = Plugins(mock.MagicMock(), mock.MagicMock(), mock.MagicMock(), mocked_config) mixer.init(mock.MagicMock()) mixer._env = {} mixer._args = MockArgs() mixer._logger = MockLogger() mixer._pluginmanager = mock.MagicMock() mixer._pluginmanager.start_external_service = mock.MagicMock( side_effect=[PluginException, True]) with self.assertRaises(EnvironmentError): mixer.start_external_services() mixer._pluginmanager.start_external_service.assert_called_once_with( "test_app", conf={"name": "test_app"}) @mock.patch("icetea_lib.TestBench.Plugins.GenericProcess") def test_start_generic_app(self, mock_gp): mocked_config = { "requirements": { "external": { "apps": [ { "cmd": [ "echo", "1" ], "path": "test_path" } ] } } } mixer = Plugins(mock.MagicMock(), mock.MagicMock(), mock.MagicMock(), mocked_config) mixer._env = dict() mixer._logger = MockLogger() mixer._args = MockArgs() mocked_app = mock.MagicMock() mocked_app.start_process = mock.MagicMock() mock_gp.return_value = mocked_app mixer.start_external_services() mocked_app.start_process.assert_called_once() mock_gp.assert_called_with(cmd=["echo", "1"], name="generic", path="test_path")
StarcoderdataPython
3573658
<reponame>jacksonicson/paper.IS2015 ''' Java is used to get the length of all log messages stored in sonar. The length of each log message is stored in a txt file. This file gets read by this script which then calculates some descriptive statistic metrics about the log message length. ''' import numpy as np ########################## ## Configuration ## ########################## FILE = 'C:/tmep/msgs.txt' ########################## arr = np.genfromtxt(FILE, delimiter=',') time = arr[:,0] pre = time[0] time[0] = 0 for i in xrange(1, len(time)): delta = time[i] - pre pre = time[i] time[i] = delta print 'time mean: %f' % np.mean(time) print 'time std dev: %f' % np.std(time) import matplotlib.pyplot as plt print time bins = np.linspace(0, 10000, 100) n, bins, patches = plt.hist(time, bins) plt.show() #from scipy.cluster.vq import kmeans #centroids , variance = kmeans(time, 400) #print centroids arr = arr[:,1] print 'max: %f' % np.max(arr) print 'min: %f' % np.min(arr) print 'mean: %f' % np.mean(arr) print 'std dev: %f' % np.std(arr) print '90 percentile: %f' % np.percentile(arr, 90) print '50 percentile: %f' % np.percentile(arr, 50) print '10 percentile: %f' % np.percentile(arr, 10) import matplotlib.pyplot as plt f = arr > 0 arr = arr[f] arr = np.log(arr) from scipy.stats import gaussian_kde #n, bins, patches = plt.hist(arr, 50, facecolor='g', alpha=0.75) density = gaussian_kde(arr) xs = np.linspace(0,8,200) density.covariance_factor = lambda : .25 density._compute_covariance() plt.plot(xs,density(xs)) plt.show() hist = np.histogram(arr, 50) print hist
StarcoderdataPython
6492168
<gh_stars>1-10 import face_recognition if __name__ == '__main__': image = face_recognition.load_image_file('images/zhouwei.jpg') # 自动查找图片中的所有面部 face_locations = face_recognition.face_locations(image) print(face_locations)
StarcoderdataPython
187425
<filename>build/PureCloudPlatformClientV2/models/coaching_notification.py<gh_stars>1-10 # coding: utf-8 """ Copyright 2016 SmartBear Software 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. Ref: https://github.com/swagger-api/swagger-codegen """ from pprint import pformat from six import iteritems import re import json from ..utils import sanitize_for_serialization class CoachingNotification(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self): """ CoachingNotification - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'id': 'str', 'name': 'str', 'marked_as_read': 'bool', 'action_type': 'str', 'relationship': 'str', 'date_start': 'datetime', 'length_in_minutes': 'int', 'status': 'str', 'user': 'UserReference', 'appointment': 'CoachingAppointmentResponse', 'self_uri': 'str' } self.attribute_map = { 'id': 'id', 'name': 'name', 'marked_as_read': 'markedAsRead', 'action_type': 'actionType', 'relationship': 'relationship', 'date_start': 'dateStart', 'length_in_minutes': 'lengthInMinutes', 'status': 'status', 'user': 'user', 'appointment': 'appointment', 'self_uri': 'selfUri' } self._id = None self._name = None self._marked_as_read = None self._action_type = None self._relationship = None self._date_start = None self._length_in_minutes = None self._status = None self._user = None self._appointment = None self._self_uri = None @property def id(self): """ Gets the id of this CoachingNotification. The globally unique identifier for the object. :return: The id of this CoachingNotification. :rtype: str """ return self._id @id.setter def id(self, id): """ Sets the id of this CoachingNotification. The globally unique identifier for the object. :param id: The id of this CoachingNotification. :type: str """ self._id = id @property def name(self): """ Gets the name of this CoachingNotification. The name of the appointment for this notification. :return: The name of this CoachingNotification. :rtype: str """ return self._name @name.setter def name(self, name): """ Sets the name of this CoachingNotification. The name of the appointment for this notification. :param name: The name of this CoachingNotification. :type: str """ self._name = name @property def marked_as_read(self): """ Gets the marked_as_read of this CoachingNotification. Indicates if notification is read or unread :return: The marked_as_read of this CoachingNotification. :rtype: bool """ return self._marked_as_read @marked_as_read.setter def marked_as_read(self, marked_as_read): """ Sets the marked_as_read of this CoachingNotification. Indicates if notification is read or unread :param marked_as_read: The marked_as_read of this CoachingNotification. :type: bool """ self._marked_as_read = marked_as_read @property def action_type(self): """ Gets the action_type of this CoachingNotification. Action causing the notification. :return: The action_type of this CoachingNotification. :rtype: str """ return self._action_type @action_type.setter def action_type(self, action_type): """ Sets the action_type of this CoachingNotification. Action causing the notification. :param action_type: The action_type of this CoachingNotification. :type: str """ allowed_values = ["Create", "Update", "Delete", "StatusChange"] if action_type.lower() not in map(str.lower, allowed_values): # print("Invalid value for action_type -> " + action_type) self._action_type = "outdated_sdk_version" else: self._action_type = action_type @property def relationship(self): """ Gets the relationship of this CoachingNotification. The relationship of this user to this notification's appointment :return: The relationship of this CoachingNotification. :rtype: str """ return self._relationship @relationship.setter def relationship(self, relationship): """ Sets the relationship of this CoachingNotification. The relationship of this user to this notification's appointment :param relationship: The relationship of this CoachingNotification. :type: str """ allowed_values = ["Attendee", "Creator", "Facilitator"] if relationship.lower() not in map(str.lower, allowed_values): # print("Invalid value for relationship -> " + relationship) self._relationship = "outdated_sdk_version" else: self._relationship = relationship @property def date_start(self): """ Gets the date_start of this CoachingNotification. The start time of the appointment relating to this notification. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z :return: The date_start of this CoachingNotification. :rtype: datetime """ return self._date_start @date_start.setter def date_start(self, date_start): """ Sets the date_start of this CoachingNotification. The start time of the appointment relating to this notification. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z :param date_start: The date_start of this CoachingNotification. :type: datetime """ self._date_start = date_start @property def length_in_minutes(self): """ Gets the length_in_minutes of this CoachingNotification. The duration of the appointment on this notification :return: The length_in_minutes of this CoachingNotification. :rtype: int """ return self._length_in_minutes @length_in_minutes.setter def length_in_minutes(self, length_in_minutes): """ Sets the length_in_minutes of this CoachingNotification. The duration of the appointment on this notification :param length_in_minutes: The length_in_minutes of this CoachingNotification. :type: int """ self._length_in_minutes = length_in_minutes @property def status(self): """ Gets the status of this CoachingNotification. The status of the appointment for this notification :return: The status of this CoachingNotification. :rtype: str """ return self._status @status.setter def status(self, status): """ Sets the status of this CoachingNotification. The status of the appointment for this notification :param status: The status of this CoachingNotification. :type: str """ allowed_values = ["Scheduled", "InProgress", "Completed", "InvalidSchedule"] if status.lower() not in map(str.lower, allowed_values): # print("Invalid value for status -> " + status) self._status = "outdated_sdk_version" else: self._status = status @property def user(self): """ Gets the user of this CoachingNotification. The user of this notification :return: The user of this CoachingNotification. :rtype: UserReference """ return self._user @user.setter def user(self, user): """ Sets the user of this CoachingNotification. The user of this notification :param user: The user of this CoachingNotification. :type: UserReference """ self._user = user @property def appointment(self): """ Gets the appointment of this CoachingNotification. The appointment :return: The appointment of this CoachingNotification. :rtype: CoachingAppointmentResponse """ return self._appointment @appointment.setter def appointment(self, appointment): """ Sets the appointment of this CoachingNotification. The appointment :param appointment: The appointment of this CoachingNotification. :type: CoachingAppointmentResponse """ self._appointment = appointment @property def self_uri(self): """ Gets the self_uri of this CoachingNotification. The URI for this object :return: The self_uri of this CoachingNotification. :rtype: str """ return self._self_uri @self_uri.setter def self_uri(self, self_uri): """ Sets the self_uri of this CoachingNotification. The URI for this object :param self_uri: The self_uri of this CoachingNotification. :type: str """ self._self_uri = self_uri def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_json(self): """ Returns the model as raw JSON """ return json.dumps(sanitize_for_serialization(self.to_dict())) def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
StarcoderdataPython
8036757
<reponame>pabvald/instagram-caption-generator from evaluation import eval import json import argparse with open('examples/gts.json', 'r') as f: gts = json.load(f) with open('examples/res.json', 'r') as f: res = json.load(f) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Image Captioning Eval Tools') parser.add_argument('--gts_path',type=str,default='examples/gts.json') parser.add_argument('--res_path',type=str,default='examples/res.json') parser.add_argument('--save_spice', action='store_true') parser.add_argument('--save_path', type=str,default='output/test_spice.json') args = parser.parse_args() print(args) with open(args.gts_path, 'r') as f: gts = json.load(f) with open(args.res_path, 'r') as f: res = json.load(f) mp = eval(gts,res,args) print(mp)
StarcoderdataPython
1970808
<reponame>ssd04/ml-project-template import logging import os import sys import traceback from loguru import logger LOCAL_DEV = os.getenv("LOCAL_DEV") def log_exception(*args): """[Captures the fullstack trace of uncaught exceptions, and provides them in a structured format]""" if len(args) == 1: e = args[0] etype, value, tb = type(e), e, e.__traceback__ elif len(args) == 3: etype, value, tb = args else: logger.error( "Not able to log exception. Wrong number of arguments given. Should either receive 1 argument " "- an exception, or 3 arguments: exc type, exc value and traceback" ) return tb_parsed = [] for filename, lineno, func, text in traceback.extract_tb(tb): tb_parsed.append( {"filename": filename, "lineno": lineno, "func": func, "text": text} ) logger.error( str(value), exception=traceback.format_exception_only(etype, value)[0].strip(), traceback=tb_parsed, ) class InterceptHandler(logging.Handler): """ A class that allows loguru library to plug into the standard logging libarary. Provides a way for imported libaries to also use the loguru logger. Please refer to the loguru docs for more information Args: logging : the standard libary logging libary """ def emit(self, record): # Get corresponding Loguru level if it exists try: level = logger.level(record.levelname).name except ValueError: level = record.levelno # Find caller from where originated the logged message frame, depth = logging.currentframe(), 2 while frame.f_code.co_filename == logging.__file__: frame = frame.f_back depth += 1 logger.opt(depth=depth, exception=record.exc_info).log( level, record.getMessage() ) def setup_logger(): """ Setup the logger and return it. """ logger.remove() if LOCAL_DEV: logger.add(sys.stdout, serialize=False, level="DEBUG") logger.add("logs/debug.log", serialize=False, level="DEBUG") logger.add("logs/error.log", serialize=False, level="ERROR") else: logger.add(sys.stdout, serialize=True) logger.add("logs/debug.log", serialize=True, level="DEBUG") logger.add("logs/error.log", serialize=True, level="ERROR") # capture uncaught exceptions sys.excepthook = log_exception # set up loguru to work with the standard logging module logging.basicConfig(handlers=[InterceptHandler()], level=30)
StarcoderdataPython
4946923
from pyhanlp import * from pyhanlp.static import download, remove_file, HANLP_DATA_PATH import zipfile import os def test_data_path(): """ 获取测试数据路径,位于$root/data/test,根目录由配置文件指定。 :return: """ data_path = os.path.join(HANLP_DATA_PATH, 'test') if not os.path.isdir(data_path): os.mkdir(data_path) return data_path ## 验证是否存在 cnname 人名性别语料库,如果没有自动下载 def ensure_data(data_name, data_url): root_path = test_data_path() dest_path = os.path.join(root_path, data_name) if os.path.exists(dest_path): return dest_path if data_url.endswith('.zip'): dest_path += '.zip' download(data_url, dest_path) if data_url.endswith('.zip'): with zipfile.ZipFile(dest_path, "r") as archive: archive.extractall(root_path) remove_file(dest_path) dest_path = dest_path[:-len('.zip')] return dest_path ## =============================================== ## 以下开始中文分词 PerceptronNameGenderClassifier = JClass('com.hankcs.hanlp.model.perceptron.PerceptronNameGenderClassifier') cnname = ensure_data('cnname', 'http://file.hankcs.com/corpus/cnname.zip') TRAINING_SET = os.path.join(cnname, 'train.csv') TESTING_SET = os.path.join(cnname, 'test.csv') MODEL = cnname + ".bin" def run_classifier(averaged_perceptron): print('=====%s=====' % ('平均感知机算法' if averaged_perceptron else '朴素感知机算法')) # 感知机模型 classifier = PerceptronNameGenderClassifier() print('训练集准确率:', classifier.train(TRAINING_SET, 10, averaged_perceptron)) model = classifier.getModel() print('特征数量:', len(model.parameter)) # model.save(MODEL, model.featureMap.entrySet(), 0, True) # classifier = PerceptronNameGenderClassifier(MODEL) for name in "赵建军", "沈雁冰", "陆雪琪", "李冰冰": print('%s=%s' % (name, classifier.predict(name))) print('测试集准确率:', classifier.evaluate(TESTING_SET)) if __name__ == '__main__': run_classifier(False) run_classifier(True)
StarcoderdataPython