id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
3519081
import numpy as np import pandas as pd from enlopy.utils import make_timeseries from enlopy.generate import (add_noise, gen_daily_stoch_el, gen_load_from_daily_monthly, gen_load_sinus, gen_demand_response, disag_upsample, clean_convert, countweekend_days_per_month, ...
StarcoderdataPython
41360
<filename>random_geometry_points_service/app.py """Entry module that inits the flask app. """ from flask import Flask from .endpoints.api import init_api def create_app(): """Create the flask app and initialize the random geometry points api. Returns: Flask: The initialized flask app """ fla...
StarcoderdataPython
3577150
import os, sys sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) try: from setuptools import setup has_setuptools = True except ImportError: from distutils.core import setup has_setuptools = False if sys.version_info >= (3, ): if not has_setuptools: raise Exception('Python3 su...
StarcoderdataPython
1621528
<gh_stars>0 import setuptools import os with open("README.md", "r", encoding='utf-8') as f: long_description = f.read() dirname = os.path.dirname(__file__) with open('pysg/version.py', 'r') as f: exec(f.read()) setuptools.setup( name="pysg", version=__version__, author="<NAME>", author_email...
StarcoderdataPython
3271823
#%% import numpy as np #%% def Custom_Convolve2D(image, kernel, padding=0, strides=1): # Cross Correlation # kernel = np.flipud(np.fliplr(kernel)) ## Put your code here. # Gather Shapes of Kernel + Image + Padding xKernShape = kernel.shape[0] yKernShape = kernel.shape[1] xImgShape = image.s...
StarcoderdataPython
1750724
import os import glob import pandas as pd import dask.dataframe as dd import pathlib from datetime import datetime, timedelta def read_data(dir_name, usecols, dtype, date_range=None): """ Return a dataframe with concatenated data. Set timestamp as index. Parameters: dir_name (str): directory ...
StarcoderdataPython
12848758
import frappe from datetime import * @frappe.whitelist() def add_leave_encashment(doc, method): from_date = (datetime.strptime(doc.start_date, "%Y-%m-%d")).date() to_date = (datetime.strptime(doc.end_date, "%Y-%m-%d")).date() salary_structure = frappe.db.sql(""" SELECT * FROM `tabSalary Structure Assignme...
StarcoderdataPython
8158247
from django.contrib import admin from .models import Map_DB # Register your models here. admin.site.register(Map_DB)
StarcoderdataPython
8076826
import numpy import subprocess from tensorflow.keras.utils import to_categorical from sklearn.model_selection import train_test_split def get_dataset(): X = [] Y = [] labels = ['nomalware', 'malware'] # num_classes is how many class you in your data for index, name in enumerate(labels): ...
StarcoderdataPython
3565645
<reponame>NotJoeMartinez/python3-groupme-tools from collections import defaultdict import sys from importlib import reload reload(sys) import json import datetime def main(): """ Usage: python posts-by-user.py [filename.json] Assumes filename.json is a JSON GroupMe transcript. """ if len(sys.a...
StarcoderdataPython
1858627
from __future__ import division, print_function import numpy as np class BCTParamError(RuntimeError): pass def teachers_round(x): ''' Do rounding such that .5 always rounds to 1, and not bankers rounding. This is for compatibility with matlab functions, and ease of testing. ''' if ((x > 0) a...
StarcoderdataPython
5162334
<filename>python/example_requests.py import datetime from confidentcannabis import ConfidentCannabis if __name__ == '__main__': api_key = 'PUT-YOUR-API-KEY-HERE' api_secret = 'PUT-YOUR-API-SECRET-HERE' cc = ConfidentCannabis(api_key, api_secret, api_stage='sandbox') client_id = 1 order_id = '1610...
StarcoderdataPython
1892318
#!/usr/bin/env python3 from __future__ import print_function import os import sys import math from PyQt5.QtCore import * from PyQt5.QtGui import * from .util import custom_qt_items as cqt from .util import file_io from .util.mygraphicsview import MyGraphicsView sys.path.append('..') import qtutil import pickle impor...
StarcoderdataPython
119616
<filename>Cartwheel/lib/Python26/Lib/site-packages/OpenGL/GL/ARB/vertex_shader.py<gh_stars>0 '''OpenGL extension ARB.vertex_shader This module customises the behaviour of the OpenGL.raw.GL.ARB.vertex_shader to provide a more Python-friendly API ''' from OpenGL import platform, constants, constant, arrays from OpenGL...
StarcoderdataPython
5129368
from lgsf.councillors.scrapers import CMISCouncillorScraper class Scraper(CMISCouncillorScraper): base_url = "http://democracy.bolton.gov.uk/cmis5/People.aspx"
StarcoderdataPython
3373381
# problem67.py r = [ ] file = open("problem67.txt", "r") for x in file: r.append([int(i) for i in x.split(" ")]) for i, j in [(i, j) for i in range(len(r) -2, -1, -1) for j in range(i + 1)]: r[i][j] += max([r[i + 1][j], r[i + 1][j + 1]]) print(r[0][0])
StarcoderdataPython
154803
<reponame>samwel2000/portfolio-backend<filename>blog/urls.py<gh_stars>0 from django.urls import path from .views import * app_name = 'blog_api' urlpatterns = [ path('posts-category/', PostCategories.as_view(), name="posCategories"), path('posts/', PostList.as_view(), name="postlist"), path('posts/<str:fil...
StarcoderdataPython
8016703
r""" 封装处理NLP各个任务的数据 """ import torch from torch.utils.data import Dataset class DatasetCLF(Dataset): def __init__(self, data, tokenizer, max_len=512, load_label=True, **kwargs): """封装文本分类数据集,现在仅支持二分类和多分类,暂不支持多标签分类 ...
StarcoderdataPython
11229907
from google.appengine.api import urlfetch import urllib from helpers import authorization import logging #returns the response object def request_twiml(Account, Url, Method, Payload): if Method == 'GET': url = Url + '?' +'&'.join(k+'='+v for k,v in Payload.iteritems()) Twilio_Signature = authorization.create_twili...
StarcoderdataPython
335082
<filename>awsm/keys/__init__.py import os from .exceptions import KeyNotFoundError from .validators import KEY_SCHEMA from awsm.storage.file_storage import USER_KEYS_CFG from awsm.utils import load_from_yaml from voluptuous.humanize import validate_with_humanized_errors class KeyManager(object): def __init__(sel...
StarcoderdataPython
51166
<gh_stars>0 import overhang def test_Overhang(): oh_aaa = overhang.Overhang("AAA") assert oh_aaa.overhang == "AAA" assert oh_aaa.overhang_rc == "TTT" assert oh_aaa.has_multimer is True # tests count_max_repeat() assert oh_aaa.is_good() is True assert oh_aaa.gc_content == 0 oh_ttaa = over...
StarcoderdataPython
3270159
<gh_stars>0 # # 28. Implement strStr() # # Implement strStr(). # # Return the index of the first occurrence of needle in haystack, or -1 if # needle is not part of haystack. # # Example 1: # Input: haystack = "hello", needle = "ll" # Output: 2 # # Example 2: # Input: haystack = "aaaaa", needle = "bba" # ...
StarcoderdataPython
6669317
import logging from .... import app_settings from . import elastic logger = logging.getLogger('django_sso_app') ELASTICSEARCH_INDEX_URL = app_settings.EVENTS_HOST + '/{}/_search'.format(app_settings.EVENTS_INDEX) def fetch_event_type_events(event_type: str, from_date: str, jwt: str = None, apikey: str = None) -> (o...
StarcoderdataPython
9626517
<filename>Programas de exercicios/exercicio078.py<gh_stars>0 m = [] n1 = [] n2 = [] for c in range(0,5): m.append(input(f'digite o numero na posição {c}: ')) print(f'Sua lista foi {m}') c = 0 for r in m: if c == 0: maior = int(r) menor = int(r) else: if maior < int(r): m...
StarcoderdataPython
372845
<filename>pyxl/scripts/parse_file.py<gh_stars>100-1000 #!/usr/bin/env python import sys from pyxl.codec.transform import pyxl_invert_string, pyxl_transform_string if __name__ == '__main__': invert = invertible = False if sys.argv[1] == '-i': invertible = True fname = sys.argv[2] elif sys....
StarcoderdataPython
10473
<reponame>vault-the/changes from changes.api.base import APIView from changes.lib.coverage import get_coverage_by_build_id, merged_coverage_data from changes.models.build import Build class BuildTestCoverageAPIView(APIView): def get(self, build_id): build = Build.query.get(build_id) if build is ...
StarcoderdataPython
3598164
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: spirrobe -> github.com/spirrobe/ """ def ConcPerCCM(bins, windspeed=[1], # in m/s samplearea=0.298, # as area in square millimeters samplefrequency=10, # as Hz combined=True): import numpy ...
StarcoderdataPython
3561098
import django.db.models.deletion from django.db import migrations, models from djangocms_blog.models import thumbnail_model class Migration(migrations.Migration): dependencies = [ ("djangocms_blog", "0020_thumbnail_move4"), ] operations = [ migrations.AlterField( model_name=...
StarcoderdataPython
6421165
<reponame>MinisterioPublicoRJ/api-cadg from django.http import Http404 from django.shortcuts import get_object_or_404 from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_page from rest_framework.generics import ( GenericAPIView, RetrieveAPIView, ListAPIView )...
StarcoderdataPython
85252
import warnings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module from gears.asset_handler import BaseAssetHandler from gears.finders import BaseFinder _cache = {} def _get_module(path): try: return import_module(path) except ImportError as e:...
StarcoderdataPython
4856947
<reponame>sourav-majumder/qtlab<filename>instrument_plugins/ThorlabsFTD2XX.py<gh_stars>0 # # Copyright (C) 2011 <NAME> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # v...
StarcoderdataPython
3440611
<reponame>vkareh/managed-tenants-cli<filename>managedtenants/bundles/addon_bundles.py import logging from functools import lru_cache from pathlib import Path import jsonschema import semver import yaml from sretoolbox.utils.logger import get_text_logger from managedtenants.bundles.bundle import Bundle from managedten...
StarcoderdataPython
279372
<reponame>pablogo1/statistics from problem1 import Problem1 from problem2 import Problem2 if __name__ == "__main__": Problem1().run(19.5, 20, 22) Problem2().run(80, 60) # result_p2 = Problem2().run(20, 22) # print(f"{result_p1:.3f}") # print(f"{result_p2:.3f}")
StarcoderdataPython
68236
<reponame>kb2ma/openvisualizer # Copyright (c) 2010-2013, Regents of the University of California. # All rights reserved. # # Released under the BSD 3-Clause license as published at the link below. # https://openwsn.atlassian.net/wiki/display/OW/License import logging from openvisualizer.utils import buf2int, hex2buf...
StarcoderdataPython
25653
<reponame>ejkim1996/Unity-JSON-Manager<filename>JSONFormatter.py import json from tkinter import Tk from tkinter.filedialog import askopenfilename # Python script that allows user to select JSON file using TKinter and format it properly. root = Tk() filename = askopenfilename() root.destroy() # Close the window read...
StarcoderdataPython
3538616
<gh_stars>1-10 import argparse import datetime import re import validators from tzlocal import get_localzone import pnc_cli.common as common import pnc_cli.utils as utils from pnc_cli.pnc_api import pnc_api import requests bc_name_regex = "^[a-zA-Z0-9_.][a-zA-Z0-9_.-]*(?!\.git)+$" # BuildConfiguration Types def val...
StarcoderdataPython
5023421
from _pytest.config import Config from _pytest.monkeypatch import MonkeyPatch from infrastructure.utility.plugin_utilities import can_plugin_be_registered def test_plugin_register_help(pytestconfig: Config, monkeypatch: MonkeyPatch) -> None: monkeypatch.setattr(pytestconfig.option, "help", True) assert not ca...
StarcoderdataPython
11237740
<reponame>rec/leds<filename>test/bibliopixel/project/make.py<gh_stars>100-1000 import tempfile from unittest.mock import patch from bibliopixel.project import project from bibliopixel.util import data_file from .. mark_tests import SKIP_LONG_TESTS def make_project(data): if isinstance(data, dict): desc = ...
StarcoderdataPython
11283346
<reponame>ipussy/ipussy.github.io #!/usr/bin/env python3 import smtplib from datetime import datetime from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def sendReportEmail(subject, message): mailContent = message #The mail addresses and password senderAddress = '<EMAIL>...
StarcoderdataPython
3369488
import time from PIL import Image, ImageDraw from genetic import Myimage, ImagePopulation if __name__ == "__main__": current_generation = 0 current_evolve = 0 start_time = time.time() refer_image = Myimage.from_file(filename="sample.png") ImagePopulation.REFRENCE_IMAGE = refer_image initial_p...
StarcoderdataPython
4900359
# Generated by Django 3.2.7 on 2021-10-14 17:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('meetup', '0007_auto_20211014_2234'), ] operations = [ migrations.AddField( model_name='meetup', name='date', ...
StarcoderdataPython
11332815
<filename>hs_tools_resource/migrations/0013_auto_20171023_1724.py<gh_stars>1-10 # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('hs_tools_resource', '0012_toolmetadata_approved'), ] ...
StarcoderdataPython
1614426
<filename>Chapter 10/cellphone.py # The CellPhone class holds data about a cell phone. class CellPhone: # The __init__ method initializes the attributes. def __init__(self, manufact, model, price): self.__manufact = manufact self.__model = model self.__retail_price = price # ...
StarcoderdataPython
231828
import unittest from unittest.mock import patch, Mock import os from . import core class TestGetFileExtension(unittest.TestCase): def setUp(self): self._exefilename = "main.exe" self._shellfilename = "script.sh" self._noextfilename = "program" self._pyfilename = "mymodule.py" ...
StarcoderdataPython
131129
<filename>rusel/base/dir_forms.py from django import forms class UploadForm(forms.Form): upload = forms.FileField()
StarcoderdataPython
5042936
<reponame>e-k-m/thingstodo import os import flask def main(): os.environ["FLASK_APP"] = "thingstodo" flask.cli.main() if __name__ == "__main__": main()
StarcoderdataPython
60124
<reponame>lipovsek/pytea<gh_stars>0 # This sample tests the type checker's "type var scoring" mechanism # whereby it attempts to solve type variables with the simplest # possible solution. from typing import Union, List, TypeVar, Type T = TypeVar("T") def to_list1(obj_type: Type[T], obj: Union[List[T], T])...
StarcoderdataPython
210217
<reponame>abivilion/Hackerank-Solutions- def print_formatted(number): l = len(str(bin(number)[2:])) for i in range(1,number+1): print(str(i).rjust(l) + ' ' + oct(i)[2:].rjust(l) + ' ' + hex(i)[2:].upper().rjust(l) + ' ' + bin(i)[2:].rjust(l))
StarcoderdataPython
6425838
<gh_stars>0 import config import os from flask import Flask from flask_cors import CORS from flask_sqlalchemy import SQLAlchemy # App instantiation app = Flask(__name__) app.config.from_object(os.environ['APP_SETTINGS']) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) # enable CORS CORS(app...
StarcoderdataPython
8049189
""" An auto-scaling service specific to Assemblyline services. """ import threading from collections import defaultdict from string import Template from typing import Dict, List import os import math import platform import time import sched from assemblyline.remote.datatypes.queues.named import NamedQueue from assem...
StarcoderdataPython
11365914
<reponame>SkyTruth/pelagos-data #!/usr/bin/env python # This document is part of Pelagos Data # https://github.com/skytruth/pelagos-data # =========================================================================== # # # The MIT License (MIT) # # Copyright (c) 2014 SkyTruth # # Permission is hereby granted, free...
StarcoderdataPython
3380354
from typing import Any, Dict, Mapping, TypedDict from kolga.libs.service import Service from kolga.settings import settings from kolga.utils.general import ( DATABASE_DEFAULT_PORT_MAPPING, POSTGRES, get_deploy_name, get_project_secret_var, ) from kolga.utils.models import DockerImageRef, HelmValues fro...
StarcoderdataPython
9758756
from os import listdir from os.path import join from itertools import product import pandas as pd class TestRun: def test_output_files_exist(self, run_as_module): csv_files = listdir("receiving") dates = [ "20200801", "20200802", "20200803", "20200...
StarcoderdataPython
3307129
import random import numpy as np print(517**13 % 1261) print(413 +180) print(512908935546875-406747768078*1261) print(type(1.5)==float) test_list = [10] * 10 print(test_list)
StarcoderdataPython
6594440
#!/usr/bin/env python2 # -*- coding: utf-8 -*- import yaml def config_loader(config_file): with config_file as f: config = yaml.load(f) return config
StarcoderdataPython
368727
<filename>yawn/migrations/0001_initial.py # -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-01-22 20:00 from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.functions import yawn.utilities.cron class Migration(...
StarcoderdataPython
3519048
<filename>pinterest_scraper/scraper.py from selenium import webdriver from selenium.common.exceptions import StaleElementReferenceException from selenium.webdriver.common.keys import Keys import time,random,socket,unicodedata import string, copy, os import pandas as pd import requests try: from urlparse import urlp...
StarcoderdataPython
9766969
# Python3 Minimum Number of Jumps needed to reach End # Given an array of integers where each element represents the max number # of steps that can be made forward from that element. Write a function to # return the minimum number of jumps to reach the end of the array (starting # from the first element). If an elemen...
StarcoderdataPython
9643221
<gh_stars>0 from django.db import models from django.utils.translation import ugettext_lazy as _ from django.core.validators import RegexValidator, validate_email class Technician(models.Model): first_name = models.CharField(max_length=200, verbose_name = _('ονομα')) surname = models.CharField(max_length=200...
StarcoderdataPython
1946337
from datetime import datetime, timezone import json import os import sys import pika import spotipy from spotipy.oauth2 import SpotifyClientCredentials import imports.broker as broker import imports.db as db from imports.logging import get_logger import imports.requests SPOTIFY_MARKET = os.environ["SPOTIFY_MARKET"]...
StarcoderdataPython
9640098
"""Add tmdb_id column Revision ID: 01602e6e9637 Revises: 050b415e6bc9 Create Date: 2020-01-09 07:38:13.146945 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = '01602e6e9637' down_revision = '050b415e6bc9' branch_labels = None depends_on = None def upgrade(): ...
StarcoderdataPython
8035771
import itertools import os import numpy as np import pandas import webbrowser data_path = "../out-data/out_top1k_no_pca" compared_files = [ "methods lof {'algorithm': 'ball_tree', 'contamination': 5e-05, 'n_neighbors': 2}.csv", "methods lof {'algorithm': 'ball_tree', 'contamination': 5e-05, 'n_neighbors': 5}.c...
StarcoderdataPython
143101
#!/usr/bin/env python # -*- coding: utf-8 -*- """This loads the user's _config.py file and provides a standardized interface into it.""" import os import sys import urllib.parse import re from . import cache from . import controller from . import filter from .cache import zf zf.config = sys.modules['zeekofile.con...
StarcoderdataPython
1842297
import os import random import string from base64 import b64encode from datetime import datetime, timedelta from typing import List import pytz from firestore_ci import FirestoreDocument from flask import request, url_for from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_pas...
StarcoderdataPython
5063669
"""Tests for Ifcfg.""" import unittest from nose.tools import ok_, eq_, raises from nose import SkipTest import ifcfg from . import ifconfig_out class IfcfgTestCase(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_ifcfg(self): inter...
StarcoderdataPython
3574885
class Languages: RU = 'ru' EN = 'en' DEFAULT = EN LANGUAGES = [RU, EN]
StarcoderdataPython
11232808
<reponame>siboles/pyCellAnalyst import warnings warnings.simplefilter("ignore", category=FutureWarning) __all__ = ['Image', 'Filters', 'FilteringPipeline', 'Helpers', 'RegionsOfInterest', 'Segmentation', 'Deformation', 'Visualization'] from...
StarcoderdataPython
1851709
<reponame>s-tar/just-a-chat #!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'mr.S' from sqlalchemy import create_engine, Column, Integer, Sequence, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, scoped_session from kernel.config import config from fun...
StarcoderdataPython
11330410
from .neuralnetwork import NeuralNetworkGenerator from .supportvector import SupportVectorMachine def generate_code(method='neuralnetwork', *args, **kwargs): if method == 'neuralnetwork': Code = NeuralNetworkGenerator(*args, **kwargs) elif method == 'supportvector': Code = SupportVectorMachine(...
StarcoderdataPython
3597917
from django.shortcuts import render from album.models import Album def index(request,id,slug_do_album): album = Album.objects.get(id=id,slug=slug_do_album) musicas = album.musicas.all() return render(request,'album/album.html',{'album':album, 'musicas':musica...
StarcoderdataPython
1996539
<reponame>Sebrowsky/Mailpile<filename>mailpile/plugins/exporters.py import mailbox import os import time from gettext import gettext as _ import mailpile.config from mailpile.plugins import PluginManager from mailpile.util import * from mailpile.commands import Command from mailpile.mailutils import Email _plugins =...
StarcoderdataPython
1607755
import tkinter as tk from tkinter import ttk from PIL import ImageTk, Image def main(): root=tk.Tk() root.title('LabelwithIcon') framettk=ttk.Frame(root) framettk.grid() icon = ImageTk.PhotoImage(Image.open('pen.png')) pen_label=ttk.Label( framettk, image=icon) pen_label.g...
StarcoderdataPython
96708
<reponame>smadardan/HMM<gh_stars>0 """ src.HMM ~~~~~~~~~ in this file you can find the utilities for viterbi and backward forward. this will help to take real example and convert to hidden markov model input """ import random class Hmm(object): def __init__(self, a, b, pi, obs_names, hidden_names, logger): ...
StarcoderdataPython
381570
import sys def fizzbuzz(a, b, n): l = [] for i in xrange(1, n+1): if i%a == 0 and i%b == 0: l.append("FB") elif i%a == 0: l.append("F") elif i%b == 0: l.append("B") else: l.append(str(i)) return " ".join(l) test_cases = open(sys.argv[1], 'r') for test in test_cases: a, ...
StarcoderdataPython
3250566
import sys from util.ODXTServer import ODXTServer, ODXTServerV2, serverReqHandler, serverReqHandlerV2 HOST = 'localhost' PORT = 50057 if __name__ == "__main__": HOST = sys.argv[1] PORT = int(sys.argv[2]) server = ODXTServerV2((HOST, PORT), serverReqHandlerV2) server.serve_forever()
StarcoderdataPython
6672360
#!/usr/bin/env python3 import sys NON_CONGES = '0' INCR_CONGES = '1' MAX_CONGES = '2' DECR_CONGES = '3' BIN_WINDOW = 0.0006 MEDIAN_VAL = 0.00103 ACCEPTABLE_VARIANCE = 0.000200 MIN_VAL = 0.0005 if __name__ == "__main__": fname = sys.argv[1] # Assume lines have format: timestamp delay with open(fname, 'r'...
StarcoderdataPython
358510
class _Snake: def __init__(self, color): self.head = () self.body = [] self.color = color self.last_op = 'w' self.score = 0 self.operation = { 'w': lambda x, y: (x - 1, y), 'a': lambda x, y: (x, y - 1), 's': lambda x, y: (x + 1, y)...
StarcoderdataPython
3509563
<gh_stars>0 # Copyright 2015 Huawei Technologies Co., Ltd. # # 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 require...
StarcoderdataPython
78451
<reponame>aspose-cells-cloud/aspose-cells-cloud-python<filename>test/test_cells_clear_object_api.py # coding: utf-8 from __future__ import absolute_import import os import sys import unittest import warnings ABSPATH = os.path.abspath(os.path.realpath(os.path.dirname(__file__)) + "/..") sys.path.append(ABSPATH) impor...
StarcoderdataPython
11317224
# 3rd-party modules from lxml.builder import E # module packages from jnpr.junos.cfg import Resource from jnpr.junos import jxml as JXML class NatSrcPool(Resource): """ [edit security nat source pool <name>] """ PROPERTIES = [ 'addr_from', 'addr_to' ] def _xml_at_top(self):...
StarcoderdataPython
8141361
import extend_chain_operation from create_dummy_chain import build_chain import os chain1 = extend_chain_operation.chain classifiers = [os.path.join(os.environ['FCM'], 'Definitions', 'Classifiers', 'sota_models_cifar10-32-dev_validation', 'V001_ResNet34_ref_0'), os.path.join...
StarcoderdataPython
1919653
# # Code under the MIT license by <NAME> # from mc import * import time import os mc = Minecraft() bridge = [] while True: pos = mc.player.getTilePos() pos.y = pos.y - 1 belowBlock = mc.getBlock(pos) if belowBlock == AIR.id or belowBlock == WATER_FLOWING.id or belowBlock == WATER_STATIONARY.id: br...
StarcoderdataPython
9605694
<filename>src/p4pktgen/core/strategy.py<gh_stars>0 from collections import OrderedDict, defaultdict import json import time import logging from random import shuffle import operator import random from enum import Enum from p4pktgen.config import Config from p4pktgen.core.translator import TestPathResult from p4pktgen...
StarcoderdataPython
3486572
<reponame>jackadamson/facebooklogger from pymessenger.bot import Bot import logging from facebooklogger.settings import PAGE_ACCESS_TOKEN, FB_USER_ID class FacebookLogger(logging.Handler): def __init__( self, user_id=FB_USER_ID, access_token=PAGE_ACCESS_TOKEN, level=logging.NOTSET ): if access...
StarcoderdataPython
6692460
<gh_stars>0 # %% from folktables import ACSDataSource, ACSIncome from sklearn.linear_model import LogisticRegression from sklearn.model_selection import cross_val_predict from sklearn.metrics import roc_auc_score import pandas as pd from collections import defaultdict from xgboost import XGBRegressor, XGBClassifier fro...
StarcoderdataPython
237884
import pickle def get_random_pgm_groups(): interval = [0, 1000, 5000, 10000, 50000, 100000] buckets = {} for i in range(len(interval)-1): buckets[i] = [] valid_count = 0 with open('baseline.txt') as f: lines = f.readlines() print("Ignore Header Line: {}".format(lines[0])) lines = lines[1:] ...
StarcoderdataPython
1638262
<filename>src/vpack/utils.py import logging # logging.basicConfig() logger = logging.getLogger("vpack") logger.propagate = False logger.setLevel(logging.INFO) c_handler = logging.StreamHandler() c_handler.setLevel(logging.INFO) c_format = logging.Formatter('(%(name)s): %(message)s') c_handler.setFormatter(c_format) lo...
StarcoderdataPython
3291338
<reponame>basnijholt/HASS-data-detective """Tests for config package.""" import os import tempfile from unittest.mock import patch import pytest from detective import config def test_find_hass_config(): """Test finding HASS config.""" with patch.dict(os.environ, {"HASSIO_TOKEN": "yo"}): assert confi...
StarcoderdataPython
5170473
<gh_stars>0 import getpass from selenium.webdriver import Firefox from time import sleep def open_browser(browser, url): return browser.get(url) def close_broser(browser): return browser.quit() def fill_form(browser, form, nome, senha): browser.find_element_by_css_selector( f'.form-{form} inpu...
StarcoderdataPython
1882356
from setuptools import setup, find_packages from pathlib import Path requirements = [] __version__ = "0.1.1" # Add README to PyPI this_dir = Path(__file__).parent with open(Path.joinpath(this_dir, "README.md"), encoding="utf-8") as f: long_description = f.read() setup( name="template-python-package", ...
StarcoderdataPython
3543735
# -*- coding: utf-8 -*- # (C) Copyright IBM Corp. 2018, 2020. # # 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 applic...
StarcoderdataPython
3339422
class Solution: def longestPalindrome(self, s): """ :type s: str :rtype: str """ def checkPalindrome(s): """ check string is palindrome, if true return count, else return 0 :type s: str :rtype: int """ li...
StarcoderdataPython
1670863
from re import Match from typing import Any, Dict, Iterable, Union import confuse import pytest from .conventional_commits import ConventionalCommitParser INVALID_SUBJECT_REGEX = [ ("spa ce: Type with space"), ("type(spa ce): Scope with space"), ("type !: Space between type and bang"), ("type(scope) ...
StarcoderdataPython
4915613
<reponame>qenett/pandas-intro-clone import pandas mesta = pandas.read_csv("mesta.csv", index_col="mesto", encoding="utf-8") # ## 2. Základní selekce # Výběr hodnot v tabulce probíhá převážně pomocí "metody" `loc`. # ### Výběr podle jmen řádků a sloupců # #### 1. Pouze řádky print(mesta.loc["brno"]) print(mesta.l...
StarcoderdataPython
1942838
class AnimalTerrestre: def __init__(self, nome, altura): self.nome = nome self.altura = altura def andar(self): print("O animal terrestre andou") def comer(self): print("O animal terrestre comeu") class AnimalAquatico: def __init__(self, nome, especie): self.n...
StarcoderdataPython
129055
import numpy as np def parse_res(res): min = -1 avg = -1 if res != "": if "," not in res: min = int(res) avg = int(res) else: all = np.array([int(r) for r in res.split(",")]) min = np.min(all) avg = np.mean(all) return min,avg ...
StarcoderdataPython
6505531
<gh_stars>1-10 import time import logging import requests from crizzle.services.base import Service as BaseService logger = logging.Logger(__name__) class Service(BaseService): """ Environment for the Poloniex exchange """ def sign_request_data(self, params=None, data=None, headers=None): pa...
StarcoderdataPython
9725554
import csv INPUT_DIR = 'Input/' OUTPUT_DIR = 'Output/' UTILITIES_DIR = 'Utilities/' VERBS_LIST = [] def read_data(filename): """" Read scv file : #0 ArticleTitle, #1 Question, #2 Answer, #3 DifficultyFromQuestioner, #4 DifficultyFromAnswerer, #5ArticleFile and store them. :param filename: ...
StarcoderdataPython
8028351
import rsa import base64 import random __all__ = ('passworldEncode', 'randomTemperature', 'getIMEI', 'USER_AGENT', 'USER_AGENT_YIBAN','getCheckData','randomTemperature') pubkey = '''-----<KEY> -----END PUBLIC KEY-----''' key:rsa.PublicKey = rsa.PublicKey.load_pkcs1_openssl_pem(pubkey) USER_AGENT:str = 'Mozilla/5.0 (...
StarcoderdataPython
1925301
from django.conf import settings from django.utils.html import escape from django.utils.http import urlquote from mediagenerator.utils import media_url WIDE_TWITTER_BUTTON = """ <iframe src="http://platform.twitter.com/widgets/tweet_button.html?count=horizontal&amp;lang=en&amp;text=%(title)s&amp;url=%(url)s%(opttwitte...
StarcoderdataPython