id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
312542
<gh_stars>0 # Copyright AllSeen Alliance. All rights reserved. # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AN...
StarcoderdataPython
8072659
import pytest from tri_declarative import ( class_shortcut, evaluate, evaluate_recursive, evaluate_recursive_strict, evaluate_strict, filter_show_recursive, matches, Namespace, remove_show_recursive, Shortcut, should_show, ) from tri_declarative.evaluate import ( get_cal...
StarcoderdataPython
9699189
<reponame>andrewinsoul/myDiary-python from django.test import TestCase class InitialTest3(TestCase): def test_one(self): self.assertEqual(2-2, 0)
StarcoderdataPython
313960
import os datapath = os.path.join(os.path.dirname(__file__), 'plots') if not os.path.exists(datapath): os.makedirs(datapath) def get_plot_path(filename): return os.path.join(datapath, filename)
StarcoderdataPython
11223587
"""The BRMFlask Sitemap Blueprint.""" from flask import Blueprint sitemap = Blueprint( 'sitemap', __name__, template_folder='templates', static_folder='static' ) from . import views
StarcoderdataPython
1749547
import json import numpy as np import os import pytest from numpy_encoder import NumpyEncoder, ndarray_hook test_vector = np.array([1.0, 2.0, 3.0]) test_mat = np.eye(3) here = os.path.dirname(os.path.realpath(__file__)) def write_encoded(obj, tdir): fp = tdir.mkdir("sub").join("obj.json") fp.write(obj) ...
StarcoderdataPython
187323
#!/usr/bin/python ''' htsint config file ''' __author__ = "<NAME>" import os,csv,re,ast from .version import __version__ defaultCONFIG = {'data':'/usr/local/share/htsint', 'dbname':"", 'dbuser':"", 'dbpass':"", 'dbhost':"localhost", ...
StarcoderdataPython
1749739
# Copyright 2008-2018 pydicom authors. See LICENSE file for details. """Read a dicom media file""" from pydicom.misc import size_in_bytes from struct import Struct, unpack extra_length_VRs_b = (b'OB', b'OW', b'OF', b'SQ', b'UN', b'UT') ExplicitVRLittleEndian = b'1.2.840.10008.1.2.1' ImplicitVRLittleEndian = b'1.2.840...
StarcoderdataPython
9650276
import re import pytest import numpy as np import warnings from unittest.mock import Mock from sklearn.utils._testing import assert_array_almost_equal from sklearn.utils._testing import assert_array_equal from sklearn.utils._testing import assert_allclose from sklearn.utils._testing import skip_if_32bit from sklearn.u...
StarcoderdataPython
9714389
from ..message_server import Message, ClosingMessage from ..interaction import instantiate from ..network_error import NetworkError class HelloMessage(Message): """ Let's name ourselves! """ def __init__(self, name=""): Message.__init__(self) self.name = name def __setstate__(self...
StarcoderdataPython
5097722
from haversine import haversine, Unit from statistics import mean import ast import urllib import aiohttp import asyncio import json import sqlite3 import googlemaps from db_handler import DatabaseHandler class ApiClient: base_url_walk_score = "https://api.walkscore.com/score?" base_url_google_geocode = "http...
StarcoderdataPython
6612264
<reponame>krlex/aws-python-examples # lamdda_function.py # It handles a simple AWS Lambda function that shows the content (JSON) of the call # to the lambda function and returns a message including this content. def lambda_handler(event, context): message = 'Hello {} {}!'.format(event['first_name'], ...
StarcoderdataPython
305403
from github import Github, UnknownObjectException, BadCredentialsException from gitopscli.gitops_exception import GitOpsException from .abstract_git_util import AbstractGitUtil class GithubGitUtil(AbstractGitUtil): def __init__(self, tmp_dir, organisation, repository_name, username, password, git_user, git_email...
StarcoderdataPython
1757186
import numpy as np import matplotlib import matplotlib.pyplot as plt import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression # from sklearn.impute import SimpleImputer # from sklearn.compose import ColumnTransformer # from sklearn.preprocessing import O...
StarcoderdataPython
6544613
<reponame>zhfeing/graduation-project<gh_stars>0 print("[info]: import get_data successful")
StarcoderdataPython
3571125
# Generate a nautilus shell from triangles # This method is based in the one described in Origami4 # "Paper Nautili: A Model for Three Dimensional Planispiral Growth" # by <NAME> # Starting with a right triangle ABC where A is the origin, # B is up and C is to the side. The goal is to calculate # the next triangle BD...
StarcoderdataPython
5166022
<reponame>jdlesage/tf-yarn """\ To run the example 1. Download winequality-*.csv from the Wine Quality dataset at UCI ML repository (https://archive.ics.uci.edu/ml/datasets/Wine+Quality). 2. Upload it to HDFS. 3. Pass a full URI to either of the CSV files to the example. For instance, if you prefer red wine:: ...
StarcoderdataPython
11216561
from unittest import TestCase from httpbase.fields import BoolField from httpbase.exceptions import SerializationError, NonNullableField from httpbase.resources import Resource class TestBoolField(TestCase): def test_bool_field(self): value = True class Foo(Resource): foo = BoolField...
StarcoderdataPython
12859097
<reponame>nickcamel/IgApi<filename>lib/watchlists.py # REF: https://labs.ig.com/rest-trading-api-reference class Watchlists: """ DO NOT CHANGE Adding is ok ... and encouraged ;) """ base = { 'path': 'watchlists', 'GET': { 'version': '1', 'tokens': True, ...
StarcoderdataPython
391617
<filename>code/frameworks/pisr/utils/__init__.py from __future__ import absolute_import from __future__ import division from __future__ import print_function from .utils import *
StarcoderdataPython
82135
<filename>src/pytti/Image/VQGANImage.py<gh_stars>0 from pathlib import Path from os.path import exists as path_exists import sys import subprocess import shutil from loguru import logger from taming.models import cond_transformer, vqgan from pytti import DEVICE, replace_grad, clamp_with_grad, vram_usage_mode import...
StarcoderdataPython
11314262
<gh_stars>0 from pathlib import Path from typing import List import numpy as np import pytest import torch from jina import Document, DocumentArray, Executor from ...transform_encoder import TransformerTorchEncoder _EMBEDDING_DIM = 768 @pytest.fixture(scope='session') def basic_encoder() -> TransformerTorchEncoder...
StarcoderdataPython
9694918
# Modified version of # DQN implementation by <NAME> found at # https://github.com/mrkulk/deepQN_tensorflow import numpy as np import tensorflow as tf tf.compat.v1.disable_eager_execution() class DQN: def __init__(self, params): self.params = params self.network_name = 'qnet' self.sess = tf...
StarcoderdataPython
3301136
<reponame>zakharovadaria/receipts<gh_stars>1-10 from flask_jwt_extended import jwt_required from flask_restplus import Namespace, reqparse, Resource, fields from app.models.ingredient import Ingredient from app.models.receipt import Receipt from app.web.controllers.entities.basic_response import BasicResponse, BasicRe...
StarcoderdataPython
9674993
import os print("Creating minified javascript") os.system("terser --compress --mangle -- tinytemplate.js > tinytemplate.min.js") large = os.path.getsize("tinytemplate.js") small = os.path.getsize("tinytemplate.min.js") print("Reduced size from %d bytes to %d bytes (%.02f%%)" % (large, small, ((large - small) / large)...
StarcoderdataPython
6422025
# coding: utf-8 import numpy as np import pandas as pd from scipy import interpolate import os import shapefile class Grid(object): def __init__(self, shp_file_path, region, density=100): """ 建立网格对象, 以shp文件获取的 region 外包矩形为网格外边界 :param shp_file_path: str -> 要打开的 shapefile 文件 :param region: st...
StarcoderdataPython
4935716
''' Created on May 24, 2018 @author: kjnether ''' from __future__ import unicode_literals from django.db import models class Destinations(models.Model): ''' Defines the destinations, uses key words in the job to define the destinations Keyword relates to this table. ''' dest_key =...
StarcoderdataPython
1764925
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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...
StarcoderdataPython
6598143
<reponame>Chris2L/gnss-ins-sim # -*- coding: utf-8 -*- # Filename: demo_mag_cal.py """ The simplest demo of soft iron and hard iron calibration. Created on 2018-07-09 @author: dongxiaoguang """ import os import math import numpy as np from gnss_ins_sim.sim import imu_model from gnss_ins_sim.sim import ins_sim # glob...
StarcoderdataPython
4826365
from lib.utils.common import * from PIL import Image import io import h5py from lib.data import ScanNet2DLoader import multiprocessing as mp import torch torch.multiprocessing.set_sharing_strategy('file_system') class ScanRefer2DDataset(ScanNet2DLoader): def __init__(self, hparams, phase, target_samples, tran...
StarcoderdataPython
1601560
<filename>src/data/914.py import sys sys.setrecursionlimit(500005) stdin = sys.stdin ni = lambda: int(ns()) nm = lambda: map(int, stdin.readline().split()) nl = lambda: list(nm()) ns = lambda: stdin.readline().strip() class LCADoubling: """ I used these sites as reference - https://ikatakos.com/pot/prog...
StarcoderdataPython
5105293
<reponame>karlneco/kanji-test-maker<gh_stars>1-10 from flask import url_for import requests from hktm import db from hktm.models import User def login(client,username,password): return client.post('/',data=dict(email=username,password=password), follow_redirects=True) def logout(client): return client.get('/...
StarcoderdataPython
336459
# IMPORTATION STANDARD # IMPORTATION THIRDPARTY import pytest # IMPORTATION INTERNAL from openbb_terminal.cryptocurrency.defi import terraengineer_model @pytest.mark.vcr @pytest.mark.parametrize( "asset,address", [("ust", "terra1tmnqgvg567ypvsvk6rwsga3srp7e3lg6u0elp8")], ) def test_get_history_asset_from_te...
StarcoderdataPython
9601966
<filename>app/StockModelLinear.py<gh_stars>0 import numpy as np import pandas as pd import datetime import logging from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LinearRegression from sklearn import metrics from sklearn.metrics impo...
StarcoderdataPython
8087429
from math import radians, degrees, sin, cos, tan, asin, acos, atan2 import numpy as np import matplotlib.pyplot as plt #Define Latitude in radians lat=radians(49.3978620896919) #Define hoirzontal limit in altitude in degree horizon_limit=12 def equ_to_altaz(ha,dec): """ Transforms equatorial coordinates (houra...
StarcoderdataPython
9623933
import torch import torch.nn as nn import numpy as np from models.real_nvp.real_nvp import RealNVP from models.resnet.resnet import ResNet class MLP_ACVAE(nn.Module): """RealNVP Model Based on the paper: "Density estimation using Real NVP" by <NAME>, <NAME>, and <NAME> (https://arxiv.org/abs/160...
StarcoderdataPython
9729407
# -*- coding: utf-8 -*- import factory from .models import Secret class SecretFactory(factory.DjangoModelFactory): """DjangoModelFactory for object Secret.""" name = factory.Faker('name') text = factory.Faker('bs') class Meta: model = Secret
StarcoderdataPython
8103613
<filename>samples/pore_detection.py import os import re import shutil import subprocess from os import listdir from os.path import isfile, join import cv2 from PIL import Image from itertools import product def splitImage(current_working_directory, inputImagePath, outputDirectory, resolution): path = current_wor...
StarcoderdataPython
11263566
<reponame>thundercrawl/book-of-qna-code<filename>ch3/dependency-parser-nivre/app/features/extractors.py # Copyright 2010 <NAME> ## # This is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the...
StarcoderdataPython
8077024
<reponame>CityU-AIM-Group/GFBS from .GateVGG import * from .GateResNet import * from .GateResNet50 import * from .GateMobileNetv2 import * from .GateDenseNet40 import *
StarcoderdataPython
11353250
<gh_stars>0 import pygame import pygame_textinput from scene.scene_base import SceneBase #from scene.lobby_scene import LobbyScene from scene.waiting_scene import WaitingScene class InputScene(SceneBase): def __init__(self): SceneBase.__init__(self) self.textinput = pygame_textinput.TextInput...
StarcoderdataPython
34718
<reponame>garysb/dismantle import os from pathlib import Path import pytest from dismantle.package import DirectoryPackageFormat, PackageFormat def test_inherits() -> None: assert issubclass(DirectoryPackageFormat, PackageFormat) is True def test_grasp_exists(datadir: Path) -> None: src = datadir.join('dire...
StarcoderdataPython
6658476
<reponame>pkusensei/adventofcode2017 from collections import deque def p1(step: int): nums = [0] idx = 0 current = 1 while current <= 2017: idx = (idx + step) % len(nums) + 1 nums.insert(idx, current) current += 1 return nums[idx + 1] def p2(step: int): nums = deque([...
StarcoderdataPython
11317935
import csv import json import os import iomb.dqi as dqi import iomb.matio as matio import numpy class Sector(object): def __init__(self): self.id = '' self.index = 0 self.name = '' self.code = '' self.location = '' self.description = '' def as_json_dict(self)...
StarcoderdataPython
6695894
<gh_stars>1-10 # -*- coding: utf-8 -*- import unittest from pystrings.pangram import Pangram class PangramTests(unittest.TestCase): def test_empty_string(self): pangram = Pangram("") self.assertFalse(pangram.is_pangram()) def test_valid_pangram(self): pangram = Pangram('the quick b...
StarcoderdataPython
8043352
<filename>src/__init__.py<gh_stars>0 # /dust/src/__init__.py import os import sys if not '__file__' in globals(): __file__ = os.path.join(os.path.abspath('.'), '__init__.py') def __setpaths__(level): PATHS = [os.path.abspath('.')] for i in range(level): PATHS.append(os.path.split(PAT...
StarcoderdataPython
9630013
import csv from time import sleep import requests STATES = [ "Sachsen-Anhalt", "Niedersachsen", "Sachsen", "Bayern", "Mecklenburg-Vorpommern", "Hamburg", "Schleswig-Holstein", "Rheinland-Pfalz", "Hessen", "Baden-Württemberg", "Thüringen", "Saarland", "Bremen", "...
StarcoderdataPython
3372297
<reponame>WPoelman/thesis import concurrent.futures import logging from argparse import ArgumentParser, Namespace from pathlib import Path import pandas as pd from tqdm import tqdm from tqdm.contrib.logging import logging_redirect_tqdm from synse.config import Config from synse.grew_rewrite import Grew from synse.hel...
StarcoderdataPython
8097541
<filename>tests/unit/classification/test_classification_widget.py # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import os import numpy as np from utils_cv.classification.widget import AnnotationWidget, ResultsWidget def test_annotation_widget(tiny_ic_data_path, tmp): ...
StarcoderdataPython
12802281
import cv2 import sys import logging as log import datetime as dt from time import sleep video_capture = cv2.VideoCapture(0) picCount = 0 while True: if not video_capture.isOpened(): print('Unable to load camera.') sleep(5) pass # Capture frame-by-frame ret, frame = video_capture....
StarcoderdataPython
6661672
from oldowan.mtconvert.sites2seq import sites2seq from oldowan.mtdna import rCRS from oldowan.polymorphism import Polymorphism def test_single_site_as_string(): sites = '16129-' seq = sites2seq(sites) assert '-' in seq def test_single_site_as_string_in_list(): sites = ['16129-'] seq = sites2se...
StarcoderdataPython
6409375
from pipeline.elastic import Elastic from pipeline.elastic.documents import Webpage, Service, Port from utils.config.ini import Ini from utils.config.env import Env ini = Ini(Env.read('CONFIG_FILE')) def test_start_connection(): with Elastic(ini=ini) as conn: assert conn def test_add_new_documents():...
StarcoderdataPython
5010504
#! -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name='bert4torch', version='0.1.5', description='an elegant bert4torch', long_description='bert4torch: https://github.com/Tongjilibo/bert4torch', license='MIT Licence', url='https://github.com/Tongjilibo/bert4torch', ...
StarcoderdataPython
3575092
# Copyright 2015 The Bazel 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 required by applicable la...
StarcoderdataPython
4838593
<filename>Lib/symbol.py<gh_stars>1-10 #! /usr/bin/env python # # Non-terminal symbols of Python grammar (from "graminit.h") # # This file is automatically generated; please don't muck it up! # # To update the symbols in this file, 'cd' to the top directory of # the python source tree after building the interpreter ...
StarcoderdataPython
1934126
# coding: utf8 import os import pathlib import shutil from os import system import pytest from clinicadl import MapsManager @pytest.fixture( params=[ "data/stopped_jobs/stopped_1", "data/stopped_jobs/stopped_2", "data/stopped_jobs/stopped_3", "data/stopped_jobs/stopped_4", ] ...
StarcoderdataPython
5069061
from .literals import TEST_RECEIVE_KEY, TEST_SEARCH_FINGERPRINT def mock_recv_keys(self, keyserver, *keyids): class ImportResult: count = 1 fingerprints = [TEST_SEARCH_FINGERPRINT] self.import_keys(TEST_RECEIVE_KEY) return ImportResult()
StarcoderdataPython
3581036
<filename>deeppavlov/models/ranking/ranking_network.py from keras.layers import Input, LSTM, Embedding, GlobalMaxPooling1D, Lambda, subtract, Conv2D, Dense, Activation from keras.layers.merge import Dot, Subtract, Add, Multiply from keras.models import Model from keras.layers.wrappers import Bidirectional from keras.op...
StarcoderdataPython
1621756
import test_interface from difficulty import Difficulty from question import Question class MultiplyTest(test_interface.TestI): def get_description(self) -> str: return "Positive multiply" def get_question(self, difficulty: Difficulty) -> Question: numbers = self.generate_numbers(difficulty)...
StarcoderdataPython
3304133
<reponame>jeffvswanson/LeetCode<filename>0019_RemoveNthNodeFromEndOfList/python/test_solution.py import pytest import solution def create_linked_list(raw_list) -> solution.ListNode: for i, val in enumerate(raw_list): if i == 0: node = solution.ListNode(val=val) head = node ...
StarcoderdataPython
5010746
__version__ = 'v3.0.1-dev'
StarcoderdataPython
6697670
import rosbag import rospy from tqdm import tqdm import sys import numpy as np import matplotlib.pyplot as plt from math import atan2, sin, cos from relative_nav.msg import NodeInfo inbag = rosbag.Bag('/home/superjax/rosbag/small_loop.bag', mode='r') outbag = rosbag.Bag('/home/superjax/rosbag/small_loop.new.bag', mode...
StarcoderdataPython
5187655
import pandas as pd """ This script concatenates a summary of the parameters/results for the cryptic phenotype models fit within each dataset. The table is used downstream by CollectResults_FilterFinalDiseases.py """ UCSFTable=pd.read_pickle('../UCSF/SummaryTable-7/UCSFModelingResults.pth') UKBBTable=pd.read_pickle('...
StarcoderdataPython
1987714
<gh_stars>0 class Meerk40tError(Exception): """ This root Meerk40t exception is provided in case we ever want to provide common functionality across all Meerk40t exceptions. """ class BadFileError(Meerk40tError): """Abort loading a malformed file"""
StarcoderdataPython
4982258
# Example of sampling from a normal probability density function import scipy.stats from pylab import *; ion() import probayes as pb norm_range = {-2., 2.} set_size = {-10000} # size negation denotes random sampling x = pb.RV("x", norm_range, prob=scipy.stats.norm, loc=0, scale=1) rx = x.evaluate(set_size) hist(rx['x'...
StarcoderdataPython
1600176
# String for add/edit.component.html user_add_edit_string = """ <div class="form-group"> <input type="{type}" class="form-control input-underline input-lg" id="{field}" required formControlName = "{field}" placeholder=" {field}"> ...
StarcoderdataPython
3471703
# Attempt to import proto file import a.b.demo_pb2
StarcoderdataPython
6476268
# 保存 import requests import json headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36', 'Content-Type': 'application/json; charset=UTF-8' } data = { "projectDeclare": { "id": "f4001645-c27e-4e3b-92ee-157...
StarcoderdataPython
4935636
<gh_stars>0 # -*- coding: utf-8 -*- # Version: 0.2 # 该模块主要做vad切割,核心函数是segmentVoiceByZero. import librosa import numpy as np import matplotlib.pyplot as plt import time import sys import os matrix_size = 500 def smooth_filter(data): ''' filter audio data by smooth Parameters -------...
StarcoderdataPython
5065359
<reponame>NeCTAR-RC/bumblebee import collections from django import template from django.template.defaultfilters import safe import six register = template.Library() def iterable(arg): return ( isinstance(arg, collections.Iterable) and not isinstance(arg, six.string_types) ) @register.filt...
StarcoderdataPython
1808982
<gh_stars>0 '''面试题6:从尾到头打印链表 输入一个链表的头节点,从尾到头反过来打印出每个节点的值。 ---------------- Example input: 1->5->3->4 output:4351 ---------------------- 如果要修改输入数据要询问(逆转链表),观测输入输出顺序考虑特殊辅助结构,栈、递归和循环间的关系 ''' class Node(object): def __init__(self, value=None, next_node = None): self.value = value self.next_node = next...
StarcoderdataPython
201650
<filename>enki/modeltokenverify.py<gh_stars>1-10 from google.appengine.ext.ndb import model class EnkiModelTokenVerify( model.Model ): token = model.StringProperty() email = model.StringProperty() user_id = model.IntegerProperty() # ndb user ID time_created = model.DateTimeProperty( auto_now_add = True ) type =...
StarcoderdataPython
355702
<reponame>ndjuric93/MusicOrganizer """ Flask application """ from micro_player import create_app from micro_player.config import SERVER_CONFIG SERVICE_NAME = 'MicroPlayer' if __name__ == '__main__': app = create_app(name=SERVICE_NAME, **SERVER_CONFIG) app.run( host=SERVER_CONFIG['host'], port=...
StarcoderdataPython
6606176
<reponame>uon-language/uon-parser import struct from validation.schema import Schema from validation.validator import Validator from validation.types.number.uint_type_validation import UintTypeValidation from validation.properties.number.number_max_property import MaxNumberValidation from validation.properties.numbe...
StarcoderdataPython
11209869
<gh_stars>0 # Collection data type that is ordered and immutable same is list but just that it cannot be changed after creation # It allows duplicate my_tuple = ("Max", 123, "Hello") print(my_tuple) print(type(my_tuple)) # parenthesis is optional my_tuple_1 = "World", "XYZ" print(my_tuple_1) # tuple with single elemen...
StarcoderdataPython
1686646
<reponame>bwmichael/jccc-cis142-python<filename>labs/unit07/unit07Lab.py ## # @author <NAME> # This program asks the user for a year that we can check to see if it is a # leap year or not. ## Determines if a year is a leap year # @param year The year to test (Integer) # @return true or false where the year is a leap ...
StarcoderdataPython
121731
<reponame>accelerationa/DistributedSpider<gh_stars>0 import logging from task_status import TaskStatus import time import pymongo from init_mongo_client import init_mongo_client class TaskDBMongoDao: def __init__(self, database_name, collection_name, stack): self.client = init_mongo_client(stack=stack) ...
StarcoderdataPython
8175494
<filename>src/api/datahub/databus/tests/modules/hdfs_import_views_test.py # -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT Licens...
StarcoderdataPython
9737603
from . import sampling, sa
StarcoderdataPython
11361462
# -*- coding: utf-8 -*- """ The MIT License (MIT) Copyright (c) 2015-2019 Rapptz 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 u...
StarcoderdataPython
11252191
from pathlib import Path from string import punctuation from nltk.corpus import stopwords ROOT = Path(__file__).resolve().parent DATA_FOLDER = ROOT.joinpath("data") STOP_WORDS = set(stopwords.words('english') + list(punctuation) + ['AT_USER', 'URL'])
StarcoderdataPython
9694873
from core.data.ans_punct import prep_ans from core.data.save_glove_embeds import StoredEmbeds import numpy as np import random, re, json from torch.utils.data._utils.collate import default_collate try: import en_vectors_web_lg except ImportError: import spacy def shuffle_list(ans_list): random.shuffle(...
StarcoderdataPython
9799161
<filename>api/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.simple_request, name='send_comment'), path('image/', views.image_request, name='send_image') ]
StarcoderdataPython
3367238
<filename>util/detector.py from detectron2.data.detection_utils import read_image from detectron2.config import get_cfg from detectron2.engine.defaults import DefaultPredictor import numpy as np import cv2 import os import glob from tqdm import tqdm import pickle class Args(): def __init__(self): self.config_...
StarcoderdataPython
212414
<gh_stars>1-10 #!/usr/bin/env python import hglib from hglib.util import b import os import sys def main(): if 'BUILD_URL' not in os.environ: print('Warning: This script should be called on jenkins only') return -1 if len(sys.argv) > 2: print('Unknown parameter: {}'.format(sys.argv)...
StarcoderdataPython
9708665
import logging from app.config_common import * # DEBUG can only be set to True in a development environment for security reasons DEBUG = True # Secret key for generating tokens SECRET_KEY = 'ishant' # Admin credentials ADMIN_CREDENTIALS = ('admin', 'admin') # Database choice SQLALCHEMY_DATABASE_URI = 'sqlite:///a...
StarcoderdataPython
5196767
# See LICENSE file for full copyright and licensing details. from odoo.tests import common from datetime import datetime from dateutil.relativedelta import relativedelta as rd class TestAttendance(common.TransactionCase): def setUp(self): super(TestAttendance, self).setUp() self.daily_attendance...
StarcoderdataPython
1944303
# -*- encoding: utf-8 -*- import sys sys.path.append("..") import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import OneHotEncoder from sklearn.tree import DecisionTreeClas...
StarcoderdataPython
1618510
<gh_stars>10-100 import pandas as pd from IPython import display def side_by_side(df1, df2, name1='', name2=''): if isinstance(df1, pd.Series): df1 = df1.to_frame(name=df1.name) if isinstance(df2, pd.Series): df2 = df2.to_frame(name=df2.name) inline = 'style="display: float; max-width:50%"...
StarcoderdataPython
3451209
<filename>src/core/fields.py import uuid from django.db import models class UUIDPrimaryKey(models.UUIDField): def __init__(self, **kwargs): kwargs['primary_key'] = True kwargs.setdefault('editable', False) kwargs.setdefault('default', uuid.uuid4) super().__init__(**kwargs)
StarcoderdataPython
196576
import numpy as np import pandas as pd from scipy import ndimage import json import h5py import keras def preprocess_input(x): x /= 255. x -= 0.5 x *= 2. return x #归一化输入 def extract_lable(path): with open(path,'rb') as f: data=json.load(f) data=pd.DataFrame.from_dict(data) del da...
StarcoderdataPython
4968796
import numpy as np import tensorflow as tf from tasks import Task class CopyTask(Task): epsilon = 1e-2 def __init__(self, vector_size, min_seq, train_max_seq, n_copies): self.vector_size = vector_size self.min_seq = min_seq self.train_max_seq = train_max_seq self.n_copies = n_...
StarcoderdataPython
3470129
<filename>HW2 - State Estimation/ZHAO_FRANKLIN_HW2.py Rank of Observability Matrix for four-state system: 3
StarcoderdataPython
9719288
<filename>cjsite/__init__.py default_app_config = "cjsite.apps.AppConfig"
StarcoderdataPython
6465350
<gh_stars>100-1000 # Copyright 2013 <NAME> # # 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 ...
StarcoderdataPython
8027186
#!/bin/python """ @author <NAME> (renegat0x0) """ import base64 import os import re import argparse import logging import shutil import traceback import sys from io import BytesIO import ftpshutil.dircrc as dircrc logging.basicConfig(level=logging.INFO) from ftplib import * def ftp_path_jo...
StarcoderdataPython
5070473
<gh_stars>0 #!/usr/bin/env python # -*- coding:utf-8 -*- import os import time if raw_input("restart swift or not (y/n):")=='y': for k in os.popen('sudo python setup.py install').readlines(): pass for j in os.popen('sudo swift-init main restart').readlines(): pass # print j, # time.sleep(...
StarcoderdataPython
265005
import boto3 import json import datetime import os ecs_client = boto3.client('ecs') alb = boto3.client('elbv2') sts = boto3.client('sts') sns = boto3.client('sns') #CROSSACCOUNT DYNAMO ACCESS TO SHARED ACCOUNT stsrolearn = os.environ['STSROLEARN'] response = sts.assume_role(RoleArn=stsrolearn, RoleSessionName='CrossA...
StarcoderdataPython
3355760
#-*- coding: utf-8 -*- from django.utils.translation import ugettext as _ TIMEZONE_CHOICES = [ ('Etc/GMT+12', _("(GMT -12:00) Eniwetok, Kwajalein")), ('Etc/GMT+11', _("(GMT -11:00) Midway Island, Samoa")), ('Etc/GMT+10', _("(GMT -10:00) Hawaii")), ('Pacific/Marquesas', _("(GMT -9:30) Marquesas Island...
StarcoderdataPython
4937731
import os HOME = os.environ['HOME'] TEST_DATA_DIR = '{}/data/CastorClientTestData'.format(HOME) TEST_DATA_EXCEL_FILE = 'ESPRESSO_v2.0_DHBA_excel_export_20201112094203.xlsx' TEST_DATA_HOSPITAL_ID = 'dhba_verrichting_upn' TEST_DATA_SURGERY_DATE = 'dhba_datok1'
StarcoderdataPython