text
string
size
int64
token_count
int64
from django.conf import settings from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class Article(models.Model): """ Models available articles """ name = models.CharField(max_length=200) serial_id = models.CharField(max_length=200)...
621
192
""" Prosumer class, extendes the battery controler """ import numpy as np from source.batterycontroller import BatteryController class Prosumer(BatteryController): def __init__(self, owner_id, b_max, b_min, eff_c, eff_d, d_max, d_min, price_buy, price_sell, load, expected_price_buy, expected_price_sell, updat...
5,925
2,007
#!/usr/bin/env python3 # Copyright (c) 2019 FRC Team 1678: Citrus Circuits import pytest import numpy as np import os, sys current_directory = os.path.dirname(os.path.realpath(__file__)) parent_directory = os.path.dirname(current_directory) grandparent_directory = os.path.dirname(parent_directory) sys.path.append(gran...
1,630
708
# Copyright [2015] Hewlett-Packard Development Company, L.P. # 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...
13,758
4,005
#! /usr/bin/python """ Enumerate selected locales and sort by codepage to determine which languages the locales support. """ # to disable the print statement and use the print() function (version 3 format) from __future__ import print_function import libastyle # local directory import locale import os imp...
3,814
1,075
""" 2015-07-23 Perform coordinate conversions from the command line. Uses """ import argparse import pyperclip # p1 = argparse.ArgumentParser() # p1.add_argument('x') # print p1.parse_args(['123']) # # p2 = argparse.ArgumentParser() # p2.add_argument('-d', action='store_const',const='dak') # print p2.p...
2,521
1,070
A, B = map(int, input().split()) print((A - 1) * (B - 1))
58
29
#! /usr/bin/env python # Version: 0.1.1 import re def convert_ws_header_vb_attributes(df): output_txt = "" for key in df.keys(): variant_array = "\'Dim " i = 0 for word in [w.capitalize().replace('\t', '') for w in str(key).lower().split("(")[0].split(" ")]: if i == 0: ...
774
260
import numpy as np import pandas as pd from sklearn.preprocessing import StandardScaler from sklearn.decomposition import IncrementalPCA as _IncrementalPCA from ..count_matrix.zarr import dataset_to_array def _normalize_per_cell(matrix, cell_sum): print('normalize per cell to CPM') if cell_sum is None: ...
6,979
2,051
from django.http import HttpResponse from django.shortcuts import render import operator def home(request): return render(request, 'home.html') def count(request): fulltext1=request.GET['fulltext1'] fulltext2=request.GET['fulltext2'] wordlist1=fulltext1.split(' ') wordlist2=fulltext2.sp...
1,051
366
# ============================================================================= # Python examples - modules # ============================================================================= # ----------------------------------------------------------------------------- # Module # ----------------------------------------...
3,137
744
#!/usr/bin/env python # # MIT License # # Copyright (c) 2021 silicon-village # # 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 # ...
5,010
1,577
# -*- coding: utf-8 -*- import os import sys import platform import glob from setuptools import setup, find_packages, Command if sys.version_info < (3, 6): print("Python 3.6 or higher required, please upgrade.") sys.exit(1) version = "0.1" name = "scholar_bot" description = ("Post updates on Slack about ci...
1,584
499
# Predict time series w/o using OutputProjectWrapper import tensorflow as tf import numpy as np import matplotlib.pyplot as plt # Create time series t_min, t_max = 0, 30 resolution = 0.1 def time_series(t): return t * np.sin(t) / 3 + 2 * np.sin(t * 5) def next_batch(batch_size, n_steps): t0 = np.random.rand...
3,226
1,379
import json import logging import os import random import time from functools import lru_cache from github import Github from github import PullRequest from pydocteur.github_api import get_commit_message_for_merge from pydocteur.github_api import get_trad_team_members from pydocteur.pr_status import is_already_greete...
5,536
1,876
import os from argparse import ArgumentParser from glob import glob import cv2 import numpy as np import torch import torchvision import matplotlib as mpl import matplotlib.pyplot as plt from PIL import Image from fiery.trainer import TrainingModule from fiery.utils.network import NormalizeInverse from fiery.utils.in...
5,172
1,839
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # filename: util.py import os import csv from copy import deepcopy import hashlib from functools import wraps from collections import OrderedDict from ._compat import json, JSONDecodeError from .exceptions import NoInstanceError, ImmutableTypeError, ReadonlyPropertyError ...
7,034
2,523
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Ed Mountjoy # """ bsub -q small -J interactive -n 1 -R "select[mem>8000] rusage[mem=8000] span[hosts=1]" -M8000 -Is bash """ import gzip import sys def main(): # Args in_ukb = '/nfs/users/nfs_e/em21/otcoregen/uk_biobank_data/data/phenotypes/tsv/ukb27852.tsv.g...
1,827
679
import asyncio import discord from discord.ext import commands, tasks import os import random import dotenv import difflib import configparser ### version = '4.0.0' ### bot = commands.Bot(command_prefix = '!', owner_id = 272446903940153345, intents = discord.Intents.all()) bot.remove_command('help') co...
6,088
1,877
import tensorflow as tf import numpy as np def euclidean_dist(x, y): return np.linalg.norm(x - y) def limit_gpu(): gpus = tf.config.list_physical_devices('GPU') if gpus: try: tf.config.set_logical_device_configuration( gpus[0], [tf.config.Logic...
565
190
from base import BaseDataSet, BaseDataLoader from utils import pallete import numpy as np import os import scipy import torch from PIL import Image import cv2 from torch.utils.data import Dataset from torchvision import transforms import json class VOCDataset(BaseDataSet): def __init__(self, **kwargs): sel...
2,226
780
# This process is the first step of a test that involves multiple # processing steps. It tests the thinning collections and # redirecting Refs, Ptrs, and RefToBases. # # Produce 15 thinned collections # # Collection A contains Things 0-8 # Collection B contains Things 0-3 and made from collection A # Collection C...
16,418
5,920
# coding: utf-8 from kerasy.Bio.tandem import find_tandem from kerasy.utils import generateSeq len_sequences = 1000 def get_test_data(): sequence = generateSeq(size=len_sequences, nucleic_acid='DNA', weights=None, seed=123) seque...
771
275
# >>> s = set("Hacker") # >>> print s.difference("Rank") # set(['c', 'r', 'e', 'H']) # >>> print s.difference(set(['R', 'a', 'n', 'k'])) # set(['c', 'r', 'e', 'H']) # >>> print s.difference(['R', 'a', 'n', 'k']) # set(['c', 'r', 'e', 'H']) # >>> print s.difference(enumerate(['R', 'a', 'n', 'k'])) # set(['a', 'c', 'r...
679
303
from PIL import Image, ImageDraw from numpy import array, random, vstack, ones, linalg from const import TOWERS from copy import deepcopy from os import path class MapDrawer: """ a class for drawing Dota2Maps with replay-parsed data """ def __init__(self, towers, received_tables): ...
4,898
1,647
import numpy as np import chainer.functions as F from chainer import Variable def neural_stack(V, s, d, u, v): # strengths s_new = d for t in reversed(xrange(s.shape[1])): x = s[:, t].reshape(-1, 1) - u s_new = F.concat((s_new, F.maximum(Variable(np.zeros_like(x.data)), x))) u = F....
1,746
771
from datetime import timedelta from celery.schedules import crontab, schedule CELERY_IMPORTS = ("chaos_genius.jobs") CELERY_TASK_RESULT_EXPIRES = 30 CELERY_TIMEZONE = "UTC" CELERY_ACCEPT_CONTENT = ["json", "msgpack", "yaml"] CELERY_TASK_SERIALIZER = "json" CELERY_RESULT_SERIALIZER = "json" CELERYBEAT_SCHEDULE = { ...
2,354
937
def get_tokenizer(tokenizer): if callable(tokenizer): return tokenizer if tokenizer == "spacy": try: import spacy spacy_en = spacy.load('en') return lambda s: [tok.text for tok in spacy_en.tokenizer(s)] except ImportError: print("Please in...
2,102
535
from servee import frontendadmin from servee.frontendadmin.insert import ModelInsert from oldcontrib.media.image.models import Image class ImageInsert(ModelInsert): model = Image frontendadmin.site.register_insert(ImageInsert)
232
62
from train import train from processing import Processing """ The Main run file, where the program execution and controller is based. """ class Run(train, Processing): def final_function(self): print('This project predicts the persons who will survive if the same RMS Titanic ') print('incident h...
974
260
#!/usr/bin/env python3 import os from shutil import copyfile def create_gdbinit_file(): """ Create and insert into a .gdbinit file the python code to set-up cbmc pretty-printers. """ print("Attempting to enable cbmc-specific pretty-printers.") home_folder = os.path.expanduser("~") if not ho...
2,646
855
# ====================================================================================== # # Module for solving maxent problem on C elegans data set. # # Author : Eddie Lee, edlee@santafe.edu # ====================================================================================== # from .utils import * from scipy.opti...
5,613
1,803
# Lint as: python3 # Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless ...
8,117
3,049
#第二次降采样使用的代码 import numpy as np import random # import sys import os from sklearn import preprocessing # import matplotlib.pyplot as plt # from mpl_toolkits.mplot3d import Axes3D # import math from scipy.stats import norm # from sklearn.neighbors import KernelDensity # import statistics # from scipy.stats i...
10,773
3,750
import torch import numpy as np import torch.nn as nn from torch.utils.data import Dataset, DataLoader def binary_reg(x: torch.Tensor): # forward: f(x) = (x>=0) # backward: f(x) = sigmoid a = torch.sigmoid(x) b = a.detach() c = (x.detach() >= 0).float() return a - b + c class HIN2vec(nn.Module...
3,630
1,412
import string from helpers import * class BoyerMoore(object): """ Encapsulates pattern and associated Boyer-Moore preprocessing. """ def __init__(self, pattern, alphabet=string.ascii_letters + string.whitespace + string.punctuation): self.pattern = pattern self.patternLen = len(pattern) ...
2,689
816
from basicts.archs.DGCRN_arch.DGCRN_arch import DGCRN
53
27
SECRET_KEY = None DB_HOST = "localhost" DB_NAME = "kido" DB_USERNAME = "kido" DB_PASSWORD = "kido" COMPRESSOR_DEBUG = False COMPRESSOR_OFFLINE_COMPRESS = True
159
66
#! /usr/bin/python3 from default_settings import default_settings from ultron_cli import UltronCLI if __name__ == '__main__': default_settings() try: UltronCLI().cmdloop() except KeyboardInterrupt: print("\nInterrupted by user.") print("Goodbye") exit(0)
301
96
import torch import torch.nn as nn import torch.nn.functional as F def soft_dice_score( output: torch.Tensor, target: torch.Tensor, smooth: float = 0.0, eps: float = 1e-7, dims=None) -> torch.Tensor: assert output.size() == target.size() if dims is not None: intersection = torch.sum(output * t...
2,689
894
import inspect import re from functools import update_wrapper from typing import Optional def is_interactive() -> bool: try: _ = get_ipython().__class__.__name__ # type: ignore return True except NameError: return False def get_attr_docstring(class_type, attr_name) -> Optional[str]:...
2,766
806
import torch def train_one_epoch(model, train_loader, loss_func, optimizer): model.train() running_loss = 0.0 for batch_idx, (x, y) in enumerate(train_loader): out = model(x) optimizer.zero_grad() loss = loss_func(out, y) loss.backward() optimizer.step() run...
2,492
812
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import json import uuid from typing import Callable, Mapping, Optional import numpy as np from caffe2.python import workspace from caffe2.python.predictor import predictor_exporter from .builtin_task import register_builtin_...
3,331
1,060
#!/usr/bin/env python import os import cv2 as cv import numpy as np from tests_common import NewOpenCVTests, unittest class cudaobjdetect_test(NewOpenCVTests): def setUp(self): super(cudaobjdetect_test, self).setUp() if not cv.cuda.getCudaEnabledDeviceCount(): self.skipTest("No CUDA-ca...
1,374
524
import logging import inspect import re from collections import OrderedDict from gremlinpy.gremlin import Gremlin, Param, AS from .entity import (_Entity, Vertex, Edge, GenericVertex, GenericEdge, ENTITY_MAP) from .exception import (AstronomerQueryException, AstronomerMapperException) from .traversal import Trav...
32,677
9,477
import pandas_ta as ta def clean(df, df_signal): df = df.join(df_signal) df.replace("", "NaN", inplace=True) df.dropna(inplace=True) df = df.reset_index(drop=True) df_signal = df['signal'] df.drop(columns=['volume', 'high', 'low', 'open', 'signal', "close_timestamp", "close_date"], inplace=True...
849
341
import sys class MenuHandler(object): def __init__(self, client, client_channel, remote_checker): self._client = client self._client_channel = client_channel self._buffer = '' self._remote_checker = remote_checker @staticmethod def create_from_channel(client, client_channe...
2,871
777
from django.conf.urls import include, url from django.contrib import admin import orderedtable from orderedtable import views app_name="orderedtable" urlpatterns = [ url(r'^$', views.home,name="home"), url(r'^import-json/$', views.import_json,name="import_json"), url(r'^project-list/$', views.project_lis...
563
195
def consolidate(sets): setlist = [s for s in sets if s] for i, s1 in enumerate(setlist): if s1: for s2 in setlist[i+1:]: intersection = s1.intersection(s2) if intersection: s2.update(s1) s1.clear() s1...
363
114
#!/usr/bin/env python3 # Calls Google Translate to produce translations. # To use, set "language" and "dest_language" below. (They are normally the same, # unless Google uses a different language code than we do.) Then fill in # the definition_[language] fields with "TRANSLATE" or # "TRANSLATE: [replacement definition...
2,242
818
""" Base classes and utilities for all Xena Manager (Xena) objects. :author: yoram@ignissoft.com """ import time import re import logging from collections import OrderedDict from trafficgenerator.tgn_utils import TgnError from trafficgenerator.tgn_object import TgnObject, TgnObjectsDict logger = logging.getLogger(_...
6,451
1,888
from ryu.base.app_manager import RyuApp from ryu.controller.ofp_event import EventOFPSwitchFeatures from ryu.controller.ofp_event import EventOFPPortDescStatsReply from ryu.controller.handler import set_ev_cls from ryu.controller.handler import CONFIG_DISPATCHER from ryu.controller.handler import MAIN_DISPATCHER from r...
2,051
701
class InterpreterException(Exception): def __init__(self, message): self.message = message def __str__(self): return self.message class SymbolNotFound(InterpreterException): pass class UnexpectedCharacter(InterpreterException): pass class ParserSyntaxError(InterpreterException): ...
508
141
# -*- coding: utf-8 -*- import unittest import os # noqa: F401 import json # noqa: F401 import time import shutil import re import sys import datetime import collections #import simplejson from os import environ try: from ConfigParser import ConfigParser # py2 except: from configparser import ConfigParser ...
21,812
5,797
# coding: utf-8 # In[1]: import numpy as np get_ipython().magic(u'matplotlib inline') from matplotlib import pyplot as plt from matplotlib.colors import LogNorm import sys sys.path.append('../../python/') from general_functions import load_5D_PDF_from_file from mpl_toolkits.mplot3d import Axes3D from matplotlib imp...
7,824
3,627
# Copyright (c) 2013 Stian Lode # # 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, distrib...
3,171
1,329
import httpx import pathlib import re import datetime from bs4 import BeautifulSoup root = pathlib.Path(__file__).parent.resolve() def formatGMTime(timestamp): UTC_FORMAT = '%Y-%m-%dT%H:%M:%SZ' timeStr = datetime.datetime.strptime(timestamp, UTC_FORMAT) + datetime.timedelta(hours=2, minutes=30) dateStr =...
3,912
1,266
import unittest # module for testing from models import news_article class TestNewsArticles(unittest.TestCase): ''' TestNewsArticles for testing class news_articles ''' def setUp(self): ''' Set up method to run before each test cases. ''' # id, title ,poster, url_link, d...
1,061
333
#! /usr/bin/env python3 import sys import random import os from faker import Factory as FFactory OUTFILE = "samples.xmi" NUM_SAMPLES = 10 NUM_COUNTRIES = 4 TEMPLATE = """<?xml version="1.0" encoding="ASCII"?> <person:Root xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:xsi="http://www.w3.org/...
2,216
787
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function __author__ = 'pygeostat development team' __date__ = '2020-01-04' __version__ = '1.0.0' import os, sys try: import pygeostat as gs except ImportError: sys.path.append(os.path.abspath(os.path.join(os....
977
333
import time import multiprocessing as mp import numpy as np from scipy.spatial.transform import Rotation from world import Earth class Rocket(object): def __init__(self, planet=Earth()): self.planet = planet self.propellant_mass = 1e6 self.dry_mass = 40e3 self.max_thrust = 2e5 *...
10,654
3,840
""" tcp_message Inline Script Hook API Demonstration ------------------------------------------------ * modifies packets containing "foo" to "bar" * prints various details for each packet. example cmdline invocation: mitmdump --rawtcp --tcp-host ".*" -s examples/complex/tcp_message.py """ from mitmproxy.utils import ...
868
254
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class NotebookConfig(AppConfig): name = "notes.notebook" verbose_name = _("Notebook")
186
58
from unittest import TestCase from unittest.mock import Mock, patch from typeseam.app import ( load_initial_data, ) class TestModels(TestCase): @patch('typeseam.app.os.environ.get') def test_load_initial_data(self, env_get): ctx = Mock(return_value=Mock( __exit__=Mock(), ...
409
133
import sys sys.path.append('../') from abc import ABCMeta, abstractmethod # https://www.python-course.eu/python3_abstract_classes.php import logging import oandapyV20 from oandapyV20 import API import oandapyV20.endpoints.orders as orders from oandapyV20.contrib.requests import MarketOrderRequest class...
2,090
618
#!/usr/bin/env python # -*- coding: utf-8 -*- # __BEGIN_LICENSE__ # Copyright (c) 2009-2013, United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The NGT platform is licensed under the Apache License, Version 2.0 (the # "Lic...
3,360
1,097
import cv2 import ProcessWithCV2 img1 = cv2.imread("D:/py/chinese/7.png") img2 = cv2.imread("D:/py/chinese/8.png") a = ProcessWithCV2.dHash(img1, img2, 1) print(a)
172
84
import pandas as pd import os MINIMAP_HEADERS = [ "Contig2", "Length2", "Start2", "End2", "Strand", "Contig1", "Length1", "Start1", "End1", "Nmatches", "Allength", "Quality", ] MINIMAP_DATATYPES = [str, int, int, int, str, str, int, int, int, int, int, int] assert len(...
3,782
1,347
# L. Лишняя буква # Васе очень нравятся задачи про строки, поэтому он придумал свою. # Есть 2 строки s и t, состоящие только из строчных букв. Строка # t получена перемешиванием букв строки s и добавлением 1 буквы в # случайную позицию. Нужно найти добавленную букву. # Формат ввода # На вход подаются строки s и t,...
961
387
from ._internal.frameworks.lightgbm import load from ._internal.frameworks.lightgbm import save from ._internal.frameworks.lightgbm import load_runner __all__ = ["load", "load_runner", "save"]
194
62
import ast from typing import List from flake8_plugin_utils import Visitor from .errors import UnnecessaryBackslashEscapingError class StringsVisitor(Visitor): lines: List[str] def _is_escaped_char(self, character: str) -> bool: repr_c = repr(character) return repr_c[1] == '\\' and repr_c[2...
723
249
#!/usr/bin/env python3.6 # -*- coding: utf-8 -*- import pytest from asyncio_hn import ClientHN @pytest.mark.asyncio async def test_last_n_posts(): async with ClientHN() as hn: posts = await hn.last_n_items(2) assert len(posts) == 2 @pytest.mark.asyncio async def test_download_posts(): asyn...
1,384
514
# -*- coding: utf-8 -*- import click import logging from pathlib import Path import pandas as pd import re import string from nltk.corpus import stopwords def brand_preprocess(row, trim_len=2): """ This function creates a brand name column by parsing out the product column of data. It trims the words based on tri...
5,649
1,912
import os import re import hyperparams as hp from data_load import DataLoad from tqdm import tqdm import numpy as np import pandas as pd import tensorflow as tf def load_ckpt_paths(model_name='cdmf'): # get ckpt ckpt_path = '../model_ckpt/compare/{}/'.format(model_name) fpaths = [] with open(ckpt_pat...
5,061
1,648
# Generated by Django 2.1 on 2018-08-14 09:42 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('substitute_finder', '0002_category'), ] operations = [ migrations.CreateModel( name='Product', ...
1,465
434
#! /usr/bin/env python # # parameters/standard.py # # Nick Barnes, Ravenbrook Limited, 2010-02-15 # Avi Persin, Revision 2016-01-06 """Parameters controlling the standard GISTEMP algorithm. Various parameters controlling each phase of the algorithm are collected and documented here. They appear here in approximately...
6,613
1,888
# Copyright 2014 Modelling, Simulation and Design Lab (MSDL) at # McGill University and the University of Antwerp (http://msdl.cs.mcgill.ca/) # # 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...
5,781
1,549
import networkx as nx import sys import os import nose sys.path.append(os.getcwd() + "/..") import utils class test_utils: def setUp(self): self.g0 = nx.Graph() self.g1 = nx.Graph() self.g2 = nx.Graph() self.g3 = nx.Graph() self.g4 = nx.Graph() self.g5 = nx.Graph() self.g7 = nx.Graph(...
3,223
1,439
import os import argparse import pytorch_lightning as pl from pytorch_lightning.callbacks import ( ModelCheckpoint, EarlyStopping, LearningRateMonitor, ) from pytorch_lightning.loggers import TensorBoardLogger from pytorch_lightning.utilities.seed import seed_everything from data.emnist import EMNISTDataMod...
2,184
777
# coding=utf-8 # Author: Rodolfo J. O. Soares <rodolfoj.soares@gmail.com> import numpy as np import re class KeelAttribute: """ A class that represent an attribute of keel dataset format. """ TYPE_REAL, TYPE_INTEGER, TYPE_NOMINAL = ("real", "integer", "nominal") def __init__(self, attribute_name...
6,681
2,026
#Rather than rely on inplicit inheritance from other classes, classes can just #call the functions from a class; termed composition class Other(object): def override(self): print "OTHER override()" def implicit(self): print "OTHER implicit()" def altered(self): print "OTHER alter...
830
245
#!/usr/bin/env python3 import os import re import sys import urllib.request # api_filename = "projects.md" api_filename = "groups.md" url = "https://gitlab.com/gitlab-org/gitlab-ce/raw/master/doc/api/" + api_filename doc_dir = "doc_tmp" if not os.path.exists(doc_dir): os.makedirs(doc_dir) filename, headers =...
2,333
792
#Copyright (c) 2009-11, Walter Bender, Tony Forster # This procedure is invoked when the user-definable block on the # "extras" palette is selected. # Usage: Import this code into a Python (user-definable) block; when # this code is run, the current mouse status will be pushed to the # FILO heap. If a mouse button ev...
997
334
#Constants POSITION_MAP = { # Remaining: F, IR, Util 0 : '0' # IR? , 1 : 'Center' , 2 : 'Left Wing' , 3 : 'Right Wing' , 4 : 'Defense' , 5 : 'Goalie' , 6 : '6' # Forward ? , 7 : '7' # Goalie, F (Goalie Bench?) , 8 : '8' # Goalie, F , 'Center': 1 , 'Left Wing'...
2,593
1,350
import os import pandas as pd import pytest import yaml import wandb run = wandb.init(project='RP_NVIDIA_Machine_Learning', job_type='data_validation') @pytest.fixture(scope='session') def data(): config_path = os.path.join(os.pardir, 'configs') with open(os.path.join(config_path, 'datav...
649
222
from abaqusConstants import * from .OdbPart import OdbPart from .OdbStep import OdbStep from .SectionCategory import SectionCategory from ..Amplitude.AmplitudeOdb import AmplitudeOdb from ..BeamSectionProfile.BeamSectionProfileOdb import BeamSectionProfileOdb from ..Filter.FilterOdb import FilterOdb from ..Material.Mat...
8,049
2,293
from django.conf.urls.defaults import patterns, url urlpatterns = patterns( 'popcorn_gallery.tutorials.views', url(r'^(?P<slug>[\w-]+)/$', 'object_detail', name='object_detail'), url(r'^$', 'object_list', name='object_list'), )
241
90
""" This test module has tests relating to kelvin model validations. All functions in /calculations/models_kelvin.py are tested here. The purposes are: - testing the meniscus shape determination function - testing the output of the kelvin equations - testing that the "function getter" is performing as exp...
3,738
1,201
import os from datetime import datetime import sys from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from jet_bridge_base import configuration from jet_bridge.configuration import JetBridgeConfiguration conf = JetBridgeConfiguration() configuration.set_configuration(conf) from jet_bridge_b...
2,231
670
from __future__ import unicode_literals from django.utils.translation import ugettext as _ from django.utils.translation import get_language as _get_language from modeltranslation.translator import translator, TranslationOptions from modeltranslation import utils from nsms.text.models import Text class TextTranslati...
690
185
can_juggle = True # The code below has problems. See if # you can fix them! #if can_juggle print("I can juggle!") #else print("I can't juggle.")
147
57
"""See pytools.prefork for this module's reason for being.""" import mpi4py.rc # pylint:disable=import-error mpi4py.rc.initialize = False from mpi4py.MPI import * # noqa pylint:disable=wildcard-import,wrong-import-position import pytools.prefork # pylint:disable=wrong-import-position pytools.prefork.enable_prefor...
703
237
''' Created on 2015/10/19 :author: hubo ''' from vlcp.server.module import Module, api from vlcp.event import TcpServer from vlcp.event.runnable import RoutineContainer from vlcp.event.connection import Client class TcpServerBase(Module): ''' Generic tcp server on specified URLs, vHosts are supported. '''...
6,096
1,573
from distutils.spawn import find_executable from os import path import click from .settings import ( BASE_DEVELOPMENT_REQUIREMENTS_FILENAME, BASE_REQUIREMENTS_FILENAME, DEVELOPMENT_REQUIREMENTS_FILENAME, REQUIREMENTS_FILENAME, ) from .util import print_and_run def _ensure_pip_tools_installed(): ...
1,571
579
# Copyright © 2020 Interplanetary Database Association e.V., # Planetmint and IPDB software contributors. # SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) # Code is Apache-2.0 and docs are CC-BY-4.0 from typing import List from planetmint_driver import Planetmint class Hosts: hostnames = [] connections...
1,135
374
"""BaiduSpider,爬取百度的利器 :Author: Sam Zhang :Licence: MIT :GitHub: https://github.com/samzhangjy :GitLab: https://gitlab.com/samzhangjy TODO: 完成文档 TODO: 添加更多爬虫 """ import json import os import re from html import unescape from pprint import pprint from urllib.parse import quote, urlparse import requests from bs4 impor...
24,737
9,161
import netCDF4 import numpy as np class CFOSAT(object): def extract(fname): try: init = netCDF4.Dataset(fname) except Exception: lats, lons, data_spd, data_dir, data_time, sate_name, res = [], [], [], [], "", "", "" return lats, lons, data_spd, data_dir, data_t...
1,200
408
""" Examples of using the functions in videotools.py to generate videos. This file will not run as-is - it is just intended to provide reference commands you might copy and edit. """ import os from videotools import * this_path = os.path.dirname(os.path.abspath(__file__)) input_path = os.path.join(this_path, "example...
17,228
4,742
from __future__ import absolute_import import pytest from qtpy import QtPrintSupport def test_qtprintsupport(): """Test the qtpy.QtPrintSupport namespace""" assert QtPrintSupport.QAbstractPrintDialog is not None assert QtPrintSupport.QPageSetupDialog is not None assert QtPrintSupport.QPrint...
615
181
from flask import Blueprint, flash, redirect, render_template, request, url_for from werkzeug.security import check_password_hash, generate_password_hash from flask_login import login_required, login_user, logout_user from logbook.models import User, db from peewee import fn auth = Blueprint("auth", __name__) ...
2,004
636