text
string
size
int64
token_count
int64
from snovault import ( AuditFailure, audit_checker, ) from .formatter import ( audit_link, path_to_text, ) def audit_contributor_institute(value, system): if value['status'] in ['deleted']: return need_inst = [] if 'corresponding_contributors' in value: for user in value['...
5,831
1,694
""" psatlib -- An imported library designed for PSAT running with Python scripts. Created by Zhijie Nie (nie@ieee.org) Created on: 06/11/2018 Last Modified on: 10/01/2018 """ __name__ = "psatlib" __version__ = "0.1" __author__ = "Zhijie Nie" __author_email__ = "nie@ieee.org" __copyright__ = "Copyright (c) 20...
5,990
2,229
import numpy as np import cv2 import math import datetime from datetime import timedelta as Delta h=300 w=300 cap = cv2.VideoCapture(0) SUN_LOC=(200,70) SUN_RSIZE=20 ORBITAL_R=10 def Orbiral(frame,Centerloc,orbit_r,size_r,phi,color): x_orbit=Centerloc[0]+int(orbit_r*np.cos(np.deg2rad(phi))...
3,001
1,385
# -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # """Tests for editor and outline explorer interaction.""" # Test library imports import pytest # Local imports from spyder.plugins.outlineexplorer.widgets import OutlineExplorerWidget from spyder.plugin...
2,913
940
from .helpers import FieldHolder, assert_or_raise class Attachment(metaclass=FieldHolder): """ representation of a Challonge match attachment """ _fields = ['id', 'match_id', 'user_id', 'description', 'url', 'original_file_name', 'created_at', 'updated_at', 'asset_file_name', 'as...
3,105
832
import pytest from cupy import array_api as xp @pytest.mark.parametrize( "obj, axis, expected", [ ([0, 0], -1, [0, 1]), ([0, 1, 0], -1, [1, 0, 2]), ([[0, 1], [1, 1]], 0, [[1, 0], [0, 1]]), ([[0, 1], [1, 1]], 1, [[1, 0], [0, 1]]), ], ) @pytest.mark.skipif( # https://git...
737
309
from typing import TYPE_CHECKING from drip.utils import json_list, json_object, raise_response if TYPE_CHECKING: from requests import Session class Subscribers: session: 'Session' @json_object('subscribers') def create_or_update_subscriber(self, email, marshall=True, **options): """ ...
6,406
1,865
from flask import Flask, request from flask_httpauth import HTTPBasicAuth from auth_handler import AuthHandler from cache import Cache from os import environ from yaml import safe_load import logging from connection_provider import ConnectionProvider # init logging logging.basicConfig(format='[%(asctime)s] [%(levelna...
2,154
690
#!/usr/bin/env python # coding: utf-8 # In[ ]: class Square_game(): display_col = (255, 255, 255) player_col = (0, 0, 0) text_col = (255, 0, 0) food_col = (0, 0, 255) maze_col = (50, 205, 55) dis_width = 400 dis_height = 400 square_block = 20 game_over = False game_close...
4,038
1,264
#!/usr/bin/env python """ Genetic algorithm class """ import random import operator import pymongo db_client=pymongo.MongoClient("223.195.37.85",27017) db=db_client["binaryCSA"] exp_col=db["experiments"] class GeneticAlgorithm(object): """Evolve a population iteratively to find better individuals on each gene...
7,255
2,210
import json import logging from typing import Tuple import requests from django.conf import settings from django.core.files.uploadedfile import InMemoryUploadedFile from django.views.generic import FormView, TemplateView from .forms import CodeSchoolForm logger = logging.getLogger(__name__) class IndexView(Templat...
2,867
941
""" The following classes are defined: AdderSubtractor4 AdderSubtractor8 AdderSubtractor16 """ from .. import wire from .. import gate from .. import signal from . import ADD Wire = wire.Wire Bus4 = wire.Bus4 Bus8 = wire.Bus8 Bus16 = wire.Bus16 class AdderSubtractor4: """Construct a new 4-bit adder-...
13,495
4,571
# Create your service here. __author__ = "Sanju Sci" __email__ = "sanju.sci9@gmail.com" __copyright__ = "Copyright 2019." from utils.commons import safe_invoke class NotificationManager(object): def __init__(self, *args, **kwargs): pass def notify(self, *args, **kwargs): pass @static...
680
222
from pathlib import Path import json import unittest from unittest.mock import MagicMock, patch from budget.config import Config import yaml class TestConfig(unittest.TestCase): def test_init(self): account_id = '012345678901' topic_arn = 'arn:aws:sns:us-east-1:123456789012:mystack-mytopic-NZJ5JSMVGFIE' ...
5,901
2,067
cubes=[value**3 for value in range(1,11)] print(cubes)
54
24
import random import numpy as np random.seed(1) np.random.seed(1) def test_composer_endpoint(client): case_id = 'scoring' history_json = client.get(f'api/composer/{case_id}').json nodes = history_json['nodes'] nodes_ids = [n['uid'] for n in nodes] edges = history_json['edges'] targets = [e[...
946
307
import cv2 import urllib import numpy as np import multiprocessing as mp stream = 'http://192.168.53.114:8000/streamLow.mjpg' stream2 = 'http://192.168.53.114:8001/streamLow.mjpg' def procImg(str, wind, stop): bytes = '' stream = urllib.urlopen(str) while not stop.is_set(): try: bytes...
1,447
498
import sys import re line = sys.stdin.readline().strip() commands = line.split() if len(commands) > 15: #Too Long print 'ERROR' exit(0) for i in range(0,len(line)): #Missing Spaces if i % 2 == 1 and line[i] != ' ': print 'ERROR' exit(0) for i in range(0,len(commands) - 2,2): #Repeated S...
901
354
from __future__ import absolute_import from __future__ import division from __future__ import print_function import cProfile import io import pstats cache = {} PROFILE_SWITCH = True class Profiler: def __init__(self): self.profiler = cProfile.Profile() def profile(self, func, *args, **kwargs): ...
1,293
404
class AImage(AShape): color: any def __init__(self, width=100, height=None, cx=None, cy=None, image='pet_darui_dog.png'): AShape.__init__(self, width, height, cx, cy) if image.startswith('http') self.pic = Image.open(io.BytesIO(requests.get(image).content)) else: ...
544
189
import aiohttp import aiohttp_jinja2 import pytest from ddtrace.contrib.aiohttp.middlewares import trace_app from ddtrace.contrib.aiohttp_jinja2.patch import patch as patch_jinja2 from ddtrace.internal.utils import version from ddtrace.pin import Pin from .app.web import setup_app if version.parse_version(aiohttp._...
1,898
666
import requests, json from bs4 import BeautifulSoup hds=[{'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'},\ {'User-Agent':'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.12 Safari/535.11'},\ {'User-Agent': 'Mozilla/5.0 (compa...
1,074
475
from flask_wtf import FlaskForm from wtforms import StringField, SubmitField, HiddenField,IntegerField from wtforms.validators import DataRequired, NumberRange class ConnectForm(FlaskForm): ''' The form for connecting to the Arduino ''' id = HiddenField('A hidden field'); serial_port = StringField...
1,323
384
from django.db.models.signals import post_save from django.dispatch import receiver from .models import User, EmailDevice @receiver(post_save, sender=User) def creating_user_settings(sender, instance, created, raw, **kwargs): """Creating the user device for a new User""" if created and not raw: EmailD...
421
119
# -*- coding: utf-8 -*- from casperlabs_client import CasperLabsClient, consts, reformat from casperlabs_client.commands.common_options import ( FROM_OPTION, CHAINNAME_OPTION, DEPENDENCIES_OPTION, TTL_MILLIS_OPTION, private_key_option, WAIT_PROCESSED_OPTION, TIMEOUT_SECONDS_OPTION, ALGOR...
2,969
953
for num in range(1,6): #code inside for loop if num == 4: continue #code inside for loop print(num) #code outside for loop print("continue statement executed on num = 4")
203
67
from django.views import View from django.shortcuts import render from services.models import Service, ServiceUser, MaterialUser from account.models import ContactUs from inv.settings import enable_otp from account.tasks import send_email from django.shortcuts import render, redirect from django.contrib import messages...
50,657
14,044
from role.role_state import RoleState from situations.situation_complex import SituationState, SituationStateData from situations.situation_job import SituationJob from situations.visiting.visiting_situation_common import VisitingNPCSituation import services import sims4.tuning.instances import sims4.tuning.tunable imp...
2,171
691
import pandas as pd import numpy as np import os import tensorflow as tf ####### STUDENTS FILL THIS OUT ###### #Question 3 def reduce_dimension_ndc(df, ndc_df): ''' df: pandas dataframe, input dataset ndc_df: pandas dataframe, drug code dataset used for mapping in generic names return: df: pand...
4,588
1,449
""" Build resume and cv from resume.md and cv.md """ import subprocess import os.path from jinja2 import Environment, FileSystemLoader from datetime import date def get_commit_hash(): out = subprocess.check_output('git show --oneline -s', shell=True) return out.decode('utf-8') .replace('\n', '').split(' ')[0]...
982
349
from datetime import datetime from setuptools import setup, find_packages DEPENDENCIES = [ 'requests', 'cryptography', ] EXCLUDED_PACKAGES = [ 'flask_example.py', ] setup( name='sns-message-validator', version='0.0.2+sunet', description='Validator for SNS messages.', author='https://githu...
511
197
''' This library is used to incorporate ''' import numpy as np def cell_prob_with_nucleus(cell, nucleus): ''' This function is used to figure out whether one region is cell or empty hole (without nucleus) :param cell: segmentations results with different labels :param nucleus: nucleus RawMemb image (...
907
275
from collections import namedtuple from typing import List from decimal import Decimal from sqlalchemy import select, func from wt.common import Money, Currency from wt.costs.expenditures import ExpenditureStatus from wt.ids import EntityId, EntityType from wt.provider.db import DbModel from wt.provider.db.tables imp...
5,677
1,686
# -*- coding: utf-8 -*- # # -------------------------------------------------------------------- # Copyright (c) 2022 Vlad Popovici <popovici@bioxlab.org> # # Licensed under the MIT License. See LICENSE file in root folder. # -------------------------------------------------------------------- # MASKS are single...
6,232
1,753
import calendar import datetime import re import sys from dateutil.relativedelta import relativedelta import gam from gam.var import * from gam import controlflow from gam import display from gam import gapi from gam import utils from gam.gapi.directory import orgunits as gapi_directory_orgunits def build(): re...
25,259
6,549
# WRITE YOUR SOLUTION HERE:
28
15
from tflyrics import Poet, LyricsGenerator artists = ['Bob Dylan', 'Tim Buckley', 'The Beatles'] gen = LyricsGenerator(artists, per_artist=5) ds = gen.as_dataset(batch_size=4) p = Poet() p.train_on(ds, n_epochs=10) poem = p.generate(start_string='Hey ', n_gen_chars=1000) print(poem)
286
126
# -*- coding: utf-8 -*- """ netvisor.schemas.companies.list ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2013-2016 by Fast Monkeys Oy. :license: MIT, see LICENSE for more details. """ from marshmallow import Schema, fields, post_load from ..fields import Boolean, List class CompanySchema(Schema):...
762
254
#!/usr/bin/env python2.7 import sys infiles = sys.argv[1:] data = [] genes = [] for i, fname in enumerate(infiles): sys.stderr.write(fname + '\n') d = [] with open(fname, 'rb') as ihandle: for j, line in enumerate(ihandle): g, c = line.strip().split() if i != 0 and g != gene...
608
219
from provider.base import BaseProvider class FacebookProvider(BaseProvider): def __init__(self, client_id, client_secret, name, redirect_uri, state=None): """ :param client_id: :param client_secret: :param name: :param redirect_uri: :param state: ...
1,372
402
import numpy as np from .image_transforms import mat_to_gray def rgb2hcv(Blue, Green, Red): """transform red green blue arrays to a color space Parameters ---------- Blue : np.array, size=(m,n) Blue band of satellite image Green : np.array, size=(m,n) Green band of satellite image...
14,757
6,270
import pandas as pd X_train = pd.read_csv("X_train.csv") df_y = pd.read_csv("y_train.csv") y_train = df_y["y"] X_test = pd.read_csv("X_test.csv")
148
70
import logging from flask import render_template, request, redirect, session, url_for, flash from flask.ext.restful import abort from flask_login import current_user, login_required from redash import models, settings from redash.wsgi import app from redash.utils import json_dumps @app.route('/embed/query/<query_id...
1,266
372
# -*- coding: utf-8 -*- """ Script to produce synthetic AIA data based on arbitrary model DEMs and test the results of the tempmap code against the model. Created on Mon Jul 28 16:34:28 2014 @author: Drew Leonard """ import numpy as np from matplotlib import use, rc use('agg') rc('savefig', bbox='tight', pad_inches=...
15,109
6,124
from unittest import TestCase import os class TestSet_up_logger(TestCase): def test_set_up_logger(self): from utils import set_up_logger from logging import Logger logger = set_up_logger("test", "test.log") self.assertIsInstance(logger, Logger) os.remove("test.log")
315
96
# the comments in this file were made while learning, as reminders # to RUN APP IN CMD PROMPT: cd to this directory, or place in default CMD directory: # then run 'python rubicon_reminders_cli.py' from os import listdir from datetime import datetime # this assigns dt variable as date + timestamp dt = (datetime.now()...
2,459
768
tournament_token_bytecode = "0x608060405233600360006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550611776806100546000396000f3006080604052600436106100fc576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806302d05d3f1...
12,213
9,197
import os from airflow import models, settings from airflow.contrib.auth.backends.password_auth import PasswordUser user = PasswordUser(models.User()) user.username = os.environ['AIRFLOW_UI_USER'] user.password = os.environ['AIRFLOW_UI_PASSWORD'] user.superuser = True session = settings.Session() session.add(user) s...
352
111
def get_remain(cpf: str, start: int, upto: int) -> int: total = 0 for count, num in enumerate(cpf[:upto]): try: total += int(num) * (start - count) except ValueError: return None remain = (total * 10) % 11 remain = remain if remain != 10 else 0 ...
909
362
""" generic functions """ from yaml import load def reduce_output(func, item, *args, **kwargs): """ simple function to reduce output from existing functions if func returns an iterable - just return item """ def inner_func(*args, **kwargs): return func(*args, **kwargs)[item] return inn...
535
161
import json from app.event import Event from app.responder import send_ok_response from app.utils import get_logger # Setup logging logger = get_logger("app") def run(event: Event): logger.info(event.http_path()) logger.info(event.http_method()) return send_ok_response(json.dumps({ 'message': 'H...
334
108
from arm.logicnode.arm_nodes import * class SetLocationNode(ArmLogicTreeNode): """Use to set the location of an object.""" bl_idname = 'LNSetLocationNode' bl_label = 'Set Object Location' arm_version = 1 def init(self, context): super(SetLocationNode, self).init(context) self.add_i...
592
185
from .enums import * from .utils import * from .exceptions import * import logging import requests import urllib logger = logging.getLogger(__name__) VALID_PERF_TYPES = [_.value for _ in PerfType] class Client: def __init__(self, token=None): self.url = "https://lichess.org/" self.s = requests.S...
32,756
8,934
""" ${NAME} """ from __future__ import absolute_import, division, print_function, unicode_literals import logging import time import weakref from PySide import QtGui from mcedit2.widgets.layout import Column log = logging.getLogger(__name__) class InfoPanel(QtGui.QWidget): def __init__(self, attrs, signals...
2,273
612
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # # MDAnalysis --- https://www.mdanalysis.org # Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors # (see the file AUTHORS for the full list of names) # # Released under t...
2,925
1,001
__source__ = 'https://leetcode.com/problems/palindrome-permutation/' # https://github.com/kamyu104/LeetCode/blob/master/Python/palindrome-permutation.py # Time: O(n) # Space: O(1) # # Description: Leetcode # 266. Palindrome Permutation # # Given a string, determine if a permutation of the string could form a palindrom...
4,536
1,459
""" To calculate the verification accuracy of LFW dataset """ # MIT License # # Copyright (c) 2018 Jimmy Chiang # # 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, includi...
2,398
846
# ------------------------------------------------------------------------------ # Program: The LDAR Simulator (LDAR-Sim) # File: LDAR-Sim main # Purpose: Interface for parameterizing and running LDAR-Sim. # # Copyright (C) 2018-2021 Intelligent Methane Monitoring and Management System (IM3S) Group # # ...
5,032
1,473
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np from sympy import Symbol, solve from sympy.abc import a, b, c from fit_beta import fit_beta_mean_uncertainty, kl_dirichlet RESULTS_FILE = "../results/results_beta_exp.csv" FILTER_BY = "range" results = pd.read_csv(RESULTS_FILE...
3,037
1,264
import logging import threading import typing import HABApp from HABApp.core.events.habapp_events import HABAppException from ._rest_patcher import RestPatcher log = logging.getLogger('HABApp.Tests') LOCK = threading.Lock() class TestResult: def __init__(self): self.run = 0 self.io = 0 ...
5,977
1,886
from airflow.models import DAG from airflow.utils.dates import days_ago from airflow.operators.python_operator import PythonOperator from datetime import datetime import pandas as pd import urllib import random import cx_Oracle import pyodbc import sqlalchemy args={ 'owner': 'BI', ### start date is used to for t...
1,948
693
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2019 Fetch.AI 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 ...
10,674
2,929
# -*- test-case-name: go.vumitools.tests.test_metrics_worker -*- from twisted.internet.defer import inlineCallbacks, returnValue from twisted.internet.task import LoopingCall from vumi import log from vumi.worker import BaseWorker from vumi.config import ConfigInt, ConfigError from vumi.persist.model import Manager ...
5,930
1,714
import warnings warnings.filterwarnings('ignore') # noqa from os.path import join, isfile, isdir import zipfile import torch from torchvision import models import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader, Subset, ConcatDataset from torchvision.transforms import (Compose, ...
6,434
1,937
import scrapy import pandas as pd import time import random import string import os class QuotesSpider(scrapy.Spider): name = "amazonspione" def start_requests(self): os.mkdir("./products") list_of_urls = [] link_file = "./names.csv" df1 = pd.read_csv(link_file) length...
1,558
492
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
2,407
651
import os import time from trousse.dataset import Dataset df_sani_dir = os.path.join( "/home/lorenzo-hk3lab/WorkspaceHK3Lab/", "smvet", "data", "Sani_15300_anonym.csv", ) metadata_cols = ( "GROUPS TAG DATA_SCHEDA NOME ID_SCHEDA COMUNE PROV MONTH YEAR BREED" " SEX AGE SEXUAL STATUS BODYWEIGHT ...
1,008
468
import sys from os.path import exists from unittest.mock import patch import numpy as np # type: ignore import pytest from despace.spatial_sort import SortND sys.path.append("..") coords_1d = np.array([1.0, 0.1, 1.5, -0.3, 0.0]) sorted_coords_1d = np.array([-0.3, 0.0, 0.1, 1.0, 1.5]) coords_2d = np.array( [[1...
3,303
1,566
""" Author: Jay Lago, SDSU, 2021 """ import tensorflow as tf import pickle import datetime as dt import os import sys sys.path.insert(0, '../../') import HDMD as dl import LossDLDMD as lf import Data as dat import Training as tr # ===========================================================================...
5,517
1,929
import json def is_valid(smc_type): # checks if smc_type is valid if smc_type == 'vmt': return True elif smc_type == 'flt': return True elif smc_type == 'nfl': return True else: return False def parse_vmt(contract): try: contract.get('value') cont...
1,542
495
class Student: def __init__(self, name, hours, qpoints): self.name = name self.hours = float(hours) self.qpoints = float(qpoints) def get_name(self): return self.name def get_hours(self): return self.hours def get_qpoints(self): return self.qpoints ...
1,332
412
#a script to run several replicates of several treatments locally #You should create a directory for your result files and run this script from within that directory seeds = range(21, 41) verts = [0.3] h_mut_rate = [0.1, 0.5, 1.0] import subprocess def cmd(command): '''This wait causes all executions to run in s...
1,292
439
class Solution: def firstUniqChar(self, s): table = {} for ele in s: table[ele] = table.get(ele, 0) + 1 # for i in range(len(s)): # if table[s[i]] == 1: # return i for ele in s: if table[ele] == 1: return s.index(ele...
499
180
from hamcrest import * from nose.tools import eq_ from mc import List, Some, Nothing,add def test_list_map(): eq_(List([1, 2, 3]).map(lambda x: x * 2), [2, 4, 6]) def test_list_flat_map(): eq_(List([1, 3]).flat_map(lambda x: (x * 2, x * 4)), [2, 4, 6, 12]) def test_list_filter(): eq_(List([1, 2, 3]).f...
2,897
1,278
import sys import re import os import commands HOST = 'grok.zope.org' RELEASEINFOPATH = '/var/www/html/grok/releaseinfo' def _upload_gtk_versions(packageroot, version): # Create the releaseinfo directory for this version. cmd = 'ssh %s "mkdir %s/%s"' % (HOST, RELEASEINFOPATH, version) print(cmd + '\n') ...
1,087
372
# Generated by Django 3.1 on 2020-12-25 15:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('obywatele', '0019_auto_20201225_1621'), ] operations = [ migrations.AlterField( model_name='uzytkownik', name='busines...
3,720
1,125
#program to compute and print sum of two given integers (more than or equal to zero). # If given integers or the sum have more than 80 digits, print "overflow". print("Input first integer:") x = int(input()) print("Input second integer:") y = int(input()) if x >= 10 ** 80 or y >= 10 ** 80 or x + y >= 10 ** 80: pri...
386
130
""" Selfium CLI Tools ~~~~~~~~~~~~~~~~~~~ All cli functions used in Selfium project; :copyright: (c) 2021 - Caillou and ZeusHay; :license: MIT, see LICENSE for more details. """ from .logo import * from .clear import * from .welcome import * from .tokenError import *
270
96
import uuid from datetime import datetime, timedelta from controllers import zfsController import jwt import pam import render JWT_SECRET = "7wXJ4kxCRWJpMQNqRVTVR3Qbc" JWT_ALGORITHM = "HS256" JWT_EXP_DELTA_SECONDS = 4300 async def index(request): return render.json({'error': 'nothing to see here...'}, 200) as...
5,136
1,575
import torch.nn as nn import torch import torchvision from utils.image_filter_utils import get_dog_image_filter, conv2d_output_shape from utils.writer_singleton import WriterSingleton class Retina(nn.Module): STEP = 0 @staticmethod def get_default_config(): config = { 'f_size': 7, 'f_sigma': 2...
2,888
996
from typing import Callable, Dict, Type def register_action(action: str, mapping_name: str = '__actions__'): # https://stackoverflow.com/questions/3589311/get-defining-class-of-unbound-method-object-in-python-3/25959545#25959545 class RegistryHandler: def __init__(self, fn: Callable): se...
790
251
#!/usr/bin/env python # -*- coding: utf-8 -*- # @copyright &copy; 2010 - 2021, Fraunhofer-Gesellschaft zur Foerderung der # angewandten Forschung e.V. All rights reserved. # # BSD 3-Clause License # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the fol...
5,154
1,765
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, DateTime, Sequence Base = declarative_base() class Subscription(Base): __tablename__ = 'subscriptions' id = Column(Integer, Sequence('subscription_id_seq'), primary_key=True) sr_id = Column(...
539
172
#!/usr/bin/env python # Motherstarter setup file from setuptools import setup, find_packages from motherstarter import __version__, __author__ # Open and read README file with open("README.md", "r", encoding="utf-8") as f: README = f.read() # Setup requirements to be installed requirements = [] with open("requi...
1,352
417
""" test_dynamic_bucket_resharding - Test resharding operations on bucket Usage: test_dynamic_bucket_resharding.py -c <input_yaml> <input_yaml> Note: any one of these yamls can be used test_manual_resharding.yaml test_dynamic_resharding.yaml Operation: Create user Perform IOs in specific bucket ...
8,006
2,547
import graphene from typing import cast from graphene_django import DjangoObjectType from graphene_django.debug import DjangoDebug from django.contrib.auth import get_user_model import devind_dictionaries.schema class UserType(DjangoObjectType): class Meta: model = get_user_model() fields = ('...
690
216
import numpy as np def main(): from fuzzi.evaluation import pate_train from fuzzi.generated import pate_label predictions = pate_label.outputs truth = [x[-1] for x in pate_label.db_test] print(predictions) print(truth) print('PATE accuracy = %f' % (np.mean(predictions == truth)))
311
107
import os import webapp2 import jinja2 import config from app.utils.compressor import WEBASSETS_ENV JINJA_ENV = jinja2.Environment( autoescape=lambda x: True, extensions=['jinja2.ext.autoescape', 'webassets.ext.jinja2.AssetsExtension'], loader=jinja2.FileSystemLoader( os.path.joi...
462
174
# Crie um programa que leia nome, sexo e idade de várias pessoas, guardando os dados # de cada pessoa em um dicionário e todos os dicionários em uma lista. No final, mostre: # A) Quantas pessoas foram cadastradas B) A média de idade C) Uma lista com as mulheres # D) Uma lista de pessoas com idade acima da média dados ...
1,479
544
import argparse import os import re import urllib.parse import requests from bs4 import BeautifulSoup from pushbullet import Pushbullet pushbullet = None def download_file(url, dir): local_filename = dir + '/' + urllib.parse.unquote_plus(url.split('/')[-1], encoding='iso-8859-1') if os.path.exists(local_fil...
3,794
1,194
import random from multiagent.scenarios.commons import * from multiagent.scenarios.simple_spread import Scenario as S class Scenario(S): def make_world(self): world = World() # set any world properties first world.dim_c = 2 num_agents = 3 num_landmarks = 3 world.col...
1,404
437
from __future__ import absolute_import, unicode_literals import os import subprocess import pytest from virtualenv.discovery.py_info import PythonInfo from virtualenv.run import run_via_cli from virtualenv.util.path import Path from virtualenv.util.subprocess import Popen CURRENT = PythonInfo.current_system() CREAT...
1,961
654
# coding: utf-8 import inspect def type_name(value): """ Returns a user-readable name for the type of an object :param value: A value to get the type name of :return: A unicode string of the object's type name """ if inspect.isclass(value): cls = value else: ...
481
158
{ "targets": [ { "target_name": "allofw", "include_dirs": [ "<!@(pkg-config liballofw --cflags-only-I | sed s/-I//g)", "<!(node -e \"require('nan')\")" ], "libraries": [ "<!@(pkg-config liballofw --libs)", "<!@(pkg-config glew --libs)", ], "cflag...
959
379
#!/usr/bin/env python # -*- coding:utf-8 -*- """================================================================= @Project : Algorithm_YuweiYin/LeetCode-All-Solution/Python3 @File : LC-0388-Longest-Absolute-File-Path.py @Author : [YuweiYin](https://github.com/YuweiYin) @Date : 2022-04-20 ========================...
5,237
1,699
#!/usr/bin/env python3 import copy import hashlib import logging import os import random import re import subprocess import sys import tempfile import time from multiprocessing import Pool from pathlib import Path from typing import Any, Dict, Optional, cast import requests import bisector import builder import chec...
44,876
14,525
import os import sys import warnings warnings.warn( "pathod and pathoc modules are deprecated, see https://github.com/mitmproxy/mitmproxy/issues/4273", DeprecationWarning, stacklevel=2 ) def print_tool_deprecation_message(): print("####", file=sys.stderr) print(f"### {os.path.basename(sys.argv[0...
585
202
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import os import logging from fnmatch import fnmatch import mutagen from mutagen.easyid3 import EasyID3 import urchin.fs.default import urchin.fs.json import urchin.fs.plugin import urchin.fs.mp3 MP3_GLOB = "*.mp3" class Plugin(ur...
1,321
446
import unittest from model.curseur import Curseur from model.pion import PionBlanc, PionNoir from model.qubic import Qubic class TestQubic(unittest.TestCase): def test_poser(self): q = Qubic() q.poser((0, 7, 0)) self.assertTrue(q.get_pion((0, 0, 0)) == PionBlanc) self.assertFalse(q.get_pion((0, 1, 0))) q....
2,449
1,291
from typing import Any, Dict, Type, TypeVar, Union import attr from ..models.sherpa_job_bean import SherpaJobBean from ..types import UNSET, Unset T = TypeVar("T", bound="ProjectStatus") @attr.s(auto_attribs=True) class ProjectStatus: """ """ project_name: str status: str pending_job: Union[Unset,...
1,536
488