id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
3372757
<reponame>monash-emu/AuTuMN from autumn.tools.project import Project, ParameterSet, TimeSeriesSet, build_rel_path from autumn.tools.calibration import Calibration from autumn.tools.calibration.priors import UniformPrior, BetaPrior from autumn.tools.calibration.targets import ( NormalTarget, get_dispersion_prior...
StarcoderdataPython
1763591
<gh_stars>1-10 #-*- coding: utf-8 -*- """ saliency_model.py This class implements a shallow convnet saliency prediction model [1]. The input is a 96x96 image, and the output is a 48*48 saliency map. [1] <NAME>., <NAME>., <NAME>., <NAME>. and <NAME>. Shallow and Deep Convolutional Networks for Saliency Prediction...
StarcoderdataPython
1779837
<gh_stars>0 from constants import * from game_utility import * def game_verb_check_results(game): needs = game[IDX_todolist] if len(needs) == 0: message = ' checks the ingredient list, and points out we have everything we need. Well done, team!\n\n' message += 'Congratulations on finishing a Chef Qu...
StarcoderdataPython
1728725
<filename>ax3_OTP_Auth/hotp.py from secrets import token_urlsafe from django.core.cache import cache from django.utils.module_loading import import_string import boto3 import pyotp from . import settings class HOTP: def __init__(self, unique_id: str, digits: int = 6): self._unique_id = unique_id ...
StarcoderdataPython
1635149
<gh_stars>1-10 """Sensor platform for NorwegianWeather.""" import logging from .const import DOMAIN from .entity import NorwegianWeatherEntity _LOGGER: logging.Logger = logging.getLogger(__package__) async def async_setup_entry(hass, entry, async_add_devices): """Setup sensor platform.""" coordinator = hass....
StarcoderdataPython
3268925
<reponame>j-gallistl/reda """Dummy data containers for testing purposes.""" import pandas as pd import numpy as np import reda # construct a simple container using random numbers df = pd.DataFrame(columns=list("abmnr")) df.a = np.arange(1, 23) df.b = df.a + 1 df.m = df.a + 2 df.n = df.b + 2 np.random.seed(0) df.r = n...
StarcoderdataPython
19773
import glob, os import numpy as np import tensorflow as tf import tensorflow.contrib.graph_editor as ge class Flownet2: def __init__(self, bilinear_warping_module): self.weights = dict() for key, shape in self.all_variables(): self.weights[key] = tf.get_variable(key, shape=shape) ...
StarcoderdataPython
4819309
import sys sys.path.append(".") from Model.jsn_drop_service import jsnDrop from time import gmtime class UserManager(object): current_user = None current_pass = None current_status = None current_screen = None stop_thread = False chat_list = None this_user_manager = None def now_tim...
StarcoderdataPython
3335110
<filename>utils.py<gh_stars>1-10 import json from settings import MASS_UNITS def convert_mass(mass, from_unit, to_unit): if from_unit == to_unit: return mass # from kg to ... if from_unit == MASS_UNITS[0]: if to_unit == MASS_UNITS[1]: return mass * 1.e3 elif to_unit ==...
StarcoderdataPython
4807766
# -*- coding: utf-8 -*- """ Created on Tue Jan 21 16:43:56 2020 @author: ssterl """ ########################################## ######### REVUB plotting results ######### ########################################## # REVUB model © 2019 CIREG project # Author: <NAME>, <NAME> # This code accompanies the paper "Turbines ...
StarcoderdataPython
1745844
<reponame>Anderson-VargasQ/mecatronicaUNT_Prog2_Digitalizaci-n_del_Sistema_de_Ventas.- #pip install pymongo --user #pip install dnspython --user import pymongo from editar_excel import list1 import random client = pymongo.MongoClient("mongodb+srv://grupo_hailpy:<EMAIL>/Proyecto?retryWrites=true&w=majority") db ...
StarcoderdataPython
3285100
<filename>src/workers.py import os from time import time from src.db import DB from src.replay import Replay from src.evaluation import Match class File(object): def __init__(self, file_name): self.name = file_name self.processed = False self.last_processed = None def mark_processed(s...
StarcoderdataPython
3206620
# -*- coding:utf-8 -*- # @Time: 2020/1/14 9:13 # @Author: jockwang, <EMAIL> from torch.utils.data import Dataset import torch import logging import pandas as pd from sklearn.model_selection import train_test_split import numpy as np class MyDataset(Dataset): def __init__(self, mode='train', item_size=0, dataset=...
StarcoderdataPython
3359595
""" Check the first value of every ABF to ensure it matches what we expect. """ import sys import pytest import datetime import inspect import numpy as np import glob try: # this ensures pyABF is imported from this specific path sys.path.insert(0, "src") import pyabf except: raise ImportError("couldn'...
StarcoderdataPython
192618
<reponame>shyamjangid07/Reverse-Engineering # Decompiled by HTR-TECH | <NAME> # Github : https://github.com/htr-tech #--------------------------------------- # Source File : pro.py # Time : Sun Feb 14 08:34:41 2021 #--------------------------------------- # uncompyle6 version 3.7.4 # Python bytecode 2.7 # Decompiled f...
StarcoderdataPython
3397291
<gh_stars>1-10 # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from .base import * from .transformer import TransformerPrimitiveBase __all__ = (u'FeaturizationPrimitiveBase', u'Featur...
StarcoderdataPython
136586
<filename>pycws/pycws/urls.py """pycws URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.ho...
StarcoderdataPython
138000
import unittest from monty.multiprocessing import imap_tqdm from math import sqrt class FuncCase(unittest.TestCase): def test_imap_tqdm(self): results = imap_tqdm(4, sqrt, range(10000)) self.assertEqual(len(results), 10000) self.assertEqual(results[0], 0) self.assertEqual(results[...
StarcoderdataPython
3310777
n = int(input()) for i in range (n, 0, -1): print (i)
StarcoderdataPython
3375212
# Copyright (c) 2013, Element Labs and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe def execute(filters=None): sqlq = """select q2.warehouse, q1.coins_expected, q1.coin_count, q1.error, q1.no_of_collections, q2.number, q1.avg_count...
StarcoderdataPython
3229328
import os, cv2 import copy import torch import torch.nn as nn import torch.autograd as autograd import numpy as np import pandas as pd import torch.optim as optim import matplotlib.pyplot as plt from tqdm import tqdm from torch.optim.lr_scheduler import CosineAnnealingLR, StepLR from utils import * from losses.losses i...
StarcoderdataPython
3362913
<gh_stars>0 from cEnum import eAxes, eRect from cConstants import cPlotConstants, cPlot2DConstants import cPlot import wx from matplotlib.figure import Figure from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas class cPlotFrame(cPlot.cPlotFrame): def __init__(self, iParent, **kwargs)...
StarcoderdataPython
101769
<reponame>half-cambodian-hacker-man/lustre #!/usr/bin/env python3 from run_dev import random_secret_key random_secret_key() from microblogging import app, DATABASE_URL from sqlalchemy import create_engine if __name__ == "__main__": app.db.metadata.create_all(create_engine(str(DATABASE_URL)))
StarcoderdataPython
1746506
<reponame>ldolin/shixi0 """ created by ldolin """ """ 1.xpath: 解析工具,用来在xml中查找信息的语言,同样适用于HTML文档的检索 2.辅助工具 Chrome插件:xpath helper 启动/关闭:ctrl+shift+x 3.匹配演示 1.查找bookstore下面所有节点:/bookstore 2.查找book下面所有节点://book 3.查找book下面所有title节点lang属性中为"en"的节点 //book/ti...
StarcoderdataPython
3378809
# -*- coding: utf-8 -*- import torch import numpy as np import matplotlib.pyplot as plt import torch.nn as nn from torch.autograd import Variable from torch.utils.data import Dataset, DataLoader import math from architectures import * import argparse from data_to_dict import get_data from dataset import OurDataset impo...
StarcoderdataPython
163883
<gh_stars>0 from django.db.models import Model
StarcoderdataPython
94601
"""URL Configuration""" from django.urls import path, include from . import views from rest_auth.views import LogoutView urlpatterns = [ path('user/', views.UserDetailsAPIView.as_view(), name='rest_user_details'), path('login/', views.LoginUserView.as_view(), name='account_login'), path('password/change...
StarcoderdataPython
1722088
<reponame>hxhxhx88/futuquant #-*-coding:utf-8-*- from futuquant import * import pandas class ALLApi(object): #上线前测试用例,遍历所有接口保证可执行 def __init__(self): pandas.set_option('max_columns',100) pandas.set_option('display.width',1000) self.host = '127.0.0.1' self.port = 11111 ...
StarcoderdataPython
3320771
from operator import itemgetter class ColorsForCounts(object): """ Maintain a collection of count thresholds and colors with methods to get a color or a CSS name for a count. @param colors: An C{iterable} of space separated "value color" strings, such as ["100 red", "200 rgb(23, 190, 207)", "...
StarcoderdataPython
1603576
from polygraphy.tools.inspect.subtool.model import Model from polygraphy.tools.inspect.subtool.data import Data
StarcoderdataPython
1735464
# author: <NAME> from p5 import * import sympy as sym import mpmath as mp import numpy as np from tkinter import Tk from scipy.spatial import distance import PIL from PIL import Image import argparse import os import csv import mimetypes DEBUG = False parser = argparse.ArgumentParser( description='Custom frame an...
StarcoderdataPython
3328353
<gh_stars>0 # Generated by Django 2.0.9 on 2019-01-21 15:08 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('oauth2_provider', '0008_auto_20181115_1642'), ] operations = [ migrations.AlterField( model_name='grant', ...
StarcoderdataPython
3215441
<gh_stars>10-100 import torch.utils.data as data from PIL import Image import torchvision.transforms as transforms class BaseDataset(data.Dataset): def __init__(self): super(BaseDataset, self).__init__() def name(self): return 'BaseDataset' def initialize(self, opt): pass def get...
StarcoderdataPython
4841002
<gh_stars>1-10 def get_legal_isbn(isbn): if len(isbn) == 10: return cal_10bit_isbn(isbn) elif len(isbn) == 13: return cal_13bit_isbn(isbn) return False def cal_10bit_isbn(isbn): sum = 0 for i in range(9): sum += (10 - i) * (ord(isbn[i]) - ord('0')) n = sum % 11 if n...
StarcoderdataPython
1638414
<reponame>Hoto-Cocoa/openNAMU<filename>route/tool/set_mark/markdown.py from . import tool import datetime import html import re class head_render: def __init__(self): self.head_level = [0, 0, 0, 0, 0, 0] self.toc_data = '' + \ '<div id="toc">' + \ '<span id="toc_title">...
StarcoderdataPython
4838992
<gh_stars>1-10 #!/usr/bin/env python3 import socket import threading import asyncio import time from message import Message import TorzelaUtils as TU # Initialize a class specifically for the round info. # This class will track if a round is currently ongoing or not, the # actual identifying number of the round, the ...
StarcoderdataPython
1791918
<filename>factorioBlueprintVisualizer/draw.py import numpy as np def get_drawing(bbox_width, bbox_height, svg_width_in_mm=250, background_color="#dddddd", metadata_str=None): dwg = [f'<svg baseProfile="tiny" height="{svg_width_in_mm*bbox_height/bbox_width}mm" version="1.2" viewBox="0,0,{bbox_width},{bbox_height}" wi...
StarcoderdataPython
1668884
from filename_database.models import ExperimentType, ChargerDriveProfile, Category, SubCategory, ValidMetadata import re import datetime import itertools def guess_exp_type(file, root): """ This function takes a file as input and guesses what experiment type it is. :param file: :param root: :return...
StarcoderdataPython
1670427
<gh_stars>1-10 from django.shortcuts import render, get_object_or_404, redirect from django.conf import settings from django.contrib.auth.decorators import login_required from django.contrib import messages from django.utils import timezone from collections import defaultdict from tournament.models import Tournament, ...
StarcoderdataPython
97797
# Generated by Django 3.1.3 on 2020-12-07 21:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('dualtext_api', '0007_auto_20201207_2106'), ] operations = [ migrations.AddField( model_name='label', name='color', ...
StarcoderdataPython
1756357
def f(R,G,B): return 2126*R+7152*G+722*B def g(a): if 0 <= a <510000: return "#" elif 510000<= a<1020000: return "o" elif 1020000<=a<1530000: return "+" elif 1530000<=a<2040000: return "-" elif a>=2040000: return "." N,M=list(map(int,input().split())) L=...
StarcoderdataPython
41654
<filename>835.Image-Overlap.py # https://leetcode.com/problems/monotonic-array/description/ # # algorithms # Medium (42.6%) # Total Accepted: 4.8k # Total Submissions: 11.2k # beats 77.52% of python submissions class Solution(object): def largestOverlap(self, A, B): """ :type A: List[List[int]]...
StarcoderdataPython
1763716
<gh_stars>0 from django.db import models from users.models import ModelTemplate,Departments # Create your models here. class Unit(ModelTemplate): name=models.CharField(max_length=50,default=None) class Meta: ordering = ['created_date'] class Product_category(ModelTemplate): name=models.CharField...
StarcoderdataPython
3236341
<gh_stars>1-10 from django.core.wsgi import get_wsgi_application from brouwers.setup import setup_env setup_env() application = get_wsgi_application()
StarcoderdataPython
42753
<gh_stars>10-100 import pygtk import gtk import IO import numpy class TilingMatrix(gtk.Frame): def __init__(self): gtk.Frame.__init__(self, 'Orbital tiling') self.matrix = numpy.array([[1,0,0],[0,1,0],[0,0,1]]) self.set_label('Orbital tiling') self.TileTable = gtk.Table(3,3) ...
StarcoderdataPython
20837
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # # pyre-strict from typing import Union import libcst import libcst.matchers as m from libcst import parse_expression from libcst.codemod imp...
StarcoderdataPython
1679565
from onshape_client.compatible_imports import HTTPServer, HTTPHandler, sendable def start_server(authorization_callback, open_grant_authorization_page_callback): """ :param authorization_callback: The function to call once with the authorization URL response :param open_grant_authorization_page_callback: ...
StarcoderdataPython
4808450
# Copyright The Linux Foundation and each contributor to CommunityBridge. # SPDX-License-Identifier: MIT import json import os from http import HTTPStatus from unittest.mock import Mock, patch, MagicMock import pytest import cla from cla.models.dynamo_models import UserPermissions from cla.salesforce import get_proj...
StarcoderdataPython
1767200
from multiprocessing import Pool import itertools def chunks(l, n): count = 0 for i in range(0, len(l), n): yield l[i: i + n], count count += 1 def multiprocessing(strings, function, cores=16): df_split = chunks(strings, len(strings) // cores) pool = Pool(cores) pooled = pool.map...
StarcoderdataPython
1759439
<reponame>adswa/PyNIDM from .Core import Core from .Project import Project from .Session import Session from .Acquisition import Acquisition from .AssessmentAcquisition import AssessmentAcquisition from .MRAcquisition import MRAcquisition from .AcquisitionObject import AcquisitionObject from .MRObject import MRObject f...
StarcoderdataPython
185311
<gh_stars>0 # coding: utf-8 import os from lib import * from tqdm import tqdm # Vigenere complexity : O(n^4 + n^3 + n^2 + n) # Cesar complexity : O(n^2(n+1)/2 + n) def auto_decipher(code, n): if max(freq(code).items(), key=operator.itemgetter(1))[0] == ' ': method = scytale else: method = vig...
StarcoderdataPython
169572
# Takes RAW arrays and returns calculated OD for given shot # along with the best fit (between gaussian and TF) for ROI. from __future__ import division from lyse import * from pylab import * from common.fit_gaussian_2d import fit_2d from common.traces import * from spinor.aliases import * from time import time from s...
StarcoderdataPython
1665805
<reponame>felliott/modular-odm import os from modularodm import fields, StoredObject from modularodm.query.query import RawQuery as Q from tests.base import ModularOdmTestCase # TODO: The following are defined in MongoStorage, but not PickleStorage: # 'istartswith' # 'iendswith', # 'exact', # 'iexact' cla...
StarcoderdataPython
3338574
<filename>hat/audit/admin.py from django.contrib import admin from .models import Modification class ModificationAdmin(admin.ModelAdmin): date_hierarchy = "created_at" list_filter = ("content_type", "source") search_fields = ("user",) admin.site.register(Modification, ModificationAdmin)
StarcoderdataPython
3215762
<reponame>glomerulus-lab/nonnegative_connectome import scipy.io experiments = ["../data/nonnegative_top_view_top_view_100_tol_e-4_e-5", "../data/nonnegative_flatmap_flatmap_100_tol_e-4_e-5", "data/nonnegative_top_view_top_view_100_tol_e-5", "data/nonnegative_flatmap_flatmap_100_tol_e-5"] for experiment in experiments:...
StarcoderdataPython
171617
<filename>clinicadl/clinicadl/preprocessing/model/squezenet_qc.py import torch import torch.nn as nn import math import torch.utils.model_zoo as model_zoo import torch.nn.init as init from torchvision import models from torch.nn.parameter import Parameter # based on https://github.com/pytorch/vision/blob/master/torch...
StarcoderdataPython
1787417
import datetime import fuel def update_refueling_list(): r0 = fuel.Refueling.all().order('odo').get() if r0.odo > 0: new_r0 = fuel.Refueling(date=datetime.datetime.combine(r0.date.date(),datetime.time(0,0,0)), odo=0, liters=0.0) new_r0.save() rest_liters = list(fuel.Refueling.all().order(...
StarcoderdataPython
1741940
<filename>src/augment.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 21 15:30:54 2019 @author: paskali """ """ Train images augmentation. Load images and binary masks from train folder, and apply various methods for transformation. Finally save them in the train folder. """ import random...
StarcoderdataPython
55825
<reponame>mlyundin/Machine-Learning import numpy as np def load_data(file_name): data = np.loadtxt(file_name, delimiter=',') X = data[:, :-1] y = data[:, -1:] return X, y def transform_arguments(tranformation): def dec(f): def wrapper(*args, **kwargs): t_args = m...
StarcoderdataPython
1611422
<gh_stars>1-10 ''' Created on Jul 9, 2014 @author: oliwa ''' import sys import glob import os from scriptutils import makeStringEndWith, mkdir_p import argparse import numpy as np import traceback #import pylab import matplotlib matplotlib.use('Agg') from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot a...
StarcoderdataPython
3307230
import os, h5py import numpy as np import matplotlib import matplotlib.pyplot as plt import matplotlib.cm as cm from matplotlib.colors import LogNorm, Normalize plt.switch_backend('Agg') import time from vegan import discriminator as build_discriminator from vegan import generator as build_generator #Get ...
StarcoderdataPython
18523
<gh_stars>100-1000 """ Language enumeration. Part of the StoryTechnologies project. June 12, 2016 <NAME> (<EMAIL>) """ from enum import Enum class Language(Enum): # https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes # https://en.wikipedia.org/wiki/ISO_639-2 ENG = 1 # English SPA = 2 # Spanish...
StarcoderdataPython
1622276
from flask import render_template_string, current_app from mistune import create_markdown md_to_unsafe_html = create_markdown(escape=False, renderer="html", plugins=["strikethrough"]) def render_markdown(filename): try: with open(f"{current_app.config['MARKDOWN_PATH']}{filename}", "r") as f: ...
StarcoderdataPython
91249
import tensorflow as tf def ridge(alpha, beta, family): return tf.reduce_sum(tf.square(beta)) def lasso(alpha, beta, family): return tf.reduce_sum(tf.abs(beta)) def network_fusion_x(graph): graph = tf.cast(graph, tf.float32) def tmp(alpha, beta, family): return tf.linalg.trace(tf.matmul(t...
StarcoderdataPython
1699219
from compat.functools import wraps as _wraps from sys import exc_info as _exc_info class _from(object): def __init__(self, EXPR): self.iterator = iter(EXPR) def supergenerator(genfunct): """Implements PEP 380. Use as: @supergenerator def genfunct(*args): try: ...
StarcoderdataPython
4834107
from panda3d.core import * from direct.distributed import DistributedSmoothNodeAI from toontown.toonbase import ToontownGlobals from otp.otpbase import OTPGlobals from direct.fsm import FSM from direct.task import Task class DistributedCashbotBossObjectAI(DistributedSmoothNodeAI.DistributedSmoothNodeAI, FSM.FSM): ...
StarcoderdataPython
1643041
<reponame>pymir3/pymir3 import mir3.data.base_object as bo import mir3.data.metadata as md class DataObject(bo.BaseObject): """Standard base for interface objects. Provides some methods to make it easier to develop interface objects. Attributes: metadata: object of type Metadata with information ...
StarcoderdataPython
1704259
<reponame>matheusccouto/palpiteiro<filename>tests/test_palpiteiro_draft.py """ Unit-tests for palpiteiro.draft """ import os import time import pandas as pd import pytest import palpiteiro import palpiteiro.data import palpiteiro.draft THIS_FOLDER = os.path.dirname(__file__) # Get clubs. clubs = palpiteiro.data.g...
StarcoderdataPython
1704757
#!/usr/bin/env python3 import sys import collections from operator import itemgetter from queue import PriorityQueue __author__ = "<NAME>" __license__ = "MIT" class Node: def __init__(self, left=None, right=None, value=None): self.left = left self.right = right self.value = value @cl...
StarcoderdataPython
3309183
# -*- coding: utf-8 -*- # Author: hpf # Date: 2020/3/1 上午10:31 # File: utils.py # IDE: PyCharm import datetime import ipaddress, glob, json, os, jwt import random import redis import bcrypt from jwt import ExpiredSignatureError, InvalidTokenError from flask import jsonify, current_app from werkzeug.http import HTTP_S...
StarcoderdataPython
1695094
# -*- coding: utf-8 -*- # Visualizzazione dell'andamento della funzione di errore quadratico nella regressione import pandas as pd import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import seaborn as sns # + plt.style.use('fivethirtyeight') plt.rcParams['font.family'] = 'sans-s...
StarcoderdataPython
3296246
<filename>python/isogram/isogram_test.py import unittest from isogram import is_isogram # Tests adapted from `problem-specifications//canonical-data.json` @ v1.6.0 class IsogramTest(unittest.TestCase): def test_empty_string(self): self.assertIs(is_isogram(""), True) def test_isogram_with_only_lowe...
StarcoderdataPython
112701
from requests import Request, Session from requests.exceptions import ConnectionError, Timeout, TooManyRedirects import json import time, datetime import sys import schedule global is_test is_test = False def check_crypto(config_json, last_sent): print("Debug: Job Started " + str(datetime.datetime.utcnow())) total...
StarcoderdataPython
1675927
<filename>protmapper/resources.py import os import csv import zlib import boto3 import logging import argparse import requests import botocore from ftplib import FTP from io import BytesIO, StringIO from urllib.request import urlretrieve from . import __version__ logger = logging.getLogger('protmapper.resources') #...
StarcoderdataPython
1785332
<gh_stars>0 def clear_all_entries(first_name, last_name, street, city, state, zipcode): first_name.delete(0, "end") last_name.delete(0, "end") street.delete(0, "end") city.delete(0, "end") state.delete(0, "end") zipcode.delete(0, "end") first_name.focus_set() def clear_all_widgets(window)...
StarcoderdataPython
4828999
<gh_stars>100-1000 from common import * redis_con = None redis_graph = None class testQueryTimeout(FlowTestsBase): def __init__(self): self.env = Env(decodeResponses=True) # skip test if we're running under Valgrind if self.env.envRunner.debugger is not None or os.getenv('COV') == '1': ...
StarcoderdataPython
3317200
from models.model import Model class Rating(Model): def __init__(self, table_name, is_active, value, user_id, site_id): super(Rating, self).__init__(table_name, is_active) self.value = value self.user_id = user_id self.site_id = site_id def generate_insert(self): retu...
StarcoderdataPython
75241
<reponame>ldworkin/torchx #!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import json import logging import time from datetime import da...
StarcoderdataPython
106244
#!/usr/bin/python3 # IMPORTS import logging from modules import devMode from website import create_app # VARIABLES app = create_app() # MAIN if __name__ == '__main__': logging.basicConfig(filename='/var/log/peon/webui.log', filemode='a', format='%(asctime)s %(thread)d [%(levelname)s] - %(message)s', level=logging...
StarcoderdataPython
1701582
<filename>chap25-functions/ex25.py def break_words(stuff): """ This function will break up words for us First: Print the whole sentence. Second: Broken words will be printed """ result = stuff.split(' ') print("whole sentence ={}".format(stuff)) print("broken words ={}".format(r...
StarcoderdataPython
3333797
<gh_stars>0 # # dbtool for MongoDB # version 1.0.0 # # author: João 'Jam' Moraes # license: MIT # import src as DBTool import json from sys import argv DBTool.app(argv)
StarcoderdataPython
1659844
<filename>inventory/templatetags/indirect.py from django import template from util.validators import ViconfValidators import sys register = template.Library() @register.simple_tag def indirect(variable, key): return variable[key] @register.simple_tag def validatorclass(name): validators = ViconfValidators.VA...
StarcoderdataPython
1799484
<filename>src/run.py # -*- coding: utf-8 -*- """The entry point for mtriage. Orchestrates selectors and analysers via CLI parameters. Modules: Each module corresponds to a web platform API, or some equivalent method of programmatic retrieval. TODO: document where to find selector and analyser design docs...
StarcoderdataPython
1120
<reponame>sebastien-riou/SATL import os import pysatl from pysatl import CAPDU if __name__ == "__main__": def check(hexstr, expected): capdu = CAPDU.from_hexstr(hexstr) if capdu != expected: raise Exception("Mismatch for input '"+hexstr+"'\nActual: "+str(capdu)+"\nExpected: "+str(e...
StarcoderdataPython
11778
<filename>hear_me_django_app/accounts/management/commands/initial_users.py from django.contrib.auth import get_user_model from django.contrib.auth.hashers import make_password from django.core.management.base import BaseCommand from ._private import populate_user User = get_user_model() class Command(BaseCommand): ...
StarcoderdataPython
3361415
#!/usr/bin/python # coding=UTF-8 import sys import json import urllib import psycopg2 import git import itertools import os import datetime import time import re import urllib.request student_amount = 300 #学生代码 db = psycopg2.connect(database="onlinejudge2", user="onlinejudge", password="<PASSWORD>", host="10.2.26.1...
StarcoderdataPython
1765746
import sys from functools import reduce def char_to_bin(c): return "{0:04b}".format(int(c, 16)) def hex_to_bits(hex_string): return ''.join(char_to_bin(c) for c in hex_string) def decode(hex_string): versions = [] packet = hex_to_bits(hex_string) def process_packet(i): def read(n): ...
StarcoderdataPython
3313187
# Copyright (c) 2013-2014 OpenStack Foundation # 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 # # Un...
StarcoderdataPython
3376461
<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- def check(height): if height >= 160: return "John" else: return "Michel" name = "who" print(name) h = 170 name = check(h) print(name)
StarcoderdataPython
119970
<gh_stars>1-10 #! /usr/bin/env python3 import os import string import time from pathlib import Path from subprocess import Popen, DEVNULL def start_openocd(): cmd = ["openocd", "-f", "interface/stlink-v2-1.cfg", "-f", "target/stm32f3x.cfg"] proc = Popen(cmd, stdout=DEVNULL, stderr=DEVNULL) time.sleep(1) ...
StarcoderdataPython
188391
# coding: utf-8 import os import glob import time import json from copy import copy import redis from lib.tools.s_logger import S_logger import config as CONF class Tools_data: # pool def redis_pool(self, SCRenv): try: pool = redis.ConnectionPool( host...
StarcoderdataPython
3364892
<reponame>bcgov/wps-api """ Code common to app.models.fetch """ from enum import Enum class ModelEnum(str, Enum): """ Enumerator for different kinds of supported weather models """ GDPS = "GDPS"
StarcoderdataPython
1612698
# -*- coding: utf-8 -*- info = { "name": "kde", "date_order": "DMY", "january": [ "mwedi ntandi", "jan" ], "february": [ "mwedi wa pili", "feb" ], "march": [ "mwedi wa tatu", "mac" ], "april": [ "mwedi wa nchechi", "apr"...
StarcoderdataPython
1660799
<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, print_function from numpy import array import pytest from PyDSTool import Point from PyDSTool.Generator import LookupTable def test_can_build_lookup_table_and_use_it_for_known_values(): """Functional (a.k.a acc...
StarcoderdataPython
37710
<filename>scripts/review_weblog.py """Process what our weblog has. Run every minute, sigh. """ import sys import subprocess import psycopg2 THRESHOLD = 30 def logic(counts, family): """Should we or should we not, that is the question.""" exe = "iptables" if family == 4 else "ip6tables" for addr, hits i...
StarcoderdataPython
3386612
<gh_stars>10-100 from PyQt5.QtWidgets import QMessageBox, QTreeWidgetItem from PyQt5.QtGui import QColor, QBrush, QPalette, QFont from PyQt5.QtCore import QObject, Qt, pyqtSignal import asyncio import re from base.https.tassomai import Tassomai from base.common import gather_answers class Lookup: def __init__(s...
StarcoderdataPython
133889
"""Top level for tools.""" from .autocorrelation import compute_morans_i from .branch_length_estimator import IIDExponentialBayesian, IIDExponentialMLE from .small_parsimony import fitch_count, fitch_hartigan, score_small_parsimony from .topology import compute_expansion_pvalues
StarcoderdataPython
3364457
# -*- coding: utf-8 -*- import bs4, pyexcel_xls, random, re, requests, time from tqdm import tqdm from collections import OrderedDict data_save = OrderedDict() actor_name = [] actor_id = [] actor_movie_count = [] headers = { # 请求头 'Host': 'movie.douban.com', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64...
StarcoderdataPython
162035
from tests.utils import W3CTestCase class TestGridMarginsNoCollapse(W3CTestCase): vars().update(W3CTestCase.find_tests(__file__, 'grid-margins-no-collapse-'))
StarcoderdataPython
1782643
<gh_stars>1-10 from torch.utils.data import Subset from sklearn.model_selection import train_test_split import json import cv2 import numpy as np import random def tensor_imwrite(img, name): temp = np.transpose(img.cpu().numpy(), (1, 2, 0)) temp = (temp * 255).astype(np.uint8) cv2.imwrite(name, temp) def ...
StarcoderdataPython