id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
5168324
<filename>xl_auth/oauth/__init__.py<gh_stars>1-10 # -*- coding: utf-8 -*- """The OAuth sub-package.""" from __future__ import absolute_import, division, print_function, unicode_literals from . import client, grant, token, views # noqa
StarcoderdataPython
3234337
<gh_stars>1-10 import os, sys, h5py import numpy as np if len(sys.argv) != 2: print("usage: python reformat_simulation_parameters.py [hdf5 file]") sys.exit(-1) filename = sys.argv[1] fout = open(os.path.join(os.path.dirname(filename), \ 'simulation_parameters.csv'), 'w+') fout.write("parameter,K,N,M,value...
StarcoderdataPython
1976448
#!/usr/bin/python3 # # Copyright (c) 2021 <NAME> <<EMAIL>> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modif...
StarcoderdataPython
3562903
""" Configuration settings for the Værmelder Python console app. See https://docs.microsoft.com/en-us/graph/auth-register-app-v2 for further information and a tutorial. """ """ Azure Active Directory app client id. Caution: Changes required. Edit this with your generated and secret id. """ CLIENT_ID = '<INSER...
StarcoderdataPython
8155997
<gh_stars>0 """ Run PyTorch DDPG on HalfCheetah. """ import random from railrl.exploration_strategies.base import \ PolicyWrappedWithExplorationStrategy from railrl.exploration_strategies.ou_strategy import OUStrategy from railrl.launchers.launcher_util import run_experiment from railrl.torch.networks import FeedF...
StarcoderdataPython
8092989
# -*- coding: utf-8 -*- # Copyright 2018 ICON Foundation # # 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 ...
StarcoderdataPython
6650557
<reponame>DistrictDataLabs/entity-resolution import os import csv import nltk FIXTURES = os.path.join(os.path.dirname(__file__), "..", "fixtures") PRODUCTS = os.path.join(FIXTURES, "products") def load_data(name): with open(os.path.join(PRODUCTS, name), 'r') as f: reader = csv.DictReader(f) for ro...
StarcoderdataPython
1950649
<filename>app/setting/__init__.py #coding: utf-8 from flask import Blueprint setting = Blueprint("setting", __name__) from . import views
StarcoderdataPython
5023762
test = { 'name': 'unique', 'points': 1, 'suites': [ { 'cases': [ { 'code': r""" scm> (unique '()) () scm> (unique '(1 2 1 3 1 4)) (1 2 3 4) scm> (unique '(1 2 3 4)) (1 2 3 4) scm> (unique '(1 1 1 1 1)) (1) ...
StarcoderdataPython
4954506
# -*- coding: utf-8 -*- # @Author: 何睿 # @Create Date: 2019-01-16 10:40:41 # @Last Modified by: 何睿 # @Last Modified time: 2019-01-16 11:21:29 class Solution(object): def findPeakElement(self, nums): """ :type nums: List[int] :rtype: int """ count = len(n...
StarcoderdataPython
3291572
<gh_stars>0 import csv import cv2 import os if not os.path.exists('./dataset'): os.makedirs('./dataset') name = input("enter your name") roll = input("enter your id") row = [name,roll,'A'] l =[] for root ,dire,filenames in os.walk('dataset'): for names in dire: l.append(int(names)) folder = str(l[-...
StarcoderdataPython
5148496
<reponame>tkanemoto/django-portfolios<gh_stars>0 # -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-08-12 13:04 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('portfolios', '0035_auto_20170812_1230'), ...
StarcoderdataPython
3435903
<gh_stars>0 """ Bablescan examples Fit multiple peaks in single scan """ import os import numpy as np import matplotlib.pyplot as plt import babelscan scan = babelscan.file_loader(r"C:\Users\dgpor\Dropbox\Python\ExamplePeaks\794940.nxs") scan.set_error_operation() print(scan) res = scan.fit.multi_peak_fit(print_resu...
StarcoderdataPython
6485599
<filename>setup.py import fnmatch from setuptools import find_packages, setup from setuptools.command.build_py import build_py as build_py_orig excluded = [ '.git*', '.vscode', '*workspace', ] class build_py(build_py_orig): def find_package_modules(self, package, package_dir): modules = super(...
StarcoderdataPython
6604870
# ========================== begin_copyright_notice ============================ # # Copyright (C) 2020-2021 Intel Corporation # # SPDX-License-Identifier: MIT # # =========================== end_copyright_notice ============================= # -*- Python -*- import lit.formats import lit.util from lit.llvm import l...
StarcoderdataPython
3555222
<filename>simax/tasks/none_task.py<gh_stars>0 from simax.tasks.base_task import BaseTask class NoneTask(BaseTask): def cycle(self): return None
StarcoderdataPython
6410939
import sys def reducer(): # previous key old_user = None # final row structure of data set row = { 'user_id': None, 'id': None, 'title': None, 'tagnames': None, 'node_type': None, 'parent_id': None, 'abs_parent_id': None, 'added_at': None...
StarcoderdataPython
8036195
# encoding: utf-8 """ @author: liaoxingyu @contact: <EMAIL> """ import math import torch from torch import nn from models.models_utils.rga_modules import RGA_Module from models.models_utils.part_rga_modules import Part_RGA_Module def weights_init_kaiming(m): classname = m.__class__.__name__ if classname.fi...
StarcoderdataPython
6494765
import pandas as pd def read_file(data_file): d_file = pd.read_csv(data_file, low_memory=False, usecols=['ACC-X-Ring1', 'ACC-Y-Ring1', 'ACC-Z-Ring1', 'GYRO-X-Ring1', 'GYRO-Y-Ring1', 'GYRO-Z-Ring1', 'ACC-X-Ring2', 'ACC-Y-Ring2', 'ACC-Z-Ring2', 'GYRO-X-Ring...
StarcoderdataPython
6454023
import urllib2 from bs4 import BeautifulSoup def cricbuzz(): url="http://www.cricbuzz.com/cricket-series/2330/indian-premier-league-2015" print "Getting updates from Cricbuzz . . . . . . . . ." page = urllib2.urlopen(url) soup = BeautifulSoup(page.read()) headlines=soup.find_al...
StarcoderdataPython
8124900
from Python_lxf.awesomepython3webapp.www import orm from Python_lxf.awesomepython3webapp.www.models import User, Blog, Comment import asyncio async def test(loop): await orm.create_pool(loop, host='127.0.0.1', port=3306, user='www-data', password='<PASSWORD>', db='awesome') u = User(n...
StarcoderdataPython
8089701
<gh_stars>1-10 ''' Factory to produce messages ''' def get_send_header(): ''' ============== 獲鴨自動腥野系統 ============== ''' return "================\r\n\u7372\u9D28\u81EA\u52D5\u8165\u91CE\u7CFB\u7D71\r\n================\n" def get_body(*messages): result = "\u8FC5\u8272\u8010\u6D74:\r\n------...
StarcoderdataPython
294469
class Solution: def XXX(self, root: TreeNode) -> int: self.maxleftlength = 0 self.maxrightlength = 0 return self.dp(root) def dp(self,root): if(root is None): return 0 self.maxleftlength = self.dp(root.left) self.maxrightlength = self.d...
StarcoderdataPython
3268970
<reponame>15379180/pipelines<filename>components/aws/sagemaker/run_tests.py # Configures and runs the unit tests for all the components import os import sys import unittest # Taken from http://stackoverflow.com/a/17004263/2931197 def load_and_run_tests(): setup_file = sys.modules['__main__'].__file__ setup_dir =...
StarcoderdataPython
176559
<gh_stars>1-10 #!/usr/bin/env python import sys if sys.version_info[0] >= 3: import PySimpleGUI as sg else: import PySimpleGUI27 as sg import random import time from sys import exit as exit """ Pong code supplied by <NAME> (Neonzz) Modified. Original code: https://www.pygame.org/project/3649/5739 """...
StarcoderdataPython
3551972
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2007-2015, GoodData(R) Corporation. All rights reserved import copy import datetime import os import pytest from smoker.server.daemon import Smokerd def generate_unique_file(): return datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S-%f') class Te...
StarcoderdataPython
6499528
<gh_stars>1-10 # encoding: utf-8 # Copyright 2011 Tree.io Limited # This file is part of Treeio. # License www.tree.io/license """ Core module: Trash views """ from django.template import RequestContext from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from django.core.urlreso...
StarcoderdataPython
11326107
<gh_stars>0 from pathlib import Path import os import random from locust import HttpUser, task, between import logging def get_project_root() -> str: return str(Path(__file__).parent.parent) def read_file(file_path): with open(file_path, 'r', encoding='utf-8') as f: content = [line.strip() for line...
StarcoderdataPython
3456067
from models import * import logging import hashlib import settings import traceback import sys import os import string import uuid from django.db import transaction from receiver.models import _XFORM_URI def get_submission_path(): return settings.RAPIDSMS_APPS['receiver']['xform_submission_path'] def save_legacy_b...
StarcoderdataPython
3520537
<filename>train_test.py import torch import torchvision import datasets import transforms import train import time import torch.nn.functional as F import torch.optim as optim from torch.utils.data import random_split, DataLoader import torch import transforms as T from movinets import MoViNet from movinets.config impor...
StarcoderdataPython
4887234
#!/usr/bin/python # -*- coding: utf-8 -*- from pocsuite.api.poc import register from pocsuite.api.poc import Output, POCBase import struct import socket,re def make_overflow_dummy(overflow_len, retaddr): return 'A' * overflow_len + struct.pack('<L', retaddr) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sc2...
StarcoderdataPython
11310812
import boto3 polly = boto3.client('polly') # Use Amazon Polly to convert text to speech res = polly.synthesize_speech( Text = "Hello, how are you?", OutputFormat = 'mp3', VoiceId = 'Joanna') # Save the response from Amazon Polly into the mp3 file audiofile = 'myaudio.mp3' file = open(audiofile, 'wb') fil...
StarcoderdataPython
331018
# -*- coding: utf-8 -*- """ Microsoft-Windows-DXGI GUID : ca11c036-0102-4a2d-a6ad-f03cfed5d3c9 """ from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct from etl.utils import WString, CString, SystemTime, Guid from etl.dtyp import Sid from etl.parser...
StarcoderdataPython
1678630
from django.urls import path, include from rest_framework.routers import DefaultRouter from .views import SharingViewSets, CommentViewSets, LikesToSharingViewSets router = DefaultRouter() # sharing router.register('sharing', SharingViewSets) # likesToSharing router.register('likes', LikesToSharingViewSets) # comments...
StarcoderdataPython
3265923
#-*- encoding: utf-8 -*- import os import sys import glob import json # Create cache dir in project root cache = os.sep.join(__file__.split(os.sep)[:-2])+os.sep+"cache" try: os.mkdir(cache) except: pass def _delete_file(filename): ''' delete a file ''' os.remove(cache+os.sep+filename) def _saf...
StarcoderdataPython
5022081
from JDI.web.selenium.elements.base.clickable import Clickable from JDI.web.selenium.elements.common.text import Text class ClickableText(Clickable, Text): def __init__(self, by_locator=None, web_element=None): if by_locator is not None: super(ClickableText, self).__init__(by_locator=by_locat...
StarcoderdataPython
6622114
<gh_stars>1-10 from .bases import * from .crawlino_model import * from .plugins_models import * from .input_model import *
StarcoderdataPython
3383124
<reponame>sgriffith3/2022-01-04-Python car = input("Whatchoo got? ") print(car)
StarcoderdataPython
6612265
<reponame>DanSeraf/spyd from spyd.registry_manager import register from spyd.utils.dictionary_get import dictget @register('client_message_handler') class EditentHandler(object): message_type = 'N_EDITENT' @staticmethod def handle(client, room, message): player = client.get_player() entit...
StarcoderdataPython
9719750
<reponame>coderMaruf/leetcode-1<filename>2020_July_Leetcode_30_days_challenge/Week_2_Subsets/by_bitmap.py<gh_stars>10-100 ''' Description: Given a set of distinct integers, nums, return all possible subsets (the power set). Note: The solution set must not contain duplicate subsets. Example: Input: nums = [1,2,3] O...
StarcoderdataPython
9798483
<reponame>halsayed/whmcs-demo import os import base64 import requests # disable ssl warnings import urllib3 urllib3.disable_warnings() # API configuration and parameters ... pc_address = '10.38.15.9' username = 'admin' password = os.environ.get('PASSWORD', '<PASSWORD>!') # change the password to a suitable value aut...
StarcoderdataPython
5067050
# Copyright (c) 2018 Graphcore Ltd. All rights reserved. import sys import os import c10driver import cmdline import popart from popart.torch import torchwriter #we require torch in this file to create the torch Module import torch args = cmdline.parse() nChans = 3 # process batchSize = 2 samples at a time, # so wei...
StarcoderdataPython
1885405
#!/usr/bin/python3 import time from http.server import HTTPServer, BaseHTTPRequestHandler from picamera import PiCamera class MjpegMixin: """ Add MJPEG features to a subclass of BaseHTTPRequestHandler. """ mjpegBound = 'eb4154aac1c9ee636b8a6f5622176d1fbc08d382ee161bbd42e8483808c684b6' frameBegin ...
StarcoderdataPython
1678660
<filename>python_teste/python_aulas/aula_96.py<gh_stars>1-10 def area(a, b): ar = a * b print(f'A área de um terreno {a:.1f}x{b:.1f} é de {ar:.1f}m²') #Programa Principal largura = float(input('Largura: ')) comprimento = float(input('Comprimento: ')) area(largura, comprimento)
StarcoderdataPython
225732
<reponame>David100459/final from django.db import models # Create your models here. class student(models.Model) : firt_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) code = models.CharField(max_length=10) created_at = models.DateTimeField() class subject(models.Mod...
StarcoderdataPython
4831074
import cv2 import pandas as pd def extract_SURF_data(inputpath, outputpath): img = cv2.imread(inputpath) surf = cv2.xfeatures2d.SURF_create(4000) kps, features = surf.detectAndCompute(img, None) kps_data = [] for kp in kps: # 关键点X,Y,从左到右0~255,从上到下0~255。关键点角度。关键点直径大小 # print(kp.pt[0...
StarcoderdataPython
4994708
<filename>Support/Fuego/Pythia/pythia-0.4/packages/pyre/pyre/graph/Graph.py #!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # <NAME> # California Institute of Technology # (C) 1998-20...
StarcoderdataPython
5013308
import numpy as np import numba as nb import pandas as pd import qnt.ta.ndadapter as nda import typing as tp import time import sys from qnt.log import log_info, log_err @nb.jit(nb.float64[:](nb.float64[:], nb.int64), nopython=True) def lwma_np_1d(series: np.ndarray, periods: int) -> np.ndarray: tail = np.empty((...
StarcoderdataPython
311164
<filename>ZeRO_SLMkII/ZeRO_SLMkII.py import Live import MidiRemoteScript from MixerController import MixerController from DisplayController import DisplayController from consts import * class ZeRO_SLMkII(): def __init__(self, c_instance): self.__c_instance = c_instance self.__c_instance.log_message...
StarcoderdataPython
5048414
from sqlalchemy import * from sqlalchemy.orm import validates, relationship from db import db class DeploymentTarget(db.Model): __tablename__ = "deployment_target" id = Column(String, primary_key=True) deployment_target_type_id = Column(String, ForeignKey('deployment_target_type.id')) partition_id =...
StarcoderdataPython
3281872
class Individual: """Represents an image""" def __init__(self, **kwargs): self.genome = kwargs['genome'] # List of genes self.fitness = 0 # Fitness value for this individual
StarcoderdataPython
1623644
<gh_stars>1-10 from bs4 import BeautifulSoup, element import re from matplotlib.cm import ScalarMappable, RdYlGn from core import * from selectors import * from actors import * from evaluators import * from autocues import * # Triggers: policy = ScoringPolicy() policy.append((ScoreAggregator(), EVAL_CONTAINE...
StarcoderdataPython
4840893
# -*- coding: utf-8 -*- """ Created on Thu Oct 01 16:19:44 2015 @author: <NAME> """ import os.path import sys, StringIO import antimony import roadrunner import tellurium as te import zipfile import tempfile import re try: import phrasedml except ImportError as e: roadrunner.Logger.log(roadrunner.Logger.LOG_W...
StarcoderdataPython
229130
import re from sublime import Region class SImport: @staticmethod def getExpressionInContext(expression, context): match = re.search(r"[^\{{\}}\(\)\<\>\.;\s]*{0}$".format(expression), context) if match: return match.group(0) return expression def __init__(self, expression, context, region, con...
StarcoderdataPython
9685931
# ------------------------------------------------------------------------------ # Class TextInput # # Allows the user to input text (as opposed to predefined options) # ------------------------------------------------------------------------------ from PythonUtils.user_input import UserInput from PythonUtils.option i...
StarcoderdataPython
11353339
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-05-09 11:48 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('mapdata', '0065_auto_20170509_1140'), ] operations...
StarcoderdataPython
4891466
from deliravision.data.base_datasets import ImageFolder, Downloadable import codecs import gzip import os import numpy as np from PIL import Image import zipfile class MNIST(ImageFolder, Downloadable): """ The MNIST Dataset See Also -------- :class:`deliravision.data.base_datasets.ImageFolder` ...
StarcoderdataPython
1914107
#!/usr/bin/env python # -*- encoding: utf-8 -*- # vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8: # Author: Vincent<<EMAIL>> # http://blog.vincentzhong.cn # Created on 2017/2/26 19:57 # !/usr/bin/env python import asynctest from catty.message_queue import AsyncRedisPriorityQueue from catty.parser import Parser ...
StarcoderdataPython
370935
<gh_stars>1-10 from sql_alchemy import db from models.fornecedor_model import FornecedorModel from models.categoria_model import CategoriaModel class ProdutoModel(db.Model): __tablename__ = 'produto' id_produto = db.Column(db.Integer, primary_key=True) cod_produto = db.Column(db.String(50), nullable=Fals...
StarcoderdataPython
3402770
import math import logging from ._instrument import * from ._instrument import _usgn, _sgn from . import _utils log = logging.getLogger(__name__) REG_SG_TrigDutyInternalCH0_L = 69 REG_SG_TrigDutyInternalCH0_H = 70 REG_SG_TrigDutyInternalCH1_L = 71 REG_SG_TrigDutyInternalCH1_H = 72 REG_SG_TrigPeriodInternalCH0_L...
StarcoderdataPython
9712414
<reponame>akumuthan-dev/data-flow import re from datetime import datetime, timedelta from functools import partial from airflow import DAG from airflow.hooks.S3_hook import S3Hook from airflow.hooks.postgres_hook import PostgresHook from airflow.operators.python_operator import PythonOperator import sqlalchemy as sa ...
StarcoderdataPython
11302981
__author__ = "<NAME>" import pythoncom import pyHook import os, sys from _winreg import * buffer = [] #Hide def hide(): import win32console, win32gui window = win32console.GetConsoleWindow() win32gui.ShowWindow(window, 0) return True # Add to startup def addStartup(): fp=os.path....
StarcoderdataPython
4987973
<gh_stars>0 import sys import random from datetime import datetime import matplotlib.pyplot as plt import numpy as np import talib as ta #list of functions #print ta.get_functions() #print ta.get_function_groups() #https://github.com/mrjbq7/ta-lib #http://www.eickonomics.com/posts/2014-03-25-python-vs-R-ad...
StarcoderdataPython
74663
<filename>make_demo_discover_rt/pysequitur/__init__.py<gh_stars>10-100 #!/usr/local/bin/python # -*- coding: utf-8 -*- # file: __init__.py from .main import Sequencer, Sequencer2, print_grammar, AlphabetsTransformer """ exporting: - Sequencer - Sequencer2 - print_grammar """
StarcoderdataPython
11255917
<gh_stars>1-10 #!/usr/bin/env python3 from setuptools import setup setup( name="wisdom", version="2.1", description="A collection of wise quotes for the terminal", long_description=open("README.md").read(), license="MIT", packages=["libwisdom"], scripts=["wisdom"], package_data={"libwi...
StarcoderdataPython
1708720
import numpy as np import keras from keras.models import Sequential from keras.layers import Dense from keras.layers import Conv2D from keras.layers import MaxPooling2D from keras.layers import Flatten import robolib.robogui.pixel_editor as pe import cv2 import robolib.images.feature_extraction as extr DEBUG = True l...
StarcoderdataPython
319783
<reponame>Liu-JiaTong/DataEngine import pandas as pd from fbprophet import Prophet import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') # 读入数据集 df = pd.read_csv('./DataSet/train.csv') # 拟合模型 model = Prophet(yearly_seasonality=True, seasonality_prior_scale=0.1) model.fit(df) # 构建待预测日期数据...
StarcoderdataPython
5126501
while True: n = int(input('Quer ver a tabuada de qual valor? ')) print('-'*35) if n < 0: # Mostra a tabuada enquanto o usuário não digitar um valor negativo break for i in range(0, 11): # Quando o progressão é de apenas 1, o 1 pode ser omitido print(f'{n} X {i} = {n*i}') print('-'*...
StarcoderdataPython
3505754
# Python RPG # <NAME> # https://github.com/AlexGalhardo/Python-RPG # <EMAIL> # https://alexgalhardo.com # !/usr/bin/python3 # coding: utf-8 # ./Python/Monsters/PitsOfInferno_Monsters/Bear.py from SuperClass.NormalMonster import NormalMonster from Global.GLOBAL_PITS_OF_INFERNO_VARIABLES import GLOBAL_BEAR_LIFE, \ ...
StarcoderdataPython
3245063
from typing import List def ref_range_to_refs(ref_range: str) -> List[str]: """ Given a ref range like eg ibr152-ibr155 returns a list of the individual refs, eg [ibr152,ibr153,ibr154,ibr155] assumptions: - always comprises alphabetic then number - alphabetic bit always constant - num...
StarcoderdataPython
125750
<reponame>ganadist/r8 #!/usr/bin/env python # Copyright (c) 2019, the R8 project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. # Script that automatically pulls and uploads all upstream direct...
StarcoderdataPython
6606929
import sys import os import requests class Client(object): """A simple API client for the Xray's API. see README for more details """ tests_name = [] test_suites = [] #last_update = 89 def __init__(self, api_token=None, url_base=""): self.api_token = api_token s...
StarcoderdataPython
9694811
<reponame>SmartDataAnalytics/KEEN-Preprocessor<filename>src/kupp/instance_creation_utils/utils.py # -*- coding: utf-8 -*- import numpy as np from typing import Dict from kupp.triples_preprocessing_utils.basic_triple_utils import slice_triples def create_multi_label_relation_instances(unique_entity_pairs: np.array, ...
StarcoderdataPython
28944
def bolha_curta(self, lista): fim = len(lista) for i in range(fim-1, 0, -1): trocou = False for j in range(i): if lista[j] > lista[j+1]: lista[j], lista[j+1] = lista[j+1], lista[j] trocou = True if trocou== Fal...
StarcoderdataPython
5150607
"""Login.gov/authorize is redirected to this endpoint to start a django user session.""" import logging from django.conf import settings from django.contrib.auth import get_user_model, login from django.core.exceptions import SuspiciousOperation from django.http import HttpResponseRedirect from django.utils import tim...
StarcoderdataPython
53103
<gh_stars>0 class Solution: # Iterative def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if not root: return None stack = [root] while len(stack) > 0: currentNode = stack.pop() currentNode.left, currentNode.right = curren...
StarcoderdataPython
5010030
<filename>Important/print_primeList.py for n in range(1,101): prime=True for i in range(2,n): if(n%2==0): prime=False if prime: print n
StarcoderdataPython
8060389
<gh_stars>0 """ The Update super class """ from Product.Database.DBConn import create_session class Update: """ Author: <NAME>, <NAME> Date: 9/11/2017 Last update: 13/11/2017 Purpose: Its subclasses should be used to retrieve from the database """ def __init__(self): """ Au...
StarcoderdataPython
6412906
<filename>tests/test_dnssec_api.py import unittest from namecom import DnssecApi, exceptions from .sample import ( correct_auth, dnssec_sample1 as sample1, dnssec_sample2 as sample2 ) api = DnssecApi(domainName=sample1.domainName, auth=correct_auth, use_test_env=True) class DnssecApiTestCase(unittest.Te...
StarcoderdataPython
1615147
<gh_stars>100-1000 load(":flake8_config.bzl", "Flake8Info") def _flake8_impl(ctx): srcs = extract_files(ctx.attr.srcs) file_paths = short_paths(srcs) config = ctx.attr.lint_config[Flake8Info].config_file.files.to_list()[0] test = [ "#!/usr/bin/env bash", "echo \"{bin} --config {config} ...
StarcoderdataPython
11249307
import cv2 from PyQt5.QtWidgets import QMainWindow, QFileDialog from PyQt5.QtCore import QThread, pyqtSignal from .configScreen import ConfigScreen from .resultScreen import ResultScreen from .titleScreen import TitleScreen from .loadingScreen import LoadingScreen from src.tracker import Tracker from src.stabilizer imp...
StarcoderdataPython
6576805
<gh_stars>1000+ # coding=utf-8 # Copyright 2021 The Google Research 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/licenses/LICENSE-2.0 # # Unless requ...
StarcoderdataPython
3208209
my_string = 'we are fine.' def replace_space(my_str): my_str = str(my_str) new = '%20'.join(my_str.split(' ')) print(new) replace_space(my_string)
StarcoderdataPython
247741
from bs4 import BeautifulSoup as Soup from muse.util import HeadlessChrome from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait import time SITE_URL = 'http://www.melon.com' REAL_TIME_CHART = '{0}/chart/in...
StarcoderdataPython
3514748
<filename>tasks/citation_network_task.py from collections import namedtuple from typing import Any, Dict, List, Iterable, Iterator import numpy as np import tensorflow as tf from dpu_utils.utils import RichPath, LocalPath from .sparse_graph_task import Sparse_Graph_Task, DataFold, MinibatchData from utils.citation_ne...
StarcoderdataPython
6475641
""" pipenv run python -m unittest tests.unit.test_formCreate """ import unittest from tests.integration.constants import _ from app import app from chalicelib.models import Response, User, Form, FormOptions, Org from chalicelib.routes import form_create from unittest.mock import MagicMock from bson.objectid import Obje...
StarcoderdataPython
8017558
#!/usr/bin/env python3 def main(): from scipy.special import comb n, p = map(int, input().split()) a = list(map(int, input().split())) e, o = 0, 0 for i in a: if i%2 == 0: e += 1 else: o += 1 if n == e: if p == 0: print(2**n) ...
StarcoderdataPython
1854188
import numpy as np from .. import OneHotEncoderRuntime def test_transform(): ohe = OneHotEncoderRuntime() X = np.array([['a'], ['b']]) X_act = ohe.fit_transform(X) X_exp = np.array([[1, 0], [0, 1]]) assert np.all(X_exp == X_act)
StarcoderdataPython
8076271
<filename>runmnist.py<gh_stars>1-10 from __future__ import division import numpy as np import tensorflow as tf from common import * import datasets from layers import * import matplotlib.pyplot as plt if __name__ == '__main__': data = datasets.Mnistdata(ds=2) sigma = 1 N = 4 lr = 0.1 rw = 0.01 layers = 8...
StarcoderdataPython
4933521
<filename>cacheTraceAnalysis/plot/workingset.py<gh_stars>1-10 """ plots how total workseting set increase over time """ import os, sys sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../")) from utils.common import * import bisect SLAB_SIZES = [96, 120, 152, 192, 240, 304, 384, 480, 600...
StarcoderdataPython
9758079
<gh_stars>1-10 """<NAME>'s aospy.Proj object for CMIP5 data.""" from aospy.proj import Proj from aospy_user import regions, models cmip5 = Proj( 'cmip5', direc_out='/work/Spencer.Hill/', tar_direc_out='/archive/Spencer.Hill/', nc_dir_struc='one_dir', models=( models.bcc_csm1, models.bnu_es...
StarcoderdataPython
11306522
from django.conf import settings from django.core.files.storage import FileSystemStorage upload_storage = FileSystemStorage(location=settings.UPLOAD_ROOT)
StarcoderdataPython
8114516
<filename>reports_api/reports/models/speaker_registration.py """ * Copyright 2019 OpenStack Foundation * 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/LICE...
StarcoderdataPython
11366931
<filename>pythonbrasil/exercicios/repeticao/ER resp 26.py ''' Numa eleição existem três candidatos. Faça um programa que peça o número total de eleitores. Peça para cada eleitor votar e ao final mostrar o número de votos de cada candidato. ''' cand1, cand2, cand3 = 0,0,0 print('***************************************...
StarcoderdataPython
8122293
<filename>greentest-py3/test__socket.py import os import sys import array import gevent from gevent import socket import greentest import time class TestTCP(greentest.TestCase): TIMEOUT_ERROR = socket.timeout long_data = ", ".join([str(x) for x in range(20000)]) def setUp(self): greentest.TestCa...
StarcoderdataPython
1830800
<reponame>Shanduur/monorepo<gh_stars>0 import requests import os import time import re import logging import ipaddress from pythonjsonlogger import jsonlogger log = logging.getLogger() __log_handler = logging.StreamHandler() __formatter = jsonlogger.JsonFormatter('%(asctime)s %(levelname)s %(message)s') __log_handler...
StarcoderdataPython
9679102
import numpy as np import cv2 class Grab_cut(object): suffix = '.jpg' def __init__(self, filename=None): self.filename = filename self.height = None self.width = None def image_matting(self, image_file, shape, iteration=10): points = shape['points'] xmin, ymin, xm...
StarcoderdataPython
5032405
'''The default configuration for pythonagent''' DEFAULT_AGENT_CONFIG = { '_use_console_span_exporter': False, 'enabled': True, 'propagation_formats': ['TRACECONTEXT'], 'service_name': 'pythonagent', 'reporting': { 'endpoint': 'http://localhost:4317', 'secure': False, 'trace_r...
StarcoderdataPython
5020475
# -*- coding: utf-8 -*- from Instanssi.common.http import Http403 from Instanssi.common.auth import staff_access_required from django.shortcuts import get_object_or_404 from django.http import HttpResponseRedirect from django.urls import reverse from django.utils import timezone from Instanssi.ext_blog.models import B...
StarcoderdataPython
4826324
<reponame>aosp-goes-brrbrr/packages_modules_NeuralNetworks # # Copyright (C) 2019 The Android Open Source Project # # 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.or...
StarcoderdataPython