text
string
size
int64
token_count
int64
''' Constants used throughout pulsar. ''' from pulsar.utils.structures import AttributeDictionary # LOW LEVEL CONSTANTS - NO NEED TO CHANGE THOSE ########################### ACTOR_STATES = AttributeDictionary(INITIAL=0X0, INACTIVE=0X1, STARTING=0x2,...
2,030
694
# Author: Ovidiu Predescu # Date: July 2011 # # 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 ...
1,732
518
# Generated by Django 3.0.6 on 2020-06-14 05:26 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Color', fields=[ ...
5,590
1,668
import torch class GradReverse(torch.autograd.Function): @staticmethod def forward(ctx, x): return x.view_as(x) @staticmethod def backward(ctx, grad_output): return - grad_output class LambdaLayer(torch.nn.Module): def __init__(self, fn): super().__init__() self....
380
130
# Binary search of an item in a (sorted) list def binary_search(alist, item): first = 0 last = len(alist) - 1 found = False while first <= last and not found: middle = (first + last) // 2 if alist[middle] == item: found = True else: if item < alist[midd...
550
191
# ipop-project # Copyright 2016, University of Florida # # 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, m...
5,052
1,530
""" Annie Modified MIT License Copyright (c) 2019-present year Reece Dunham and the Annie Team 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 th...
3,879
1,246
# Generated by Django 3.1.3 on 2020-12-13 08:36 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('store', '0010_auto_20201212_2058'), ] operations = [ migrations.AddField( model_name='watch', name='slug', ...
427
152
# -*- encoding: utf-8 -*- import os import jinja2 import webapp2 from models.models import * from google.appengine.ext import blobstore from google.appengine.ext.webapp import blobstore_handlers from libs import mylib template_dir = os.path.join(os.path.dirname(__file__), 'views') jinja_env = jinja2.Environment (loade...
11,329
3,484
from .views import index from django.urls import path urlpatterns = [ path('', index, name='index'), ]
108
34
# Required to use access this directory as a "package." Could add more to this file later! # See http://docs.python.org/2/tutorial/modules.html#packages
154
44
from django import test as django_tests from django.contrib.auth import get_user_model from mytravelblog.accounts.forms import UserLoginForm, EditPasswordForm UserModel = get_user_model() class EditPasswordFromTests(django_tests.TestCase): def setUp(self): self.username = 'testuser' self.passwor...
937
275
""" Experiments with infix operator dispatch >>> kadd = KnowsAdd() >>> kadd + 1 (<KnowsAdd object>, 1) >>> kadd * 1 """ class KnowsAdd: def __add__(self, other): return self, other def __repr__(self): return '<{} object>'.format(type(self).__name__)
295
108
from django.contrib import admin from .models import Writer, Record admin.site.register(Writer) admin.site.register(Record)
125
36
from pykalman import KalmanFilter import numpy as np kf = KalmanFilter(transition_matrices=np.array([[1.0, 0.0, 0.0, 1.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 1.0, 0.0, 0.0, 1.0], ...
1,279
548
from api.models import Payroll class Payrolls(object): def __init__(self, cursor): """ :param cursor: MySQLdb.cursor.Cursor """ self.cursor = cursor cursor.execute('SET NAMES utf8;') cursor.execute('SET CHARACTER SET utf8;') cursor.execute('SET character_set...
1,935
545
# Python solution for 'Abbreviate a Two Word Name' codewars question. # Level: 8 kyu # Tags: FUNDAMENTALS, STRINGS, and ARRAYS. # Author: Jack Brokenshire # Date: 16/05/2020 import unittest def abbrev_name(name): """ Converts name of two words into initials. :param name: a string. :return: two capita...
929
346
import os import cv2 import random src_dir = "select2000/" name_idx = 6000 dest_img_dir = "scale/image/" dest_txt_dir = "scale/txt/" img_list = os.listdir(src_dir) def write_label(old_name, new_name, hratio_, wratio_): old_obj = open(src_dir+old_name) new_obj = open(dest_txt_dir+new_name, 'w') old_txt = ...
1,876
762
"""-------------------------------------------------------------------- COPYRIGHT 2014 Stanley Innovation Inc. Software License Agreement: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code m...
2,912
905
import logging import os from ruamel.yaml import YAML LOGGER = logging.getLogger('pussy') logging.basicConfig( level=logging.INFO, format="[%(asctime)s] %(levelname)s:%(name)s:%(message)s" ) CONFIG_PATH = os.path.join('./', 'config.yaml') LOGGER.info("Loading config: " + CONFIG_PATH) CONFIG = YAML(typ='safe').loa...
340
129
#!/usr/bin/python # -*- coding: utf-8 -*- from flask import jsonify def response_ok(value=None, message='', code=-1): result = { 'status': 1, 'message': message, 'code': code } if len(message) > 0: result['message'] = message if value is not None: result.update({'data': value}) return jsonify(result...
501
197
#!/usr/bin/env python # Copyright 2008-2015 Nokia Networks # Copyright 2016- Robot Framework Foundation # # 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...
3,344
1,156
#!/usr/bin/env python # -*- coding: utf-8 -*- """Provide the linear policy. The linear policy uses a linear parametric approximator to predict the action vector based on the state vector. """ from pyrobolearn.policies.policy import Policy from pyrobolearn.approximators import LinearApproximator __author__ = "Brian ...
3,074
846
def resolve(): ''' code here ''' N = int(input()) A_list = [int(item) for item in input().split()] hp = sum(A_list) #leaf is_slove = True res = 1 # root prev = 1 prev_add_num = 0 delete_cnt = 0 if hp > 2**N: is_slove = False elif A_list[0] == 1: i...
875
328
# -*- coding: utf-8 -*- import os import re import json import codecs import datetime import threading import urllib import urllib2 import string import random import BigWorld from constants import AUTH_REALM from gui.Scaleform.daapi.view.lobby.hangar.Hangar import Hangar from gui.battle_control import g_sessionProvi...
13,941
4,670
# Copyright (c) 2014 OpenStack Foundation # # 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 ...
19,118
5,856
# Copyright (c) 2016 Catalyst IT Ltd. # # 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 ...
3,497
1,063
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.13.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # + import gzip import numpy as np import...
3,126
1,333
import json import pandas as pd import random df = pd.read_csv("experiment\stimuli_creation\maze_lexemes.csv") states = ["California","Alabama","Alaska","Arizona","Arkansas","Connecticut","Colorado","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","Ma...
6,835
2,182
from pyfasta import Fasta def writebed(probelist, outbedfile): '''probe list format: chr\tstart\tend ''' outio = open(outbedfile, 'w') for pbnow in probelist: print(pbnow, file=outio) outio.close() def writefa(genomefile, bedfile, outfile): fastafile = Fasta(genomefile...
737
284
c = lambda n: n % 3 == 0 or n % 5 == 0 print(sum(filter(c, range(0, 1000))))
77
41
import rclpy from rclpy.action import ActionClient from rclpy.node import Node from action_tutorials_interfaces.action import Fibonacci class FibonacciActionClient(Node): def __init__(self): super().__init__('fibonacci_action_client') self._action_client = ActionClient(self, Fibonacci, 'fibonacc...
770
267
import ui def make_label(text, font, alignment, background_color, x, y): w, h = ui.measure_string(text, font=font, alignment=alignment, max_width=0) #print(w,h) label = ui.Label(text=text, font=font, alignment=alignment, background_color=background_color, f...
655
262
from web import app from glob import glob app.run( debug=True, host='0.0.0.0', port=5000, extra_files=glob('./web/templates/**.html') )
153
62
""" Django settings for addr project. Generated by 'django-admin startproject' using Django 1.11.29. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os f...
6,010
2,155
import getpass import os import platform import subprocess class Style: BLACK = '\033[30m' RED = '\033[31m' GREEN = '\033[32m' YELLOW = '\033[33m' BLUE = '\033[34m' MAGENTA = '\033[35m' CYAN = '\033[36m' WHITE = '\033[37m' UNDERLINE = '\033[4m' RESET = '\033[0m' BLUEBACKGRO...
1,243
497
from bs4 import BeautifulSoup import requests import pymongo from splinter import Browser from flask import Flask, render_template, redirect from flask_pymongo import PyMongo import pandas as pd def init_browser(): executable_path = {"executable_path": "chromedriver"} return Browser("chrome", **execu...
2,197
765
# ~ if project_type == 'script': # ~ with proyo.config_as(var_regex=r'# ---(.*?)--- #'): # ---gen_license_header('#')--- # # ~ # from argparse import ArgumentParser def main(): parser = ArgumentParser(description='{{description or tagline or ""}}') args = parser.parse_args() if __name__ == '__main__': m...
332
115
import logging import mysql.connector from get_sd_ou.config import Config logger = logging.getLogger('mainLogger') def init_db(host=None, user=None, password=None, port=None): logger.debug('[databaseUtil][init_db][IN]') cnx = mysql.connector.connect( host = host or Config.DATABASE_HOST, ...
5,435
1,876
import sys, os, os.path, re import codecs import numpy as np from scipy.sparse import * from scipy import * from sklearn.externals import joblib import networkx as nx django_path = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(13, django_path) os.environ['DJANGO_SETTINGS_MODULE'] = 'xxhh.settings' from d...
5,106
1,864
""" Tests the DQM Server class """ import json import os import threading import pytest import requests import qcfractal.interface as ptl from qcfractal import FractalServer, FractalSnowflake, FractalSnowflakeHandler from qcfractal.testing import ( await_true, find_open_port, pristine_loop, test_serv...
6,248
2,142
import lightpack, socket, configparser, os from time import sleep import sys class WLED_WiFi: def __init__(self): self.loadConfig() self.lp = lightpack.Lightpack() self.status = False try: self.lp.connect() except lightpack.CannotConnectError as e: pr...
2,278
731
import argparse import os import os.path as osp import cv2 import numpy as np from scipy.stats import multivariate_normal from scipy.stats import norm import matplotlib # matplotlib.use('agg') from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import subprocess import shutil import chainer from ch...
16,513
7,471
from tkinter import * root = Tk() canvas = Canvas(root, width=1000, height=1000, background="#FFFFFF") canvas.pack(expand=YES, fill=BOTH) def dot(x,y,size=1, color="#FF0000", outline=""): if size==1: canvas.create_line(x,y,x+1,y, fill=color, width=size) return canvas.create_ova...
1,290
660
from gurobipy import * from itertools import combinations from time import localtime, strftime, time import config from fibonew2 import ( AK2exp, InitMatNew, MatroidCompatible, Resol2m, bi, bs, disjoint, rankfinder, ib, sb) from timing import endlog, log def CheckOneAK(mbases,gset,rnk): ''' We check ...
7,034
2,336
import pandas as pd import numpy as np import random,time import math,copy from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeRegressor from sklearn.metrics import classification_report, confusion_matrix, accuracy_score from skle...
7,160
2,566
#!/usr/bin/env python import pytest import os import sys import logging logging.basicConfig() logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) from pathlib import Path from dselib.thread import initTLS initTLS() from constants import CONST from dselib.path import normalizePath from dselib.dir impo...
2,814
931
import gym from gym import error, spaces, utils from gym.utils import seeding import numpy as np import pandas as pd import gym from gym import error, spaces, utils from gym.utils import seeding from pilemma.env.dai_auct import Urn import glob import os import random init_dai=1000 init_eth=0 ACTION_SKIP = 0 ACTION_...
4,823
1,667
class Solution: def reverseWords(self, s: str) -> str: s = s.split(" ") s = [i for i in s if i != ""] return " ".join(s[::-1])
154
57
from haversine import haversine def loadOrder(fileName): print("Loading order from " + fileName + "...") order = [] # open the file with open(fileName) as infile: # read line by line for line in infile: # remove newline character from the end...
2,700
886
from xml.etree import ElementTree as ET import io import os.path import sys import gpxpy import builtins def find_all_tags(fp, tags, progress_callback=None): parser = ET.XMLPullParser(("start", "end")) root = None while True: chunk = fp.read(1024 * 1024) if not chunk: break ...
4,425
1,399
# utils/test_kronecker.py """Tests for rom_operator_inference.utils._kronecker.""" import pytest import numpy as np import rom_operator_inference as opinf # Index generation for fast self-product kronecker evaluation ================= def test_kron2c_indices(n_tests=100): """Test utils._kronecker.kron2c_indices...
9,628
3,949
# # GADANN - GPU Accelerated Deep Artificial Neural Network # # Copyright (C) 2014 Daniel Pineo (daniel@pineo.net) # # 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 restricti...
3,420
1,250
import sys sys.path.append( r"C:\Users\900157\Documents\Github\TrabalhosPython\Aula37" ) from Controller.squad_controller import SquadController from Model.squad import Squad squad = Squad() squad.nome = 'JooJ' squad.descricao = 'Intermediário' squad.npessoas = 20 squad.backend.nome = 'Lua' #Adicionar squad.b...
880
311
# -*- coding: utf-8 -*- from datetime import datetime, timedelta import pytz from restapi.rest.definition import EndpointResource from restapi.exceptions import RestApiException from restapi.connectors.authentication import HandleSecurity from restapi import decorators from restapi.confs import WRAP_RESPONSE from re...
5,427
1,478
# -*- coding: utf-8 -*- import redis import os import telebot import math import random import threading from telebot import types from emoji import emojize from pymongo import MongoClient token = os.environ['TELEGRAM_TOKEN'] bot = telebot.TeleBot(token) admins=[441399484] games={} client1=os.environ['database'] clie...
13,196
5,081
import math from abc import ABC, abstractmethod from enum import Enum from typing import Iterator class CollectibleType(Enum): Consumable = 1 Gate = 2 ActiveItem = 3 PassiveItem = 4 Pickup = 5 Qubit = 6 Multi = 0 # wraps multiple collectibles def type_str(c_type: CollectibleType) -> s...
2,317
696
from mesh.standard import * from scheme import * __all__ = ('Workflow',) Layout = Sequence(Structure({ 'title': Text(), 'view': Token(), 'elements': Sequence(Structure({ 'type': Token(nonempty=True), 'field': Token(nonempty=True), 'label': Text(), 'options': Field(), })...
2,952
825
# https://leetcode.com/problems/k-closest-points-to-origin/ # 973. K Closest Points to Origin # Medium # Share # Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0). # The distance between two points on the X-Y plane...
1,079
416
#!/usr/bin/env python # -*- coding:utf-8 -*- """ Time: 2021-10-13 8:30 下午 Author: huayang Subject: """ import os import sys import json import doctest from typing import * from collections import defaultdict from torch.nn import functional as F # noqa from huaytools.pytorch.modules.loss.mean_squared_error import...
1,232
513
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right # if root.left and root.right: # if v <= root.left.val or v >= root.right.val: return False # elif ...
866
266
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jul 1 12:48:08 2020 @author: smith """ import spacy from gensim.test.utils import common_texts, get_tmpfile from gensim.models import Word2Vec from gensim.models.phrases import Phrases, Phraser import os import multiprocessing import csv import re impo...
11,197
3,960
import setuptools __author__ = 'serena' try: import multiprocessing # noqa except ImportError: pass setuptools.setup( setup_requires=['pbr==2.0.0'], pbr=True)
180
73
import os import re import html import unidecode import torch HTML_CLEANER_REGEX = re.compile('<.*?>') def clean_html(text): """remove html div tags""" return re.sub(HTML_CLEANER_REGEX, ' ', text) def binarize_labels(labels, hard=True): """If hard, binarizes labels to values of 0 & 1. If soft thresholds...
3,406
1,110
""" Комбинации. Составьте программу combinations. ру, получающую из командной строки один аргумент n и выводящую все 2" комбинаций любого размера. Комбинация - это подмножество из п элементов, независимо от порядка. Например, когда п = 3, вы должны получить следующий вывод: а аЬ аЬс ас Ь ьс с Обратите внимание, чт...
659
268
# -*- coding: utf-8 -*- """ Created on Fri Jun 16 22:19:57 2017 @author: RaduGrig @inspiration: NikCleju """ # import stuff from keras.optimizers import Adam from keras.models import Sequential from keras.layers import Dense, Activation import numpy as np import matplotlib.pyplot as plot #Params DataPoints = 100 No...
2,445
1,054
from .opentok import OpenTok, Roles, MediaModes, ArchiveModes from .session import Session from .archives import Archive, ArchiveList, OutputModes from .exceptions import OpenTokException from .version import __version__
221
60
import abc import json import os from rubrik_config import helpers class RubrikConfigBase(abc.ABC): def __init__(self, path, rubrik, logger): self.path = path self.rubrik = rubrik self.logger = logger self.cluster_version = self.rubrik.cluster_version() self.cluster_name...
2,130
604
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 28 19:51:12 2018 @author: ozkan """ import pandas as pd import numpy as np #from sklearn.preprocessing import MinMaxScaler, LabelEncoder from scipy import stats import gc import GatherTables def one_hot_encoder(df): original_columns = list(df....
26,309
9,899
from .data_request_type import DataRequestType class DataRequest(): def __init__(self, fieldName, requestType): self.fieldName = fieldName self.requestType = requestType self.value = 0
216
61
# -*- coding: utf-8 -*- """ Sphinx configuration for nexson. Largely based on Jeet Sukumaran's conf.py in DendroPy. """ import sys import os import time from sphinx.ext import autodoc from nexson import __version__ as PROJECT_VERSION # -- Sphinx Hackery ------------------------------------------------ # Following ...
15,242
4,784
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import math # The PYTHONPATH should contain the location of moose.py and _moose.so # files. Putting ".." with the assumption that moose.py and _moose.so # has been generated in ${MOOSE_SOURCE_DIRECTORY}/pymoose/ (as default # pymoose build does) and this file i...
2,105
768
import copy import logging import os import ray from ray import tune from ray.rllib.agents import dqn from ray.rllib.agents.dqn.dqn_torch_policy import postprocess_nstep_and_prio from ray.rllib.utils import merge_dicts from ray.rllib.utils.schedules import PiecewiseSchedule from ray.tune.integration.wandb import Wandb...
31,420
11,560
from winrt.windows.media.control import GlobalSystemMediaTransportControlsSessionManager from winrt.windows.storage.streams import DataReader, Buffer, InputStreamOptions async def get_current_session(): """ current_session.try_play_async() current_session.try_pause_async() current_session.try_toggle_p...
1,370
400
""" Django settings for lawerWeb project. Generated by 'django-admin startproject' using Django 2.1.3. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os ...
4,001
1,478
from .kparam import Kparam from .variogram import Variogram from .utilities import predict
91
24
class hparams: sample_rate = 16000 n_fft = 1024 #fft_bins = n_fft // 2 + 1 num_mels = 80 hop_length = 256 win_length = 1024 fmin = 90 fmax = 7600 min_level_db = -100 ref_level_db = 20 seq_len_factor = 64 bits = 12 seq_len = seq_len_factor * hop_length d...
900
424
"""The HDHomeRun component.""" import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant import config_entries from homeassistant.const import CONF_PORT from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from .const import DOMAIN, CONF_HOST DEVICE_SCHEMA = vol....
1,338
449
# Material buttonType = ['Arrow button', 'Radio button', 'Switch button', 'Option'] requestLUT = [ { 'name' : 'Radio', 'on' : 'OSD_ImgFolder/radio_on.png', 'off' : 'OSD_ImgFolder/radio_off.png', 'default' : 'off', 'hint_path' : 'OSD_ImgFolder/L4 off.png', 'hint': 0 }, { 'nam...
2,542
1,259
import Dynamic_Network_Graph_Exploration_py3 as dynamic import Data_Cleaning as dc #import heatmap_functions as heatmap #import Member_Distribution as dist ''' So far the main method only includes dynamic network graph functions Heatmap_functions and Member_Distribution functions to be added ''' def ma...
2,142
680
from django.conf import settings from django_webtest import WebTest from evap.evaluation.models import Course from evap.evaluation.models import UserProfile from evap.rewards.models import SemesterActivation from evap.rewards.models import RewardPointRedemptionEvent from evap.rewards.tools import reward_points_of_user ...
6,606
1,889
from unittest import TestCase from ddipy.constants import MISSING_PARAMETER from ddipy.ddi_utils import BadRequest from ddipy.seo_client import SeoClient class TestSeoClient(TestCase): def test_seo_home(self): client = SeoClient() res = client.get_seo_home() assert len(res.graph) > 0 ...
1,416
473
import re from textwrap import indent import mistune from jinja2 import Template from .directives.injection import InjectionDirective from .directives.renvoi import RenvoiDirective from .directives.section import SectionDirective from .directives.question import QuestionDirective from .directives.toc import Directive...
3,900
1,245
from django.db import models from django.contrib.auth.models import User # Create your models here # All the departments departments = [('Cardiologist', 'Cardiologist'), ('Dermatologists', 'Dermatologists'), ('Emergency Medicine Specialists', 'Emergency Medicine Specialists'), ...
5,404
1,630
from datetime import datetime import pytest from intents import Sys from intents.connectors._experimental.snips import entities from intents.connectors._experimental.snips import prediction_format as pf def test_date_mapping_from_service(): mapping = entities.DateMapping() snips_date_result = { 'inpu...
2,008
728
import pytest from django.core.management import call_command @pytest.mark.django_db def test_common_runperiodic(): call_command('runperiodic')
150
48
from typing import List, Optional import pygame from OpenGL.GL import * from src.utils.drawing_utils import draw_texture, surface_to_texture class DropDown: def __init__(self, color_menu, color_option, x: int, y: int, width: int, height: int, font_name: str, font_size: int, main: str, options: ...
2,907
913
from air_conditioner import AirConditioner
43
11
import random OPTIONS = ['rock', 'paper', 'scissors'] def print_options(): """ This function prints game's options :return: """ print('(1) Rock\n(2) Paper\n(3) Scissors') def get_human_choice(): """ This function gets the choice of the human :return: """ human_choice_numb...
2,333
732
import inspect import itertools __all__ = ['NDArrayReprMixin'] class NDArrayReprMixin: def _name_params(self, ignore=()): name = type(self).__name__ sig = inspect.signature(type(self)) params = tuple(p for p in sig.parameters if p not in ignore) return name, params def _repr_...
899
307
#!/usr/bin/env python3 # # horizon.py - by Don Cross - 2019-12-18 # # Example Python program for Astronomy Engine: # https://github.com/cosinekitty/astronomy # # This is a more advanced example. It shows how to use coordinate # transforms and a binary search to find the two azimuths where the # ecli...
3,417
1,133
#!/opt/libreoffice5.2/program/python # -*- coding: utf-8 -*- # This name will be rdb file name, .components file name, oxt file name. BASE_NAME = "ProtocolHandlerAddonPython" # これがrdbファイル名、.componentsファイル名、oxtファイル名になる。 # a list of a dict of Python UNO Component Files: (file name,service implementation name, service ...
1,101
506
from collections import namedtuple import json, logging, socket, re, struct, time from typing import Tuple, Iterator from urllib.parse import urlparse, parse_qs from backend import Backend, Change from protocol import PacketType, recvall, PKT_CHANGE_TYPES, change_from_packet, packet_from_change, send_packet, recv_pack...
8,508
2,445
#!/usr/bin/env python # -*- coding: utf-8 -*- ################################################################################ # Copyright (c) 2019. Vincenzo Lomonaco, Karan Desai, Eugenio Culurciello, # # Davide Maltoni. All rights reserved. # # See the accompanying LICENSE...
7,564
2,427
"""8. String to Integer (atoi) Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. Notes: It is intended for this problem to be specified vaguely (ie, no given input sp...
1,029
328
database = "database" user = "postgres" password = "password" host = "localhost" port = "5432"
95
35
def mul(a, b): return a * b mul(3, 4) #12 def mul5(a): return mul(5,a) mul5(2) #10 def mul(a): def helper(b): return a * b return helper mul(5)(2) #10 def fun1(a): x = a * 3 def fun2(b): nonlocal x return b + x return fun2 test_fun = fun1(4) test_fun(7) #19
318
155
from ..factory import Method class setBotUpdatesStatus(Method): pending_update_count = None # type: "int32" error_message = None # type: "string"
152
53
""" This is an abbreviated version of my random number generator test suite. It uses the pytest framework. It does not do much in this form. """ import numpy as np import scipy.stats import random class TestRandoms( ): """ This is the main class. Normally it would hold all the tests, plus and setup and...
811
264
import pytest from unittest.mock import patch import vcf2cytosure def test_version_argument(): with patch('sys.argv', ['vcf2cytosure.py','--version']): with pytest.raises(SystemExit) as excinfo: vcf2cytosure.main() assert excinfo.value.code == 0
281
97