id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
1695395
import datetime #Django Imports from django import forms from django.conf import settings from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Fieldset, Div, Submit from crispy_forms.bootstrap import FormActions #Local App Imports import contacts.models as cont import utils.forms as ut...
StarcoderdataPython
1703050
<gh_stars>0 """ Class representing ice clusters or aggregates. Parent class that defines: - point arrays - crystals within the cluster - methods to move and reorient the arrays """ import shapely.ops as shops from pyquaternion import Quaternion import copy as cp import numpy as np import random import shap...
StarcoderdataPython
167191
from os import path import analytics_utils import setuptools this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, "README.md"), encoding="utf-8") as f: long_description = f.read() setuptools.setup( name="analytics_utils", version=analytics_utils.__version__, autho...
StarcoderdataPython
1653480
<reponame>andela-ojoloko/Todo-Api from flask import Flask, jsonify from flask_restful import Api from flask_migrate import Migrate from .util import limiter from .models import db from .resources.todos import TodoListResource, TodoResource from .resources.users import UserListResource, AuthResource, UserResource from ...
StarcoderdataPython
1643793
import types import logging from botocore.auth import SigV4Auth logger = logging.getLogger("awscli.clidriver") def get_auth_instance(self, signing_name, region_name, signature_version=None, **kwargs): # create new signer for API Gateway # addresses `Credential should be scoped to correct service: 'execute-api...
StarcoderdataPython
3324620
<filename>Model Building/2.2 Logistic Regression/2.2.2.4.py import pandas as pd dataset = pd.read_csv('heart.csv') dataset.head(20) X = dataset.iloc[:, :-1] y = dataset.iloc[:, -1] X y # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y...
StarcoderdataPython
1761303
#!/usr/local/imdc/core/python/bin/imdc -OO # The line above is required to run as an IMDC plugin # im_comtrend.py - Intermapper probe for Comtrend DSL modems # # Scrape web interface of a Comtrend DSL modem to return its SNR values, # and other important operational characteristics. # Tested with Comtrend AR-5381U #...
StarcoderdataPython
1777710
# latency.py Benchmark for uasyncio. Author <NAME> July 2018. # This measures the scheduling latency of a notional device driver running in the # presence of other coros. This can test asyncio_priority.py which incorporates # the priority mechanism. (In the home directory of this repo). # When running the test that u...
StarcoderdataPython
1698011
<reponame>mattpitkin/GraWIToNStatisticsLectures<filename>figures/scripts/estimator.py #!/usr/bin/env python """ Make plots of the Gaussian/normal distribution for different standard devaitions """ import matplotlib.pyplot as pl from scipy.stats import norm import numpy as np theta0 = 1.5 mus = [1.5, 3.] # the mean, ...
StarcoderdataPython
4825946
# Copyright 2015 Metaswitch Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
StarcoderdataPython
3222370
import logging import os import sys from pprint import pprint from pymongo import MongoClient logging.basicConfig() logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) class MongoWatch: def __init__(self, db): pass def watch_collection(self, collection, document=None): watc...
StarcoderdataPython
1689421
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from MinimizaAuto.class_auto import Auto def completa_auto(auto): for i in auto.estados: transisoes = [(x, y, z) for (x, y, z) in auto.trans if x == i] presentes = [] for t in transisoes: for letra in auto.alfabeto: ...
StarcoderdataPython
22473
nota1 = float(input('nota 1: ')) nota2 = float(input('nota 2: ')) media = (nota1 + nota2)/2 print('A media entre a nota 1 e a nota 2 é {}'.format(media))
StarcoderdataPython
3234628
from rest_framework.authtoken.models import Token from BettingRestAPI.utils.Message import Message import json from BettingRestAPI.Serializer.Encoder import ComplexEncoder from django.contrib.auth.models import User, Permission from rest_framework import status def check_authorization(request): permissions = Perm...
StarcoderdataPython
1666936
import tensorflow as tf import numpy as np import logging logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s') ## ====================================================================== ## ====================================================================== def crop_and_concat_layer(inputs, axis=...
StarcoderdataPython
3369032
<filename>utilities/csv_preprocessing/csv2mat.py import string import numpy as np import os import sys from sklearn.decomposition import PCA import matplotlib.pyplot as plt import scipy.io class TF: def __init__(self, f_id, cf_id): self.frame_id = f_id self.child_frame_id = cf_id # loads all CSV...
StarcoderdataPython
3250264
<filename>tools/prepare_python_system_tests.py import argparse import json import os import subprocess import tempfile import time import urllib.request import zipfile print('****Installing tox to Python.****') results = subprocess.run(["python", '-m', 'pip', 'install', '--disable-pip-version-check', '--upgrade', 'pip...
StarcoderdataPython
4808501
#! /usr/bin/env python # -*- coding: utf8 -*- from django import template register = template.Library() def render_paginator(context, first_last_amount=2, before_after_amount=4): page_obj = context['page_obj'] paginator = context['paginator'] page_numbers = [] # Pages before current page if page_...
StarcoderdataPython
3222506
import re import nltk from helpfunctions import mutual_exclusive_score eventTimePath = '0_Preprocessing/corpus/eventtime/event-times_normalized.tab' eventTimes = {} predLabelPosition = -1 def getDates(value): """ Normalizes TimeX Value, Normalize seasons and weeks return the normalized dates in value ...
StarcoderdataPython
1679541
__module_name__ = 'hlphrase' __module_description__ = 'highlights phrases instead of just single words' __module_version__ = '1.0' import hexchat, re CONFFILE = hexchat.get_info('configdir') + '/hlphrase.conf' list=[] hexchat.prnt('%(name)s, version %(version)s' % {'name': __module_name__, 'version': __module_vers...
StarcoderdataPython
4811692
<reponame>ample-tech/electric-units """Test the NemDispatchPeriod object. Assumes that the base object is the same as the NemSettlementPeriod object, so it doesn't require the same tests""" from datetime import datetime from pytz import timezone import pytest from electric_units import NemDispatchPeriod NEM_DATA = [ ...
StarcoderdataPython
3231535
<gh_stars>0 """ Client classes for the GA4GH reference implementation. """ from __future__ import division from __future__ import print_function from __future__ import unicode_literals import requests import posixpath import logging import json from requests_oauthlib import OAuth2Session from oauthlib.oauth2 import L...
StarcoderdataPython
1798174
<reponame>o3project/odenos # -*- coding:utf-8 -*- # Copyright 2015 NEC Corporation. # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in ...
StarcoderdataPython
182417
import sys keys = ["1", "!", "2", "\"", "3", "4", "$", "5", "%", "6", "^", "7", "8", "*", "9", "(", "0", "q", "Q", "w", "W", "e", "E", "r", "t", "T", "y", "Y", "u", "i", "I", "o", "O", "p", "P", "a", "s", "S", "d", "D", "f", "g", "G", "h", "H", "j", "J", "k", "l", "L", "z", "Z", "x", "c", "C", "v", "V", "b", "B", "n",...
StarcoderdataPython
105825
''' Problem 019 You are given the following information, but you may prefer to do some research for yourself. 1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. A...
StarcoderdataPython
3392109
<filename>generated-libraries/python/netapp/fcport/link_state_info.py<gh_stars>1-10 from netapp.fcport.fc_ports import FcPorts from netapp.netapp_object import NetAppObject class LinkStateInfo(NetAppObject): """ list link-state info of a specific adapter channel """ _fc_port_info = None @prope...
StarcoderdataPython
45498
# encoding: utf-8 from IPython.testing import decorators as dec def test_import_backgroundjobs(): from IPython.lib import backgroundjobs def test_import_deepreload(): from IPython.lib import deepreload def test_import_demo(): from IPython.lib import demo
StarcoderdataPython
191267
import sys def clean_html(html_file): """Remove unnecessary tags from slides.""" clean_file = (html_file.replace("<section><section><image>", "") .replace("</image></section></section>", "")) return clean_file if __name__ == "__main__": try: with open(sys.argv[1], "r...
StarcoderdataPython
3208102
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-14 11:20 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('UserManagement', '0023_auto_20170314_1139'), ('SessionManagement', '0003_auto_201703...
StarcoderdataPython
3274876
class UnionFind(object): def __init__(self,n): self.parent=[-1]*n self.rank=[0]*n self.union=0 for i in xrange(n): self.parent[i]=i def find(self,x): if self.parent[x]==x: return x self.parent[x]=self.find(self.parent[x]) return self.paren...
StarcoderdataPython
72725
<reponame>radiumweilei/chinahadoop-ml-2 #!/usr/bin/python # -*- coding:utf-8 -*- import numpy as np from sklearn import svm import matplotlib.colors import matplotlib.pyplot as plt from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, fbeta_score import warnings def show_accuracy(a, b)...
StarcoderdataPython
4842962
<reponame>ahijevyc/HWT_mode import tensorflow as tf from tensorflow.keras.regularizers import Regularizer import tensorflow_probability as tfp @tf.keras.utils.register_keras_serializable(package='Custom', name='Covariance') class CovarianceRegularizer(Regularizer): """ The CovarianceRegularizer is designed to...
StarcoderdataPython
1686375
<gh_stars>1-10 # -*- coding: utf-8 -*- "Tests for keyboard support." # std imports import functools import tempfile import signal import curses #import time import math import tty # NOQA import pty import sys import os # local from .accessories import ( init_subproc_coverage, read_until_eof, read_until_s...
StarcoderdataPython
1786305
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- import os from getpass import getpass try: import dotenv except ModuleNotFoundError: print( """Missing dependencies. Run: pip install -r requirements.txt""" ) exit(1) class Config(): def __init__(self, saveDir): self.file = os.path.join(saveDir, ".env") doten...
StarcoderdataPython
1680240
from tests.utils import W3CTestCase class TestFlexbox_StfTable(W3CTestCase): vars().update(W3CTestCase.find_tests(__file__, 'flexbox_stf-table'))
StarcoderdataPython
27056
<gh_stars>1-10 """ To start the tests, type from CLI: python test_solution_sum_of_missing_numbers.py """ import unittest from solution_football_yellow_and_red_cards import men_still_standing class TestSolution(unittest.TestCase): def test_simple_cases(self): self.assertEqual(men_still_standing([]), (11...
StarcoderdataPython
88684
<reponame>Palem1988/blocknetdx-utils<filename>rpc_test_cases/xbridge_rpc_generating_test.py import unittest import xbridge_logger from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException import random from utils import xbridge_custom_exceptions from interface import xbridge_rpc from utils import xbri...
StarcoderdataPython
52766
<gh_stars>100-1000 import clr clr.AddReference('RevitAPI') from Autodesk.Revit.DB import * clr.AddReference("RevitNodes") import Revit clr.ImportExtensions(Revit.Elements) def GetElevationMarkerView(item): val = [] if hasattr(item, "HasElevations"): if item.HasElevations(): for i in range(item.MaximumViewCount...
StarcoderdataPython
3216938
<reponame>Yutongamber/Competition_Olympics-Curling import sys from pathlib import Path base_path = str(Path(__file__).resolve().parent.parent) sys.path.append(base_path) print(base_path) from core import OlympicsBase from object import * import time gamemap = {'objects':[], 'agents':[]} #rectangular #gamemap['obje...
StarcoderdataPython
5103
from django.contrib import admin from .models import Songs admin.site.register(Songs) # Register your models here.
StarcoderdataPython
3312953
<gh_stars>1-10 from __future__ import annotations from typing import TYPE_CHECKING, Any, Type, TypeVar, cast, overload from asyncpg import Record from asyncpg.pool import PoolConnectionProxy from attr import dataclass from discord.ext import typed_commands from ..compat import ( AbstractAsyncContextManager, ...
StarcoderdataPython
3336102
<reponame>kdorichev/text2speech<gh_stars>1-10 """ from https://github.com/keithito/tacotron """ import re valid_symbols = \ ('AA AA0 AA1 AA2 AE AE0 AE1 AE2 AH AH0 AH1 AH2 AO AO0 AO1 AO2 AW AW0 AW1 '+ 'AW2 AY AY0 AY1 AY2 B CH D DH EH EH0 EH1 EH2 ER ER0 ER1 ER2 EY EY0 EY1 '+ 'EY2 F G HH IH IH0 IH1 IH2 IY IY0 I...
StarcoderdataPython
3296841
<reponame>liuh127/Two-branch-dehazing import torch.nn as nn class Res2Net(nn.Module): def __init__(self, block, layers, baseWidth=26, scale=4, num_classes=1000): self.inplanes = 64 super(Res2Net, self).__init__() self.baseWidth = baseWidth self.scale = scale self.conv1 = nn....
StarcoderdataPython
154480
<filename>httprunner/loader.py<gh_stars>1-10 import csv import importlib import io import json import os import sys import types from typing import Tuple, Dict, Union, Text, List, Callable import yaml from loguru import logger from pydantic import ValidationError from httprunner import builtin, utils from httprunner ...
StarcoderdataPython
1626808
<reponame>cforlando/intake<filename>phone/urls.py from django.conf.urls import url from phone.views import record, handle_new_message urlpatterns = [ # voicemail views # these views are public, csrf exempt, and answer to POST data url(r'^handle-incoming-call$', record, name='phone-handle_incoming_call'), ...
StarcoderdataPython
27636
<gh_stars>0 """ Base settings to build other settings files upon. """ from pathlib import Path import environ env = environ.Env() # GENERAL # ------------------------------------------------------------------------- BASE_DIR = Path(__file__).resolve(strict=True).parent.parent.parent PROJECT_NAME = "process_status_m...
StarcoderdataPython
32595
<filename>BOMFinder/helpers.py import BOMFinder.UI.UI as UI def to_prompt_sequence(part): prompt_sequence = [] for key, value in part.properties.items(): if isinstance(key, str): if isinstance(value, str): prompt_sequence.append(UI.ValuePrompt(key)) elif isinst...
StarcoderdataPython
3268758
import pytest import math @pytest.fixture(scope='function') def IpcServer(): from gpopup import ipc from random import randint val = ipc.Server._default_sock_name() rando = '_' + '{:d}'.format(randint(0, int(1e6))) class _IpcServer(ipc.Server): @classmethod def _default_sock_name(cl...
StarcoderdataPython
1744173
<gh_stars>0 import pygame class Wall: def __init__( self, header_size, window_height, window_width, thickness, color=(255, 255, 255) ): self.x_min = 0 self.x_max = window_width - thickness self.y_min = header_size self.y_max = window_height - thickness self.x_...
StarcoderdataPython
1723793
from data import word_frequencies from data.graph import bloom_node, ngram, regex, walk from spec.mamba import * comparison = perf.Perf('trie v regex', ['trie', 'regex']) def get_words( length_mask: int = None, file: str = 'data/g1m_1gram.txt', multi: bool = False) -> list: def _check(word: str) -> bo...
StarcoderdataPython
3280877
# Generated by Django 3.1.4 on 2020-12-29 10:06 from django.db import migrations, models import uuid class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Hospital', fields=[ ('id', mode...
StarcoderdataPython
1610611
#from Python import time import csv import os import math import numpy as np import sys from shutil import copyfile #from Pytorch import torch import torchvision import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from torchvision import datasets from torchvision import transforms...
StarcoderdataPython
1779750
# -*- coding: utf-8 -*- import numpy as np from .numberedentity import UniqueNumbered class NumberedList(list): """ Makes it possible to loop over a list of items with discontinous numbering. """ def __init__(self, *args, **kwargs): super().__init__() self.Sequence = None sel...
StarcoderdataPython
105112
"""Filter used to select the first preferred output format available, excluding interactive widget format if the widget state is not available. The filter contained in the file allows the converter templates to select the output format that is most valuable to the active export format. The value of the different form...
StarcoderdataPython
3278764
<gh_stars>0 from iso639 import languages def get_language(code): try: return languages.get(part3=code) except Exception: return None
StarcoderdataPython
3292831
from __future__ import unicode_literals from unittest import TestCase from ..models.variants import normalize_variant from .genome import MockGenomeTestFile _genome_seq = dict([ (('chr1', 0, 41), 'N' * 41), (('chr1', 1, 31), 'N' * 30), (('chr17', 41246230, 41246271), 'AGCCTCATGAGGATCACTGGCCAGTAAGTCTATT...
StarcoderdataPython
1728756
import json from whyis.test.api_test_case import ApiTestCase testdata = [ {"id":1,"name":"<NAME>","age":"12","col":"red","dob":""}, {"id":2,"name":"<NAME>","age":"1","col":"blue","dob":"14/05/1982"}, {"id":3,"name":"<NAME>","age":"42","height":0,"col":"green","dob":"22/05/1982","cheese":"true"}, {"id":...
StarcoderdataPython
3389966
"""Group process requirements check and the creation of the game""" from s2clientprotocol import sc2api_pb2 as sc_pb from .protocol import Protocol from .player import Computer class Controller(Protocol): """It creates the game and checks processes""" def __init__(self, web_service, process): super()...
StarcoderdataPython
117483
from carrots import Microproducer import datetime rabbit_uri = 'amqp://rabbitmq:rabbitmq@localhost:5672/%2F' mp = Microproducer(rabbit_uri,'','example.tasks') ids = [{'id': i} for i in range(0,100000)] before = datetime.datetime.now() mp.send(ids) print((datetime.datetime.now()-before).total_seconds())
StarcoderdataPython
4821534
"""Unit testing module for scraping/page_scrape.py""" from bs4 import BeautifulSoup from bs4.element import Tag import unittest from __main__ import page_scrape class Test(unittest.TestCase): def setUp(self): self.test_case = page_scrape.make_request('bruh') def test_make_request(self): "...
StarcoderdataPython
1711707
import praw import requests import datetime def get_date(submission): time = submission.created return datetime.datetime.fromtimestamp(time) r = praw.Reddit(client_id='SDNLVa0_tOJOfg' , client_secret='-<KEY>', username='frankeve', password='<PASSWORD>...
StarcoderdataPython
1648884
from django.db.models import fields from rest_framework.serializers import ModelSerializer from blog.models import Post class PostSerializer(ModelSerializer): class Meta: model = Post fields = "__all__"
StarcoderdataPython
4815803
"""Fixtures for cloud tests.""" from unittest.mock import patch import jwt import pytest from openpeerpower.components.cloud import const, prefs from . import mock_cloud, mock_cloud_prefs @pytest.fixture(autouse=True) def mock_user_data(): """Mock os module.""" with patch("opp_cloud.Cloud.write_user_info")...
StarcoderdataPython
1760018
import matplotlib.pyplot as plt depth = [0,1,2,3,4,5,6,7] train_error = [0.4430,0.2013,0.1342,0.1141,0.1074,0.0872,0.0738,0.0671] test_error = [0.5060,0.2169,0.1566,0.1687,0.2048,0.1687,0.1928,0.2048] plt.plot(depth,train_error, ls='--', marker='o', label='Train Error Rate') plt.plot(depth,test_error, ls='-', marker...
StarcoderdataPython
1786439
<filename>Part3/advanced_square.py import getopt import sys from math import sqrt """ get the square but get the square root incase the argument 'root' is provided """ def usage(): """ Show help for the CLI program """ print("python advanced_square.py --number <your_number> \n OR\n") print("pytho...
StarcoderdataPython
62875
<gh_stars>0 import os ICONS = { "red": os.environ.get('RED_ICON', ":red_circle:"), "black": os.environ.get('BLACK_ICON', ":black_circle:"), "green": os.environ.get('GREEN_ICON', "") } def determine_color(number): """ In number ranges from 1 to 10 and 19 to 28, odd numbers are red and even are bla...
StarcoderdataPython
1797851
import numpy as np from keras.engine.sequential import Sequential from keras.layers.core import Dense, Dropout from keras.layers.embeddings import Embedding from keras.layers.recurrent import LSTM from keras.preprocessing.text import Tokenizer from keras.utils.np_utils import to_categorical from pymystem3 import Mystem...
StarcoderdataPython
3235785
import os import boto3 import time client = boto3.client('cloudfront') def display_title_bar(): os.system('clear') print("\n\n") print("\t**********************************************") print("\t*** cdn and cache control ***") print("\t*****************************************...
StarcoderdataPython
4804514
# -*- coding: utf-8 -*- import os from builtins import object from .client.pps.pps_pb2 import * from .client.pps.pps_pb2_grpc import * class PpsClient(object): def __init__(self, host=os.environ.get('PACHD_SERVICE_HOST', 'localhost'), port=os.environ.get('PACHD_SERVICE_PORT_API...
StarcoderdataPython
3267551
import os import pandas as pd class TextFileLoader: def __init__(self, dirs): self.df = pd.DataFrame(columns=['measurement number']) meas_number = 0 for directory in dirs: self.df = self.df.append(self.read_dir(directory)) self.df.fillna(meas_number, inplace=True) ...
StarcoderdataPython
3396148
def env_translate_obs(obs): """ This should only be used for the Tiger ENV. Parameters ---------- obs : list or array-like The observation to be translated. Returns ------- str A representation of the observation in English. """ if obs[0] == 1: return 'G...
StarcoderdataPython
1612802
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
StarcoderdataPython
1712469
<reponame>imjoseangel/100DaysOfCode<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) # Load Libraries from sklearn.datasets import make_blobs import matplotlib.pyplot as plt # Generate feature matr...
StarcoderdataPython
66411
<gh_stars>0 # -*- coding: utf-8 -*- from os import getcwd import boto3 from api.rdb.utils.lambda_logger import lambda_logger from api.rdb.utils.service_framework import handle_request from api.rdb.utils.sns import get_sns_attributes logger = lambda_logger(__name__, getcwd()) # ...
StarcoderdataPython
49295
<gh_stars>0 from . import _BASE_WEB_INTERFACE,_BASE_API_BILIBILI_COM_X,_BASE_API_BILIBILI_COM,_BASE_API_BILIBILI_COM_X_V2 CARD="%s/card" % _BASE_WEB_INTERFACE NAV="%s/nav" % _BASE_WEB_INTERFACE RELATION_STAT="%s/relation/stat" % _BASE_API_BILIBILI_COM_X FAV_FOLDER="%s/fav/folder" % _BASE_API_BILIBILI_COM_X_V2
StarcoderdataPython
3321786
<gh_stars>0 from __future__ import annotations import logging import typing as T import xarray import numpy as np from scipy.special import erf def Efield_erf( E: xarray.Dataset, xg: dict[str, T.Any], lx1: int, lx2: int, lx3: int, gridflag: int, flagdip: bool, ) -> xarray.Dataset: """...
StarcoderdataPython
180229
<reponame>yanzhoushow/hackathon def lambda_handler(event, context): message = event['Records'][0]['Sns']['Message'] print("handle message: " + message) webhook_url = 'https://hookb.in/RZYdoJVodkcREEj72WqV' http = urllib3.PoolManager() r = http.request( 'POST', webhook_url, b...
StarcoderdataPython
1686017
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in co...
StarcoderdataPython
94060
#!/usr/bin/python import json import random as r import requests from credentials import * # URL Helper def _url(path): return 'https://api.ciscospark.com/v1' + path def get_rooms(at): headers = {'Authorization': at, 'content-type': 'application/json; charset=utf-8'} resp = requests.get(url=...
StarcoderdataPython
4806950
__author__ = 'ricky'
StarcoderdataPython
105016
import flask from flask import request from flask import render_template from .web_support import * from .cli import cli ##################################################################### # STARING NEW FLASK SKELETON (Task 2 - flask) #check the config class LabelordWeb(flask.Flask): """ The class represent...
StarcoderdataPython
1747134
# -*- coding: utf-8 -*- # # Copyright (C) 2021 <NAME>. # # Invenio-Requests is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more details. """Systemfield for managing referenced entities in request.""" from functools import partial from invenio_rec...
StarcoderdataPython
3381865
from typing import Dict, Any JSON = Any def compare_schemas(left: Dict[str, any], right: Dict[str, any]): left_dict = {c["name"]: c["type"] for c in left["columns"]} right_dict = {c["name"]: c["type"] for c in right["columns"]} left_ok = all([right_dict.get(k, None) == v for k, v in left_dict.items()]) ...
StarcoderdataPython
90019
from urllib.parse import urlencode from django.conf import settings from django.contrib.auth import REDIRECT_FIELD_NAME from security.forms.object_list import PRISON_SELECTOR_USER_PRISONS_CHOICE_VALUE from security.utils import can_choose_prisons def prison_choice_available(request): return { 'prison_ch...
StarcoderdataPython
3296353
<reponame>EraYaN/FletcherFiltering<gh_stars>0 # Copyright (c) 2019 <NAME>. 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/LIC...
StarcoderdataPython
3299324
<reponame>mesudip/instabot<filename>src/qt_ui/status.py # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'status.ui' # # Created by: PyQt5 UI code generator 5.9 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): ...
StarcoderdataPython
81347
import os, random, sys, time import torch from os import path as osp from pprint import pprint import numpy as np from torch import nn from torch.backends import cudnn import utils.loss as loss from models import get_baseline_model from utils.meters import AverageMeter from utils.loss import TripletLoss from utils.seri...
StarcoderdataPython
6008
<reponame>HumanBrainProject/secure-data-store # -*- coding: utf-8 -*- """Console script for secure_data_store.""" import click from . import secure_data_store as sds CONFIG='~/.sdsrc' @click.group() def main(): """Wrapper for GoCryptFS""" @main.command() @click.argument('name') @click.option('--config', help='Pa...
StarcoderdataPython
1755984
import unittest import os from dao.unverified_reminder_messages_dao import UnverifiedReminderMessagesDAO class TestUnverifiedReminderMessagesDAO(unittest.TestCase): def setUp(self): self.db_addr = "database/test_db.db" os.popen(f"sqlite3 {self.db_addr} < database/schema.sql") self.unverifie...
StarcoderdataPython
1737030
<filename>tg/migrations/0003_chat_title.py # -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-04-02 03:43 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tg', '0002_auto_20180402_0255'), ] operations = [ migrations.AddField(...
StarcoderdataPython
3246241
print ("Expressie",5, "uitkomst" ,5, "type", type(5)) print ("Expressie",5.0, "uitkomst", 5.0,"type", type(5.0)) print ("Expressie", "5 % 2", "uitkomst", 5 % 2,"type", type(5 % 2)) print ("Expressie","5 > 1", "uitkomst", 5 > 1, "type", type(5 > 1)) print ("Expressie", "'5'","uitkomst", "'5'","type", type('5')) print ("...
StarcoderdataPython
30407
<gh_stars>1-10 from .cvision import * from .models import * from .net import * from .util import *
StarcoderdataPython
160076
<filename>sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/models/resource_requests_py3.py # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License....
StarcoderdataPython
1749294
<filename>patientappointment/settings/celery.py from __future__ import absolute_import import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'patientappointment.settings.production') from django.conf import settings ap...
StarcoderdataPython
1703227
<gh_stars>10-100 """ This file runs a number of commands including data preprocessing """ import argparse import logging from typing import Any, Dict from types import SimpleNamespace # import train first, so that comet initializes before torch from train import define_train_args from evaluate import define_eval_args ...
StarcoderdataPython
1680793
from datetime import datetime from flask import render_template, request from run import app from wxcloudrun.dao import delete_counterbyid, query_counterbyid, insert_counter, update_counterbyid from wxcloudrun.model import Counters from wxcloudrun.response import make_succ_empty_response, make_succ_response, make_err_r...
StarcoderdataPython
9839
import uos as os import time def countdown(): for i in range(5, 0, -1): print("start stubbing in {}...".format(i)) time.sleep(1) import createstubs # import stub_lvgl try: # only run import if no stubs yet os.listdir("stubs") print("stub folder was found, stubbing is not aut...
StarcoderdataPython
1616440
<gh_stars>0 import torch.nn as nn import torch.nn.functional as F from torch import Tensor import torch class ContentLoss(nn.Module): def __init__(self, target,): super(ContentLoss, self).__init__() # we 'detach' the target content from the tree used # to dynamically compute the gradient:...
StarcoderdataPython
1783409
from __future__ import unicode_literals from .models import redshift_backends from ..core.models import MockAWS redshift_backend = redshift_backends['us-east-1'] def mock_redshift(func=None): if func: return MockAWS(redshift_backends)(func) else: return MockAWS(redshift_backends)
StarcoderdataPython
3375998
<filename>mhtportal/celery.py import os import logging from celery import Celery logger = logging.getLogger(__name__) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mhtportal.settings') app = Celery('mhtportal') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.t...
StarcoderdataPython