text
string
size
int64
token_count
int64
file_forgot_password = ["""<!DOCTYPE html> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <style type="text/css">...
30,598
10,529
import icalendar import urllib2 import hashlib import string import re import datetime from database import Database, TableHandler class Schedule(TableHandler): columns = [("Title", Database.C_TCN), "Description", ("Category", Database.C_TCN), ("Location", Database.C_TCN), ("StartDate", Database.C_D), ("EndDate", Dat...
2,106
786
############################################################################## # # Copyright (c) 2002 Zope Foundation and Contributors. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS I...
24,887
7,065
class TreeNode: def __init__(self, val, left=None, right=None): self.val = val self.right = right self.left = left class Solution: def searchBST(self, root, val): # if not root: # return None # if root.val == val: # return root ...
1,697
561
import subprocess import os import numpy as np import pandas as pd from datetime import datetime def store_relational_JH_data(): pd_raw = pd.read_csv('../data/raw/COVID-19/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv') pd_data_base = pd_raw.rename(columns={'Country/Re...
1,019
378
# Python 3 import sys import socketserver from http.server import SimpleHTTPRequestHandler class WasmHandler(SimpleHTTPRequestHandler): def __init__(self, *args, **kwargs): super().__init__(*args, directory="release/emscripten", **kwargs) def do_GET(self): if self.path == '/': self...
1,023
333
import pygame import sys import os from pygame.locals import * class Stage: # Set up the PyGame surface def __init__(self, caption, dimensions=None): pygame.init() # If no screen size is provided pick the first available mode if dimensions == None: dimensions = pygame.di...
1,850
542
from flask import Flask, request, jsonify, render_template_string import redis import requests import re import json import sys app = Flask(__name__) @app.route('/getid/<username>') def getid(username): red = redis.Redis(host="redis_users") return red.get(username).decode() @app.route('/useraction', methods...
2,596
855
import requests from bs4 import BeautifulSoup import json import pprint url = 'https://www.bcn.cl/siit/divisionelectoral/index.htm' res = requests.get(url) soup = BeautifulSoup(res.text, 'html.parser') rows = soup.find_all('tbody')[1].find_all('tr') region = "" circunscripcion = "" distrito = "" comuna = "" region...
1,195
508
#################################################### # (C) Mark Trimmer, 2016, All Rights Reserved # # File Name: app.py # # Creation Date: 28-12-2016 # # Created By: Mark Trimmer # # Purpose: # #################################################### from __future__ import print_function from credentialfile import Creden...
685
210
#!/usr/bin/env python from setuptools import setup, find_packages setup(name='classification-banner', version='1.0.0', description='Classification banner compatable with GTK3 and X11.', author='Mike May', author_email='mikemay@datamachines.io', url='https://www.github.com/datamachines/cl...
486
155
from synapyse.base.activation_functions.activation_function import ActivationFunction __author__ = 'Douglas Eric Fonseca Rodrigues' class Linear(ActivationFunction): def calculate_output(self): return self.x def calculate_derivative(self): return 1.0 def clone(self): clone = Lin...
371
110
#check description from bs4 import BeautifulSoup import lxml.html def check_description(tree): description = "" xpath_meta = "//meta[@name='description']/@content" xpath_og_property = "//meta[@property='og:description']/@content" xpath_og_name = "//meta[@name='og:description']/@content" meta_conte...
1,027
304
import re from backend.projectfiles.GenericProjectFile import GenericProjectFile QUOTE = r'(?:["|\'])' STRING = r'([\w\.\-\+]+)' GAV_REGEXP = QUOTE + '(?:' + ":".join([STRING, STRING, STRING]) + ')' + QUOTE class GradleProjectFile(GenericProjectFile): """ Gradle project file implementation to extract dependenc...
919
249
"""Example code for importing a single rigid body trajectory into Rhino from a Optitrack CSV file. Copyright (c) 2016, Garth Zeglin. All rights reserved. Licensed under the terms of the BSD 3-clause license as included in LICENSE. Example code for generating a path of Rhino 'planes' (e.g. coordinate frame) from a tr...
1,879
591
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This experiment was created using PsychoPy3 Experiment Builder (v2020.1.3), on 六月 15, 2020, at 09:02 If you publish work using this script the most relevant publication is: Peirce J, Gray JR, Simpson S, MacAskill M, Höchenberger R, Sogo H, Kastman E, Li...
91,180
29,514
from ...cg import asShape as pShape from ...common import requires as _requires from warnings import warn @_requires('geopandas') def to_df(df, geom_col='geometry', **kw): """ Convert a Geopandas dataframe into a normal pandas dataframe with a column containing PySAL shapes. Always returns a copy. Ar...
3,271
877
from django.urls import path from whitelist_api.views import AddTorrentInfoHash, RemoveTorrentInfoHash app_name = 'whitelist_api' urlpatterns = [ path('add-torrent-info-hash/', AddTorrentInfoHash.as_view()), path('del-torrent-info-hash/', RemoveTorrentInfoHash.as_view()), ]
287
105
# -*- coding:utf-8 -*- # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # This program is free software; you can redistribute it and/or modify # it under the terms of the MIT License. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the ...
1,847
609
from Stack import Stack def main(): stack = Stack() stack.push(0) stack.push(1) stack.push(2) stack.push(3) assert stack.data == [0, 1, 2, 3] assert stack.capacity == 4 assert stack.size == 4 popped = stack.pop() assert popped == 3 popped = stack.pop() assert popped =...
524
201
__version__ = '0.3.2' # noinspection PyUnresolvedReferences from ._cache._cache import cache # noinspection PyUnresolvedReferences from ._scheduler._scheduler import add_schedule, schedule, ScheduleSubscription
212
66
import numpy as np import pytest from pandas.core.frame import DataFrame from bender.importers import DataImporters from bender.model_loaders import ModelLoaders from bender.model_trainer.decision_tree import DecisionTreeClassifierTrainer from bender.split_strategies import SplitStrategies pytestmark = pytest.mark.as...
1,670
541
#!/usr/bin/env python3 # Goshu IRC Bot # written by Daniel Oaks <daniel@danieloaks.net> # licensed under the ISC license """extends several builtin functions and provides helper functions The default Python library is extensive and well-stocked. There are some times however, you wish a small task was taken care of for...
16,691
4,886
#!/usr/bin/env python2 # Copyright 2013-present Barefoot Networks, Inc. # SPDX-FileCopyrightText: 2018-present Open Networking Foundation # # SPDX-License-Identifier: Apache-2.0 import Queue import argparse import json import logging import os import re import subprocess import sys import threading import time from c...
8,707
2,763
from .snapshots import set_client from .snapshots import get_snapshots from .snapshots import tag_snapshot from .snapshots import set_drymode from .snapshots import unset_drymode
178
64
from flask_wtf import FlaskForm from wtforms import SubmitField, SelectField, IntegerField, FloatField, StringField from wtforms.validators import DataRequired import pandas as pd uniq_vals = pd.read_csv("data/unique_cat_vals.csv", index_col=0) class InputData(FlaskForm): car = SelectField(label="Car", choices=u...
1,184
359
#!usr/bin/env python3 color_chart = { '1C1':[13.24, 88.89, 228.98, 0.], '1N1':[14.2, 95.37, 233.82, 0.], '1N2':[12.95, 91.79, 219.5, 0.], '1W1':[14.67, 103.64, 229.41, 0.], '1W2':[14.69, 106.34, 227.28, 0.], '2C0':[15.73, 134.68, 222.32, 0.], '2C1':[14.57, 125.89, 220.69, 0.], '2C3':[13.7, 103.72, 199.4...
2,764
2,443
from typing import List class Solution: def findOcurrences(self, text: str, first: str, second: str) -> List[str]: ls = text.split() return [c for a, b, c in zip(ls, ls[1:], ls[2:]) if a == first and b == second]
235
82
import math from scipy.spatial.distance import euclidean from ..types.bbox import BoundingBox def is_left_of(bb1, bb2): _, _, bb1_max, _, _ = bb1 bb2_min, _, _, _, _ = bb2 return bb1_max < bb2_min def is_right_of(bb1, bb2): bb1_min, _, _, _, _ = bb1 _, _, bb2_max, _, _ = bb2 return bb1_min ...
454
215
import bayesian_irl import mdp_worlds import utils import mdp import numpy as np import scipy import random import generate_efficient_frontier from machine_replacement import generate_posterior_samples if __name__=="__main__": seed = 1234 np.random.seed(seed) scipy.random.seed(seed) random.seed(seed) ...
2,883
1,133
#!/usr/bin/env python3 # Copyright 2019 Benjamin Ehret, Maria Cervera # # 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 ...
5,982
1,983
from wordcloud2 import wordcloud as W import os from PIL import Image stwords = {"us", "will"} print("==Obama's==") cs = W.randomscheme() #:Set1_8 as_ = W.randomangles() #(0,90,45,-45) dens = 0.5 #not too high wca = W.wordcloud( W.processtext(open(W.pkgdir(W.WordCloud)+"/res/Barack Obama's First Inaugural Address...
2,490
949
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import itk import module_kits.itk_kit as itk_kit from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin class nbCurvesLevelSet(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, mo...
3,520
1,058
# # Copyright 2018-2019 Happineo # """setuptools installer for zamita.""" import os import uuid from setuptools import find_packages from setuptools import setup from setuptools.command.build_py import build_py # local imports from build_scripts.version import VersionInfo HERE = os.path.abspath(os.path.dirname(__fi...
2,835
928
""" Sep 21 -- A few of the plots used in analysis, very far from a complete list, and probably most are too specific to be useful again. Moved useful functions from here. """ from __future__ import annotations from typing import List, Callable, Optional, Union, TYPE_CHECKING import numpy as np from dat_analysis.anal...
4,724
1,306
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 10 23:54:16 2021 @author: rolandvarga """ import gym import numpy as np import matplotlib.pyplot as plt import time from scipy.signal import savgol_filter import pickle #%matplotlib qt #%matplotlib inline # Set to 1 to repeat SARSA learning (With...
9,980
3,403
from scipy.spatial.distance import cdist from numpy.linalg import eig, norm, pinv import matplotlib.pyplot as plt from PIL import Image import numpy as np import argparse import ntpath import glob import os parser = argparse.ArgumentParser() parser.add_argument("--option", type=str, default="PCA", ...
8,952
3,243
# -*- coding: utf-8 -*- """ Created on Fri Aug 9 15:33:47 2019 @author: Bogoclu """ import typing import multiprocessing as mp import warnings import numpy as np from scipy import stats from .space import FullSpace from duqo.proba import DS, MC, SUSE, ISPUD, FORM from duqo.doe.lhs import make_doe def _check_obj_w...
18,427
5,560
"""Parse json files.""" import json import re def search_for_key(final_key: str, tree: dict, space: list = []): """Search all data for a key. :param final_key: the key :param tree: the data :param space: found values :return: all found values """ if isinstance(tree, dict) and final_key in...
5,352
1,564
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-03-17 02:58 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import meet.models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ ...
2,795
812
#!/usr/bin/env python from setuptools import setup,find_packages version = '0.1' setup( name='pyfa_gpio', version=version, description='', author='Jason Pruitt', url='https://github.com/jrspruitt/pyfa_gpio', license='MIT', packages = find_packages(), )
284
103
import tensorflow as tf import numpy as np from dps.register import RegisterBank from dps.env import TensorFlowEnv from dps.utils import Param, Config def build_env(): return PathDiscovery() config = Config( build_env=build_env, curriculum=[ dict(shape=(2, 2), threshold=6), dict(shape=(...
4,093
1,519
# -*- coding: utf-8 -*- import requests class Query: '''Implements queries to the Github API using GraphQL ''' def __init__(self, token, max_page_size=100, min_page_size=5): self._token = token self._max_page_size = max_page_size self._min_page_size = min_page_size self.a...
14,812
3,101
from typing import List import matplotlib.pyplot as plt class Mortgage: """ A mortgage overview of the total burden (incl. interest) and the monthly fees per fixed period """ def __init__(self, mortgage_amount, burden, periods, monthly_fees, name): self.mortgage_amount = int(mortgage_amount)...
4,404
1,509
#!/usr/bin/env python # # Copyright 2018-2019 IBM Corp. 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 requ...
32,827
8,600
""" Module contains tests for the sim_client package """
57
16
"""A simple Google-style logging wrapper.""" import logging import time import traceback import os import sys import gflags as flags FLAGS = flags.FLAGS def format_message(record): try: record_message = "%s" % (record.msg % record.args) except TypeError: record_message = record.msg retu...
8,344
2,654
""" Python reference implementation of the Recurrent Neural Aligner. Author: Ivan Sorokin Based on the papers: - "Recurrent Neural Aligner: An Encoder-Decoder Neural Network Model for Sequence to Sequence Mapping" Hasim Sak, et al., 2017 - "Extending Recurrent Neural Aligner for Streaming End-to-End Speech Rec...
4,141
1,700
import unittest from typing import Any from coiny.core import CoinPrice, CoinyQueue, CoinySession, price_now_url, price_task from coiny.utils import NullCoinPrice class HasJson: def __init__(self, data) -> None: self.data = data async def __aenter__(self): return self async def __aexit_...
2,994
969
import unittest from simulator_diagnoser.graph import InmemoryGraph from simulator_diagnoser.graph.traversal import ForwardAnalysis class ForwardAnalysisTest(unittest.TestCase): def setUp(self): # Graph = # 9 # / | \ # 6 7 8 # \ / \ / # 4 5 #...
969
361
#!/usr/bin/python # -*- coding: utf-8 -*- ''' sonos-fadein-alarm.py - a gentle alarm using Sonos Favorites. This module allows a user to choose a SONOS favorite channel to play for a gentle alarm. Select the maximum desired volume, the number of minutes over which to ramp volume from 0 to the chosen maxium, and choose...
5,396
1,629
#!/usr/bin/env python import math import os import numpy as np import time import sys import copy import rospy import moveit_msgs.msg import geometry_msgs.msg import random import csv from sensor_msgs.msg import JointState from gazebo_msgs.msg import LinkStates from gazebo_msgs.msg import LinkState from std_msgs.msg i...
5,775
2,113
import collections import ctypes import elftools from elftools.common.utils import roundup, struct_parse from elftools.common.py3compat import bytes2str from elftools.construct import CString from ..context import context from ..log import getLogger from .datatypes import * from .elf import ELF from ..tubes.tube impo...
10,043
2,968
from __future__ import print_function import numpy as np import operator import os import sys if sys.version_info[0] >= 3: xrange = range def createDataSet(): group = np.array([[1.0,1.1], [1.0,1.0], [0,0], [0,0.1]]) labels = ['A', 'A', 'B', 'B'] return group, labels # kNN classifier de...
2,875
1,026
from simfin.tools import account class personal_taxes(account): ''' Classe permettant d'intégrer l'impôt des particuliers. ''' def set_align(self,pop,eco): earnings = pop.multiply(eco['emp']*eco['earn_c']+eco['taxinc'],fill_value=0.0) value = earnings.multiply(eco['personal_taxes'],fi...
642
241
# !!!!!!! This file is OBSOLETE. Its content has been absorbed into pilotController.py in the autopilot repository. # !!!!!!! Questions to Torre Wenaus. PandaSiteIDs = { 'AGLT2' : {'nickname':'AGLT2-condor','status':'OK'}, 'ALBERTA-LCG2' : {'nickname':'ALBERTA-LCG2-lcgce01-atlas-lcgpb...
16,094
6,856
class ScenarioError(Exception): pass class ScenarioTxError(ScenarioError): pass class TokenRegistrationError(ScenarioTxError): pass class ChannelError(ScenarioError): pass class TransferFailed(ScenarioError): pass class NodesUnreachableError(ScenarioError): pass class RESTAPIError(Sc...
513
162
#!/usr/bin/env python from pprint import pprint from matchmaker.database import * import sys def main(argv): if len(argv) == 1: return line = argv[1] if line[0] in '+-': line = line[1:] user, repos = line.split(":") user = int(user) repos = [int(r) for r in repos.split(",")] ...
1,002
361
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any...
3,862
1,090
from torchvision import datasets, transforms from torchvision.transforms import functional as TF from base import BaseDataLoader from six.moves import urllib from parse_config import ConfigParser # downloads import requests import json from collections import Counter import os import errno import csv import numpy as ...
6,654
2,035
from datetime import date from typing import List from stockscanner.model.asset.asset_type import AssetType from stockscanner.model.exceptions.exceptions import AssetNotFoundException from stockscanner.model.asset.asset import Asset from stockscanner.model.asset.cash import Cash from stockscanner.model.asset.debt impo...
5,855
1,947
#!/usr/bin/env python # # Copyright (C) 2017 import json import time from error_logger.url_rules import _base_url_rule # from error_logger.net import sms_notification, email_notification from error_logger.utils import generic class Report(_base_url_rule.BaseUrlRule): __url__ = '/report' __methods__ = ['POST...
2,478
680
# -*- coding: utf-8 -*- import click from .. import cli @cli.cli.command(hidden=True) def update(): """ Look for new version updates to CLI """ # TODO create update command click.echo('Sorry, command not programmed yet.')
246
80
import unittest import numpy as np import pandas as pd import mlsurvey as mls class TestData(unittest.TestCase): def test_to_dict_dict_should_be_set(self): """ :test : mlsurvey.model.Data.to_dict() :condition : x,y, y_pred data are filled. :main_result : the dictionary generated...
2,397
792
# encoding:utf-8 import requests import base64 import time ''' 通用文字识别 ''' request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic" access_token = '' # 百度AI的token access 详情请去看文档 request_url = request_url + "?access_token=" + access_token headers = {'content-type': 'application/x-www-form-urlencoded'} f...
1,126
445
from random import shuffle import numpy as np import torch import torch.nn as nn import math import torch.nn.functional as F import cv2 from matplotlib.colors import rgb_to_hsv, hsv_to_rgb from PIL import Image from .RepulsionLoss.my_repulsion_loss import repulsion def preprocess_input(image): image /= 255 ...
11,478
4,230
import os from django.core.wsgi import get_wsgi_application from rest_base.utils import dotenv os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') dotenv.load(os.path.join(os.path.dirname(__file__), '../.env')) application = get_wsgi_application()
267
95
from .context import CoCoDataset import os from torchvision import transforms import torch.utils.data as data from src.data_loader import get_loader from context import COCO_SMALL from context import clean_sentence def test_coco_dataset(): transform_train = transforms.Compose([ transforms.Resize(256), # ...
3,445
1,080
#!/usr/bin/env python3 # # Copyright 2021 Jay Logue # # 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 la...
5,019
1,577
#! /bin/python from flask import Flask app = Flask(__name__) @app.route('/') def hello(): return "Hello World! - v1" @app.route('/<name>') def hello_name(name): return "Hello {}! - v1".format(name) @app.route('/audio') def audio(): return "Audio - v1" @app.route('/video') def video(): return "Vi...
387
157
import collections import numpy as np from sklearn import utils from .. import base __all__ = ['KMeans'] def euclidean_distance(a, b): return sum((a.get(k, 0) - b.get(k, 0)) ** 2 for k in set([*a.keys(), *b.keys()])) class KMeans(base.Clusterer): """Incremental k-means. The most common way to imple...
4,374
1,294
from __future__ import print_function from __future__ import division from builtins import str from builtins import object __copyright__ = "Copyright 2015 Contributing Entities" __license__ = """ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with...
42,165
14,114
import numpy as np from stardist import star_dist, relabel_image_stardist import pytest from utils import random_image, real_image2d, check_similar, circle_image @pytest.mark.parametrize('img', (real_image2d()[1], random_image((128, 123)))) @pytest.mark.parametrize('n_rays', (4, 16, 32)) def test_types(img, n_rays): ...
2,686
1,173
import math import functools from scipy.stats import binom import numpy as np import itertools import sys import matplotlib.pyplot as plt import matplotlib.patheffects as PathEffects from copy import copy def combine_distribs(deletes, inserts): """ Combine insert and delete models/distributions :param de...
26,395
8,865
""" GUI tool to create a Bag from a filesystem folder. """ import sys import os import shutil import bagit import platform import random import string import re from time import strftime import subprocess from paramiko import SSHClient from paramiko import AutoAddPolicy from paramiko import AuthenticationException fro...
18,398
6,814
# -*- coding: utf-8 -*- ''' This module implements :class:`BaseSignal`, an array of signals. This is a parent class from which all signal objects inherit: :class:`AnalogSignal` and :class:`IrregularlySampledSignal` :class:`BaseSignal` inherits from :class:`quantities.Quantity`, which inherits from :class:`numpy.ar...
10,937
3,053
import sys sys.path.append("..") #this is to add the avobe folder to the package directory import geopandas as gpd import pandas as pd import numpy as np import os from nexustool.gis_tools import download_data, create_time_data, get_area_share, get_zonal_stats from nexustool.weap_tools import reproject_raster, sample_r...
3,038
1,171
from .file import FileGenerator from ..report.group import GroupReport import logging import asyncio import os class GroupGenerator(object): logger = logging.getLogger("ddvt.rep_gen.grp") def __init__(self, group): self.meta = group async def generate(self, parent): self.logger.info("Generating Group ...
891
303
# This is here for compatability purposes. Once all known OpenStack clients # are updated to use glanceclient.exc, this file should be removed from glanceclient.exc import *
174
43
from django.http import JsonResponse from rest_framework import status, viewsets from scpca_portal.models import Project class FilterOptionsViewSet(viewsets.ViewSet): def list(self, request): dicts = ( Project.objects.order_by() .values("diagnoses", "seq_units", "technologies", "m...
1,458
405
from .craigstrategy import CRAIGStrategy from .dataselectionstrategy import DataSelectionStrategy from .glisterstrategy import GLISTERStrategy from .randomstrategy import RandomStrategy from .submodularselectionstrategy import SubmodularSelectionStrategy from .gradmatchstrategy import GradMatchStrategy from .fixedweigh...
409
98
""" Metrics to calculate and manipulate the ROC Convex Hull on a classification task given scores. """ # Author: Tom Fawcett <tom.fawcett@gmail.com> from collections import namedtuple from math import sqrt from typing import List, Dict, Tuple, Union # DESCRIPTION: # # This program computes the convex hull of a set...
10,917
3,572
""" Program: DriveTesting.py Revised On: 12/01/2019 """ ### Library Imports from DriveArduino import DriveArduino import numpy as np from time import sleep from sys import exit from signal import signal, SIGINT ### ### CTRL + C Signal Handler & Resource Cleanup def signal_handler(sig, frame): """Handler for...
846
308
def truncatechars(value, arg): """ Truncates a string after a certain number of chars. Argument: Number of chars to truncate after. """ try: length = int(arg) except ValueError: # Invalid literal for int(). return value # Fail silently. if len(value) > length: retu...
363
105
import os import re from setuptools import find_packages, setup def get_version(package): path = os.path.join(os.path.dirname(__file__), package, "__init__.py") with open(path, "rb") as f: init_py = f.read().decode("utf-8") return re.search("__version__ = ['\"]([^'\"]+)['\"]", init_py).group(1) ...
817
279
import os import uuid from django.db import models from django.contrib.auth.models import User from django.db.models.base import Model from django.db.models.enums import Choices, ChoicesMeta from django.db.models.fields.related import ForeignKey from django.utils.deconstruct import deconstructible @deconstructible cl...
9,545
2,725
import re from collections import defaultdict with open('input/errors-ewts.csv') as f: raw = f.read() #raw = raw.replace('`not expected', '` not expected') lines = raw.split('\n') data = [] for line in lines: columns = re.split(r'(?:^"|","|",,"|"$)', line) msgs = [a for a in columns[3].split(',') i...
1,012
361
from django.shortcuts import render # Create your views here. from user.forms import UserForm def register(request): form = UserForm() if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): form.save() return render(request, 'user/registeration/register...
344
99
# -*- coding: utf-8 -*- import numpy as np import PIL import torch import torchvision.transforms as TF from types import SimpleNamespace from gym import spaces, Env from .SharkExampleEnv import CatchBallSimulate # internal_screen_h, internal_screen_w = 80, 140 class CatchBallEnvBase(Env): metadata = {'render.m...
3,609
1,224
#!/usr/bin/env python # -*- coding: utf-8 -*- '''Create a new tor node and add a simple http server to it, serving a given directory over http. The server is single-threaded and very limited. There are two arguments that can be passed via the commandline: -p\tThe internet-facing port the hidden service should list...
4,652
1,402
import os import json import threading import time import yaml from flask import Flask from flask import render_template from kubernetes.client.rest import ApiException from kubernetes.client.configuration import Configuration from kubernetes.config.incluster_config import load_incluster_config from kubernetes.clien...
5,123
1,467
import functools import time __all__ = ('ReachedMaxRetries', 'rever') class ReachedMaxRetries(Exception): def __init__(self, func): Exception.__init__(self, "Function {} raised exception due to max number of retries performed".format(func)) self.func = func def rever(**rever_kwargs): """ ...
3,417
955
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'gui.ui' # # Created by: PyQt5 UI code generator 5.6 # # WARNING! All changes made in this file will be lost! import os from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets imp...
25,811
9,165
from bs4 import BeautifulSoup import requests from IPython.core.display import display, HTML def get_soup(url): response = requests.get(url) page = response.text soup = BeautifulSoup(page, "lxml") return soup
226
69
''' rename_selected_relation_box.py Written by Alex Forsythe (awforsythe.com) When executed, attempts to locate any selected box within any relation constraint in the scene. If a selected relation box is found, prompts the user to enter a new name for that box. Allows relation boxes to be given more descriptive names....
1,912
555
import os import time import obspython as obs initial_load = False status_file = '' idle_scene = '' playing_scene = '' def undb(db): return pow(10, db/20) def script_description(): return 'Automatically switch scenes upon entering osu! gameplay.\n\n' \ 'See github page for setup instructions.\n\n...
4,010
1,303
''' file: donkey_env.py author: Tawn Kramer date: 2018-08-31 ''' import os from threading import Thread import numpy as np import gym from gym import error, spaces, utils from gym.utils import seeding from donkey_gym.envs.donkey_sim import DonkeyUnitySimContoller from donkey_gym.envs.donkey_proc import Do...
3,386
1,149
from tests.unit.backend.corpora.common.entities.datasets import TestDataset class TestDatasetRevision(TestDataset): def test__create_dataset_revision(self): dataset = self.generate_dataset_with_s3_resources(self.session, published=True) rev_dataset = dataset.create_revision("test_collection_id_rev...
2,403
646
""" ____ _____ _ _ _ | _ \ | __ \ (_) | | | | |_) |_ _ | |__) |_ _ _ __ _____| |__ _ _| |_ ___ | _ <| | | | | ___/ _` | '__|_ / | '_ \| | | | __/ _ \ | |_) | |_| | | | | (_| | | / /| | |_) | |_| | || __/ |____/ \__, | |_| ...
3,966
1,378
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-01-27 17:24 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('kawacon2016', '0002_auto_20160127_1922'), ] operations = [ migrations.AlterF...
707
288