id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
1775984
from django.db import models from datetime import datetime # Create your models here. class Pics(models.Model): name = models.CharField(max_length=200); addtime = models.DateTimeField(default=datetime.now) class Meta: db_table = "pics"
StarcoderdataPython
3501688
<reponame>exasol/error-reporting-python<gh_stars>0 from exasol_error_reporting_python.error_message_builder import \ ErrorMessageBuilder def test_message(): message = str(ErrorMessageBuilder("E-ERJ-TEST-1") .message("Test message")) assert message == "E-ERJ-TEST-1: Test message" def te...
StarcoderdataPython
3562743
import json from asyncio import Future, AbstractEventLoop from typing import Optional, Dict from bas_remote.errors import FunctionError from bas_remote.types import Response class BasRunner: _loop: AbstractEventLoop = None _future: Future = None _id: int = 0 def __init__(self, client): """...
StarcoderdataPython
1698929
<reponame>mczwier/zeta<filename>zeta/data/geom.py ''' Created on Oct 31, 2021 @author: mzwier ''' import numpy as np import zeta from .elements import element_label_to_number def normalize_atoms(atoms): return np.array([element_label_to_number(atom) for atom in atoms], dtype=zeta.data.atomi...
StarcoderdataPython
6601421
<reponame>lakepower/Ruby-Bot import asyncio import codecs from discord.ext import commands from cogs.utils import llparser, checks from cogs.utils import twitconn import linkutils, discordutils class Info: max_char = 2000 buffer = 5 code_block = '```' loop = None spoil = list() ...
StarcoderdataPython
154987
# Copyright 2015 Google Inc. 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 law or a...
StarcoderdataPython
1744968
# Copyright 2013-2018 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RShiny(RPackage): """Makes it incredibly easy to build interactive web applications with R...
StarcoderdataPython
6441860
"""The code template to supply to the front end. This is what the user will be asked to complete and submit for grading. Do not include any imports. This is not a REPL environment so include explicit 'print' statements for any outputs you want to be displayed back to the user. Use triple single q...
StarcoderdataPython
4844404
<filename>train_ifo.py import warnings import ifo_model warnings.filterwarnings('ignore', category=DeprecationWarning) import random from pathlib import Path import hydra import numpy as np import torch import torch.utils.data from dm_env import specs from hydra.utils import to_absolute_path import context_changer...
StarcoderdataPython
12861498
<gh_stars>1-10 """In this code we wanna plot real-time data.""" # import random from itertools import count import pandas as pd import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation plt.style.use('fivethirtyeight') x_vals = [] y_vals = [] index = count() def animate(i): ...
StarcoderdataPython
6450919
#!/usr/bin/env python import fileinput import re import numpy as np number = re.compile(r"\d+") lights1 = np.zeros((1000, 1000), np.bool_) lights2 = np.zeros((1000, 1000), np.longlong) for instr in fileinput.input(): tlx, tly, brx, bry = map(int, number.findall(instr)) brx += 1 bry += 1 if "turn ...
StarcoderdataPython
3586801
<filename>app/__init__.py # -*- coding: utf-8 -*- from eve import Eve from flask_socketio import SocketIO from flask_cors import CORS from flask_mail import Mail from flask_security import Security, MongoEngineUserDatastore from models import db, User from settings import SETTINGS io = SocketIO() user_datastore = Mon...
StarcoderdataPython
1837930
<filename>题源分类/剑指offer/python/剑指 Offer 15. 二进制中1的个数.py # 剑指 Offer 15. 二进制中1的个数 # 请实现一个函数,输入一个整数(以二进制串形式),输出该数二进制表示中 1 的个数。例如,把 9 表示成二进制是 1001,有 2 位是 1。因此,如果输入 9,则该函数输出 2。 # 示例 1: # 输入:00000000000000000000000000001011 # 输出:3 # 解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。 # 示例 2: # 输入:000000000000000000...
StarcoderdataPython
11249373
<filename>protocols/migration/migration_reports_611_to_reports_620.py from protocols import reports_6_1_1, reports_6_2_0 from protocols.reports_6_2_0 import UserComment from protocols.migration import BaseMigration class MigrateReports611To620(BaseMigration): old_model = reports_6_1_1 new_model = reports_6_2...
StarcoderdataPython
5142656
colorNames = [[[0, 0, 0], "Schwarz"], [[60, 61, 188], "<NAME>"], [[105, 57, 144], "Schiefergrau"], [[105, 57, 153], "<NAME>"], [[107, 53, 222], "<NAME>"], [[0, 0, 105], "<NAME>"], [[0, 0, 128], "Grau"], [[0, 0, 169], "Dunkelgrau"], [[0, 0, 192], "Silber"], [[0, 0, 211], "Hellgr...
StarcoderdataPython
361639
import redis import requests from django.http import HttpResponse, JsonResponse from django.shortcuts import render from django.views import View import json import urllib.request # Create your views here. class UsersView(View): def __init__(self): self.project_reply={ 'word':'''上传Word后对文档修改,也可替换...
StarcoderdataPython
1902014
<reponame>jrmarino/ravensource --- gnatdoc/docs/users_guide/conf.py.orig 2021-06-18 05:08:58 UTC +++ gnatdoc/docs/users_guide/conf.py @@ -53,7 +53,8 @@ def get_version(): version_file = "../../../VERSION.txt" if os.path.isfile(version_file): return open(version_file).readline() - raise Exception("...
StarcoderdataPython
8036722
<gh_stars>10-100 import os.path import seisgen import obspy import numpy as np import pickle from mtuq.greens_tensor.SPECFEM3D import GreensTensor from mtuq.io.clients.base import Client as ClientBase from mtuq.util.signal import resample class Client(ClientBase): """ SPECFEM3D strain Green's tensor database cl...
StarcoderdataPython
4986616
from aiohttp import web from pydantic import Field, PositiveInt from servicelib.aiohttp.application_keys import APP_SETTINGS_KEY from settings_library.base import BaseCustomSettings class ResourceManagerSettings(BaseCustomSettings): RESOURCE_MANAGER_RESOURCE_TTL_S: PositiveInt = Field( 900, descr...
StarcoderdataPython
11343389
<filename>elasticsearch_django/migrations/0009_searchquery_query_type.py # Generated by Django 2.2 on 2019-04-11 17:15 from django.db import migrations, models from ..models import SearchQuery class Migration(migrations.Migration): dependencies = [("elasticsearch_django", "0008_searchquery_search_terms")] ...
StarcoderdataPython
3522099
# Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE.md file in the project root for full license information. # solver.py : Defines the base class for all PDP Solvers as well as the various inherited solvers. import os import torch import torch.nn as nn import numpy...
StarcoderdataPython
8109437
<reponame>yottaawesome/ml-nanodegree-stuff<gh_stars>0 # Import statements from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import accuracy_score import pandas as pd import numpy as np # Read the data. data = np.asarray(pd.read_csv('3-3-16-decision-trees-in-sklearn.csv', header=None)) # Ass...
StarcoderdataPython
12861190
from searcher import CLIPSearcher from utils import get_args if __name__ == "__main__": args = get_args() cs = CLIPSearcher(device=args.device, store_path=args.store_path) cs.load_dir(args.dir, save_every=args.save_every, recursive=args.recursive, load_new=(not args.dont_load_new)) cs.search(texts=args...
StarcoderdataPython
3444766
# Copyright (c) 2020, DjaoDjin inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and t...
StarcoderdataPython
6461730
#!/usr/bin/env python # encoding: utf-8 # # Copyright (c) 2014 <NAME> <<EMAIL>> # # MIT Licence. See http://opensource.org/licenses/MIT # # Created on 2014-02-15 # """ A Python helper library for `Alfred 2 <http://www.alfredapp.com/>`_ Workflow authors. Alfred Workflows typically take user input, fetch data from the ...
StarcoderdataPython
3354047
<reponame>Mostofa-Najmus-Sakib/Applied-Algorithm<gh_stars>1-10 """ LeetCode Problem: 895. Maximum Frequency Stack Link: https://leetcode.com/problems/maximum-frequency-stack/ Language: Python Written by: <NAME> Time Complexity: O(1) Space Complexity: O(N) """ class FreqStack: def __init__(self): self.freq...
StarcoderdataPython
3420207
from app import db class User(db.Model): id = db.Column(db.Integer, primary_key = True) # Login email = db.Column(db.String, unique = True, nullable = False) password = db.Column(db.String, nullable = False) #Info name = db.Column(db.String) cpf = db.Column(db.String) gender = db.Colum...
StarcoderdataPython
333179
<filename>pygments/formatters/groff.py """ pygments.formatters.groff ~~~~~~~~~~~~~~~~~~~~~~~~~ Formatter for groff output. :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import math from pygments.formatter import Formatter from pygme...
StarcoderdataPython
9652336
#/* # * Copyright (C) 2013 <NAME> # * # * # * This Program 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 2, or (at your option) # * any later version. # * # * This Program is dis...
StarcoderdataPython
3445907
<reponame>PacktPublishing/MicroPython-Cookbook<filename>Chapter11/01_remount.py import storage storage.remount('/', False)
StarcoderdataPython
4968091
from .validation import validation_handler
StarcoderdataPython
5163219
# -*- coding: utf-8 -*- # Copyright (c) 2015, <NAME>, <NAME> # Licensed under the BSD 3-clause license (see LICENSE.txt) """ Classes in this module enhance Brownian motion covariance function with the Stochastic Differential Equation (SDE) functionality. """ from .brownian import Brownian import numpy as np class sd...
StarcoderdataPython
1850206
#!/usr/bin/env python class Bunch( dict ): def __init__( self, *args, **kwargs ): dict.__init__( self, *args, **kwargs ) self.__dict__ = self def __getstate__( self ): return self def __setstate__( self, state ): self.update( state ) self.__dict__ = self if __name...
StarcoderdataPython
92876
<filename>robustness/run_robustness.py """This script runs the robustness analysis.""" import os from pathlib import Path import respy as rp from robustness_library import distribute_tasks from robustness_library import eval_eu_loss from robustness_library import eval_experience_effect_ambiguity from robustness_librar...
StarcoderdataPython
9683682
<gh_stars>1-10 # -*-coding:utf-8-*- __author__ = "<NAME>" PLUGIN_NAME = "aliyun_oss_plugin" CONFIG = { "ACCESS_KEY":{ "info":"ACCESS KEY ID", "value_type":"string", "value":"<Your AK ID>", "reactivate":True }, "SECRET_KEY":{ "info":"SECRET KEY", "value_type"...
StarcoderdataPython
11265383
"""module for running the kn_build pipeline. Contains utilities for running pipeline steps and checking their statuses. Contains module functions:: main_parse_args() get_status(chronos_url, statuses=False) wait_for_success(chronos_url, interval=30) wait_for_port(port, host="localhost", interval=30) ...
StarcoderdataPython
8195368
#!/usr/bin/env python """Test for the ee.__init__ file.""" import six import unittest import ee from ee import apitestcase class EETestCase(apitestcase.ApiTestCase): def setUp(self): ee.Reset() def testInitialization(self): """Verifies library initialization.""" def MockSend(path, params, unus...
StarcoderdataPython
8197761
from tqdm import tqdm from pytorch_metric_learning import miners from pytorch_metric_learning import losses from torch.optim import Adam def train_metric(net, loader, device="cpu", epochs=50, lr=3e-4): miner = miners.MultiSimilarityMiner() contrastive_loss = losses.ContrastiveLoss() optim = Adam(net.param...
StarcoderdataPython
290634
import os import sys from time import sleep import requests class Cracker(): def __init__(self, url, file, login, submit, params_names, fail_phrase): self.submit = submit self.url = url self.fail = fail_phrase self.file_name = file if os.path.exists(file): # Read...
StarcoderdataPython
3368499
<filename>code/style_gan/StyleGAN_PyTorch/torchvision_sunner/transforms/simple.py from torchvision_sunner.utils import INFO from torchvision_sunner.constant import * import numpy as np import torch """ This script define some operation which are rather simple The operation only need to call function once (with...
StarcoderdataPython
6507109
import os inputPath = r'D:\adclassifier\labelled_dataset\political\images2' #frame = 'frame-%02d.png' % (frameNum) for videoFolder in os.listdir(inputPath): countframe = len(os.listdir(os.path.join(inputPath, videoFolder))) selectframe = ['frame-%02d.png' % (countframe), 'frame-%02d.png' % (countframe - 1), '...
StarcoderdataPython
4817091
import sys from datetime import datetime from sqlalchemy import INTEGER, TIMESTAMP, VARCHAR, Column, create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from . import config reload(sys) sys.setdefaultencoding('utf-8') Base = declarative_base() class Messag...
StarcoderdataPython
11377650
<reponame>marcoshsq/python_practical_exercises # Exercise 061 - Arithmetic Progression v2.0 """Redo CHALLENGE 051, reading the first term and the ratio of an AP, showing the first 10 terms of the progression using the while structure.""" # 1. We'll ask the user to input the first term of our AP first_term = int(inpu...
StarcoderdataPython
3518240
<reponame>JosueHernandezR/TTR<gh_stars>0 from typing import Any, List from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from app import crud, models, schemas from app.api import deps router = APIRouter() @router.post("/", response_model=schemas.Prediction) def createPrediction(...
StarcoderdataPython
6455082
<reponame>pszafer/core<filename>homeassistant/components/risco/entity.py """A risco entity base class.""" from homeassistant.helpers.entity import Entity class RiscoEntity(Entity): """Risco entity base class.""" def __init__(self, coordinator): """Init the instance.""" self._coordinator = coo...
StarcoderdataPython
4911164
import requests import pandas as pd import json def Test(): head = { "Accept": "*/*", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-CN,zh;q=0.9", "Connection": "keep-alive", "Cookie": "st_si=33930137927479; FundWebTradeUserInfo=<KEY>; qgqp_b_id=07e364420df...
StarcoderdataPython
3336294
import grblas import atexit import itertools import pytest def pytest_configure(config): backend = config.getoption("--backend", "suitesparse") blocking = config.getoption("--blocking", True) record = config.getoption("--record", False) grblas.init(backend, blocking=blocking) print(f'Running test...
StarcoderdataPython
242219
TESTS_BUNDLE_MODEL = 'TestBundle' TESTS_BUNDLE_APP = 'tests_bundle_app' TESTS_DYNAMIC_APP = 'tests_dynamic_app'
StarcoderdataPython
6676648
<reponame>victoraccete/data_science_projects # -*- coding: utf-8 -*- import pandas as pd suicide_rates = pd.read_csv('data_science_projects/brazil_suicides_plot/master.csv') br_rates = suicide_rates[suicide_rates['country']=='Brazil'][suicide_rates['sex'] == 'male'][suicide_rates['age']=='15-24...
StarcoderdataPython
3597884
""" * https://leetcode.com/problems/concatenated-words/ """ def solution1(words): """ for w in words -> can we break w by rest of words? fn(w, rest_words) if prefix in rest_words and is prefix of w -> fn(w-prefix, rest_words - prefix) """ can_break_cache = {w: True for w in words} def can_...
StarcoderdataPython
5111058
<reponame>bilabon/paymentwall-python from paymentwall.httpaction import Httpaction from paymentwall.base import Paymentwall import json class ApiObject(Paymentwall, Httpaction): API_BRICK_SUBPATH = 'brick' API_OBJECT_CHARGE = 'charge' API_OBJECT_SUBSCRIPTION = 'subscription' API_OBJECT_ONE_TIME_TOKEN ...
StarcoderdataPython
1995270
<filename>calculateBudget.py import datetime import json from calendar import monthrange from math import ceil def main(): # Load the budgeting data with open('BudgetingData.json') as json_data: financeData = json.load(json_data) # Tracking variable for the budget budget = 0 # For loop ...
StarcoderdataPython
3206386
<gh_stars>0 """ Sum Lists: You have two numbers represented by a linked list, where each node contains a single digit.The digits are stored in reverse order, such that the 1 's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list. EXAMPLE Input:(7-> 1 -> 6) +...
StarcoderdataPython
3275289
<filename>leaguebot_version_0.py<gh_stars>0 from riotwatcher import RiotWatcher from requests import HTTPError import os watcher = RiotWatcher(str(os.environ.get("LOL_API_KEY"))) ''' my_region = 'na1' me = watcher.summoner.by_name(my_region, 'joe joe joe joe') print(me) # all objects are returned (by de...
StarcoderdataPython
6418096
"""Test cases for the `inputs.heroku` module."""
StarcoderdataPython
5137443
# Copyright 2016-present CERN – European Organization for Nuclear Research # # 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...
StarcoderdataPython
6476066
<gh_stars>1-10 from testarch import * class TunnelDataCollector(SealOutput): def __init__(self): super(TunnelDataCollector, self).__init__("TunnelDataCollector") self.useFunction.value = "tunnelDataCollectorSend(&tunnelDataCollectorPacket, sizeof(tunnelDataCollectorPacket))" tunnelDataColl = Tunne...
StarcoderdataPython
325914
<filename>robustness_metrics/datasets/base.py # coding=utf-8 # Copyright 2021 The Robustness Metrics Authors. # # 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/lic...
StarcoderdataPython
5107713
<reponame>cleitonleonel/pix-code import re import os import sys import crc16 import base64 import qrcode from unicodedata import normalize from amzqr import amzqr from PIL import Image from io import BytesIO def validate_cpf(numbers): cpf = [int(char) for char in numbers if char.isdigit()] if len(cpf) != 11: ...
StarcoderdataPython
3509022
def ObserverProxy(method_names): class Proxy: def __init__(self): self._observers = [] def add_observer(self, observer): self._observers.append(observer) def remove_observer(self, observer): self._observers.remove(observer) def create_method_proxy(met...
StarcoderdataPython
52603
<filename>pydis_site/constants.py import os GIT_SHA = os.environ.get("GIT_SHA", "development") GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN") # How long to wait for synchronous requests before timing out TIMEOUT_PERIOD = int(os.environ.get("TIMEOUT_PERIOD", 5))
StarcoderdataPython
195532
<reponame>gabinguo/bbx import json import random import argparse def read_filename(filename=""): with open(filename, 'r') as f: queries = json.load(f)["data"] return queries def sample_from_large_dataset(queries, count=2000): sample_size = min(len(queries[:count]), count) return random.sampl...
StarcoderdataPython
225058
<reponame>tavor118/pythonjunior from django import template from .. import models register = template.Library() @register.simple_tag def get_submenu(): """ Return items for submenu """ submenu = models.MainCategory.objects.all() return submenu @register.simple_tag def get_tags(): """ R...
StarcoderdataPython
6524476
# Copyright 2020 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
260483
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' utils.py (c) <NAME> 12 December, 2015 Utility functions. ''' from __future__ import absolute_import from fsed.compat import PY3, string_type import sys def open_file(filename, mode='rb'): """ Opens a file for access with the given mode. This function t...
StarcoderdataPython
3453511
<reponame>KM3NeT/km3pipe # Filename: shell.py # pylint: disable=C0103 """ Some shell helpers """ import os import subprocess from .tools import lstrip from .logger import get_logger from subprocess import DEVNULL # py3k __author__ = "<NAME>" __copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration."...
StarcoderdataPython
8041614
import tacoma as tc from tacoma.drawing import draw_edges from tacoma.analysis import temporal_network_group_analysis import matplotlib.pyplot as pl from tacoma.model_conversions import estimate_ZSBB_args from tacoma.model_conversions import estimate_flockwork_P_args from tacoma.model_conversions import estimate_dynam...
StarcoderdataPython
3354080
import datetime import decimal import uuid from dateutil.relativedelta import relativedelta from django.db import transaction from django.db.models import Sum from django.http import HttpResponse from django.utils.translation import ugettext_lazy as _ from django_filters.rest_framework import DjangoFilterBackend from ...
StarcoderdataPython
11388210
# This file is generated by setup.py. DO NOT EDIT! from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from .onnx_operators_onnx_torch_ml_pb2 import * # noqa
StarcoderdataPython
165451
from django.contrib.postgres.fields import ArrayField from django.db import models from bumblebee.buzzes.models import Buzz, Rebuzz from bumblebee.users.models import CustomUser class IdDateField(models.Model): """ """ userid = models.PositiveIntegerField() date = models.DateTimeField() class Abstract...
StarcoderdataPython
8102586
""" This script creates a shape uses 10 minute averages from weather data to create a merged predictive shape for downed wildlife monitoring. """ import os import datetime import sys import math import arcpy from arcpy import env #Set environmental variables env.workspace = sys.path[0] arcpy.env.overwriteOutput = T...
StarcoderdataPython
8026673
# Merge action_movies to the scifi_movies with right join action_scifi = action_movies.merge(scifi_movies, on='movie_id', how='right', suffixes=('_act','_sci')) # From action_scifi, select only the rows where the genre_act column is null scifi_only = action_scifi[action_scifi['g...
StarcoderdataPython
4929915
<reponame>billyeatcookies/Biscuit<filename>src/lib/components/editor_types/editor/utils/binder.py class Binder: def __init__(self, master, bindings=None): self.base = master.base self.master = master self.bindings = bindings if bindings: self.bind_all() def bind(se...
StarcoderdataPython
5197176
<gh_stars>1000+ from collections import defaultdict from ...core.models import EventPayload from ...webhook.models import WebhookEvent from ..core.dataloaders import DataLoader class PayloadByIdLoader(DataLoader): context_key = "payload_by_id" def batch_load(self, keys): payload = EventPayload.objec...
StarcoderdataPython
3320363
<reponame>JexPY/filemanager-fastapi import os from pathlib import Path from fastapi.responses import FileResponse from fastapi import HTTPException,status def response_image_file(filename:str, image_type:str): validPath = { 'original': os.environ.get('IMAGE_ORIGINAL_LOCAL_PATH'), 'thumbnail': os.e...
StarcoderdataPython
6433441
import discord from redbot.core import commands from discord_slash import SlashCommand, cog_ext, SlashContext from discord_slash.utils.manage_commands import remove_all_commands, create_option from discord_slash.model import SlashCommandOptionType from redbot.core.utils.menus import menu, prev_page, next_page from disc...
StarcoderdataPython
3240161
<reponame>LINXNet/pyOCNOS """ This test module covers tests cases for function pyocnos.diff.normalize_tree() """ from lxml import etree from pyocnos.diff import normalize_tree def test_normalize_tree(): """ Ensure normalize_tree() wipe off name spaces, prefixes, redundant white spaces and new lines. """...
StarcoderdataPython
6564300
<gh_stars>0 # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2015-2016, <NAME> <EMAIL> # pylint: disable=too-many-public-methods # pylint: disable=unus...
StarcoderdataPython
3262518
#!/usr/bin/python # -*- coding: utf-8 -*- import argparse import base64 import os import sys import cs_methods import helpers from datetime import datetime # GLOBALS/PARAMS HOME_DIR = os.path.expanduser('~') DIR_PATH = os.path.join(HOME_DIR, '.bulkstrike') CRED_PATH = os.path.join(DIR_PATH, "credentials") TOKEN_PATH ...
StarcoderdataPython
8083366
#!/usr/bin/env python # say hello world and asks for name. print('Hello world!') print('What\'s your name') name = input() print('Nice to meet you, ' + name) print('The length of your name is: ' + str(len(name))) print('What\'s your age?') age = input() print('You will be ' + str(int(age) + 1) + ' in a year.')
StarcoderdataPython
3454460
<filename>stablab/finite_difference_code/approximate.py # -*- coding: utf-8 -*- """ Created on Tue May 30 14:01:31 2017 @author: <NAME> """ import numpy as np from matplotlib import pyplot as plt np.set_printoptions(threshold=np.nan) """******************************************** Initializing functions...
StarcoderdataPython
12821684
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 2 11:39:57 2018 @author: <NAME> @Contains : Pre-processing functions """ import pandas as pd import numpy as np import json def mapprice(v): if pd.isnull(v): return [ np.nan] try: vv = v.split('-') p0 = vv[0].str...
StarcoderdataPython
1990769
<reponame>piwai/mail-recovery #!/bin/env python3 import os import sys HEADER_THRESHOLD = 5000 # 2 matches within 5k of data are likely the same mail CHUNK_MAX_SIZE = 50 * 1000 * 1000 # Conservative limit of 50 MB per chunk CHUNK_DIR = "chunks" if len(sys.argv) < 3: print("Usage: extract-chunks.py <audit_file.t...
StarcoderdataPython
8067446
<gh_stars>10-100 from typing import Tuple, Optional import warnings import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import pytorch_lightning as pl import torchmetrics from ._total_ce_loss import TotalCrossEntropyLoss from ..dataset import SequenceBatch from ._base_single_sequence...
StarcoderdataPython
11230150
<reponame>jsmnbom/htxaarhuslan # -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-08-17 14:38 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('main', '0042_lan_payment_man...
StarcoderdataPython
4921865
"""Utility module for BenchBuild experiments.""" import os import random import traceback import typing as tp from abc import abstractmethod from pathlib import Path from benchbuild import source from benchbuild.experiment import Experiment from benchbuild.project import Project from benchbuild.utils.actions import S...
StarcoderdataPython
3421742
# OpenMV Unit Tests. # import os, sensor, gc TEST_DIR = "unittest" TEMP_DIR = "unittest/temp" DATA_DIR = "unittest/data" SCRIPT_DIR = "unittest/script" if not (TEST_DIR in os.listdir("")): raise Exception('Unittest dir not found!') print("") test_failed = False def print_result(test, passed): s = ...
StarcoderdataPython
9648176
<reponame>dagnelies/restfs<filename>old/parseftp.py import dateutil.parser import sys def parseList(raw): files = [] for line in raw.splitlines(): files.append(parseLine(line)) return files def parseLine(line): # mode links owner group size datetime name # drw...
StarcoderdataPython
4929300
<gh_stars>100-1000 #!/usr/bin/env python # -*- coding: utf_8 -*- import logging from logging.handlers import RotatingFileHandler import os # logPath = os.getcwd() + os.path.sep + "logs" # if not os.path.exists(logPath): # os.makedirs(logPath) # fh = RotatingFileHandler("logs/scons.log", # ...
StarcoderdataPython
8078700
import glob import os import matplotlib import torch from torch.nn.utils import weight_norm matplotlib.use("Agg") import matplotlib.pylab as plt from matplotlib import colors all_colors = [*colors.BASE_COLORS.values(), *colors.TABLEAU_COLORS.values(), *colors.CSS4_COLORS.values()] all_colors = all_colors *...
StarcoderdataPython
6649266
from agents.models import Agent from django.core.management.base import BaseCommand class Command(BaseCommand): help = "Find all agents that have a certain software installed" def add_arguments(self, parser): parser.add_argument("name", type=str) def handle(self, *args, **kwargs): search...
StarcoderdataPython
3263427
import time import sys import platform from PyQt5 import QtWidgets from PyQt5 import QtGui from PyQt5 import uic from PyQt5 import QtCore from PyQt5.QtCore import pyqtSlot from win10toast import ToastNotifier import threading def notify(): if( platform.system() == 'Windows' and platform.release() == '10'): ...
StarcoderdataPython
3507485
#!/usr/bin/env python """ .. py:currentmodule:: FileFormat.Results.test_XraySpectraAtomEmittedDetectedLines .. moduleauthor:: <NAME> <<EMAIL>> Tests for the module `XraySpectraAtomEmittedDetectedLines`. """ # Script information for the file. __author__ = "<NAME> (<EMAIL>)" __version__ = "" __date__ = "" __copyright__...
StarcoderdataPython
6698753
<reponame>RangeKing/PaddleViT<filename>image_classification/BEiT/lr_decay.py # Copyright (c) 2021 PPViT 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 # # h...
StarcoderdataPython
5169305
<reponame>pantaryl/adventofcode<gh_stars>1-10 from shared import * # Input data is in INPUT_DATA. #INPUT_DATA = [int(x) for x in INPUT_DATA] costs = { 'A': 1, 'B': 10, 'C': 100, 'D': 1000, } room1T, room2T, room3T, room4T = tuple(parse.parse('###{}#{}#{}#{}###', INPUT_DATA[2]).fixed) room1B, room2B, ...
StarcoderdataPython
4938332
<reponame>c-rainbow/nurse-scheduling import os import tkinter as tk from tkinter import filedialog from tkinter import messagebox from tkinter import scrolledtext from tkinter import ttk from shiftscheduler.excel import input as excel_input from shiftscheduler.excel import output as excel_output from shiftscheduler.g...
StarcoderdataPython
3487691
<reponame>Syndra/Ambari-source<gh_stars>1-10 """ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Versi...
StarcoderdataPython
3570986
def hamiltonian(N,J,sigma): import numpy as np diag = np.random.randn(N)*sigma off_diag = np.ones((N-1))*J H = np.diag(off_diag,1) + np.diag(off_diag,-1) + np.diag(diag,0) return H if __name__ == '__main__': hamiltonian(4,10,10)
StarcoderdataPython
4926807
<gh_stars>1-10 Mongo=open("mongodb.txt","r").readline()
StarcoderdataPython
3264070
#coding: utf-8 import json DEBUG = False class JSWrapper(): def __init__(self, prev, to_add_js='', post=''): if hasattr(prev, 'target_webview'): self.target_webview = prev.target_webview prev_js = prev.js post_js = prev.post_js else: self.target_webview = prev prev_js = 'ele...
StarcoderdataPython