id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
1766667 | <reponame>xpheragroup/PbackO
from odoo import api, fields, models
import json
import logging
from io import BytesIO, StringIO
import csv
import io
import xlwt
import base64
_logger = logging.getLogger(__name__)
try:
import xlsxwriter
except ImportError:
_logger.debug("Can not import xlsxwriter`.")
class Bo... | StarcoderdataPython |
6562574 | <filename>logger/transforms/derived_data_transform.py
#!/usr/bin/env python3
import sys
from os.path import dirname, realpath
sys.path.append(dirname(dirname(dirname(realpath(__file__)))))
from logger.transforms.transform import Transform # noqa: E402
###############################################################... | StarcoderdataPython |
9697176 | """
https://practice.geeksforgeeks.org/problems/arrange-consonants-and-vowels/
Given a singly linked list of size N containing only English Alphabets. Your task is to complete the function arrangeC&V(), that arranges the consonants and vowel nodes of the list it in such a way that all the vowels nodes come before the ... | StarcoderdataPython |
8055499 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2019 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this ... | StarcoderdataPython |
30013 | <reponame>Simage/TileMapBase
__version__ = "0.4.6"
from .tiles import init, get_cache
from .mapping import project, to_lonlat, Extent, Plotter, extent_from_frame
from .utils import start_logging
from . import tiles
from . import mapping
from . import utils
from . import ordnancesurvey
| StarcoderdataPython |
4989973 | <filename>data/migrations/versions/d17c695859ea_delete_old_appr_tables.py<gh_stars>1000+
"""
Delete old Appr tables.
Revision ID: d17c695859ea
Revises: 5<PASSWORD>
Create Date: 2018-07-16 15:21:11.593040
"""
# revision identifiers, used by Alembic.
revision = "d17c695859ea"
down_revision = "5d463ea1e8a8"
import sqla... | StarcoderdataPython |
11226376 | import sys
sys.path.append('../../')
from cop_e_cat.copecat import CopECat, CopECatParams
import numpy as np
from sklearn import preprocessing
import pickle
import os
import pandas as pd
state_feats = ['anchor_age', 'patientweight', 'gender',
'cad', 'afib', 'chf', 'ckd', 'esrd', 'paralysis', 'parathyroid',
... | StarcoderdataPython |
6449717 | # Some utility tools to handle rising and setting etc.
from __future__ import print_function, unicode_literals, absolute_import, division
import traceback
import struct
import os
import json
import numpy as np
import yaml
from tornado.web import RequestHandler
from tornado.escape import json_encode
from astropy.io imp... | StarcoderdataPython |
4816419 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Build information for this service.
Auto-generated during the build process - do not modify
"""
class BuildInfo(object):
"""Current build info"""
repo_name = 'ember-falcon-mongo'
service_type = 'demo'
service_name = 'backend-falcon'
version = '0.9.9'
... | StarcoderdataPython |
11326240 | <reponame>nealholt/python_programming_curricula
import random, robot
from functions import *
class AI2(robot.Robot):
def __init__(self, screen, color,name):
super().__init__(screen, color,name)
def isInDirection(self,row,col,direction):
if direction == 'north':
return row<self.row
... | StarcoderdataPython |
3219808 | from directx.types import *
from directx.d3d import *
#********************************************************************
# Typedefs and constants
#********************************************************************
try:
#SDK April 2006 - you can change the
#.dll to a another one if you know what you are... | StarcoderdataPython |
1900310 | def mutate_string(string, position, character):
return (string[:position]) + character + (string[position+1:])
| StarcoderdataPython |
9610478 |
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from datetime import date
class User(AbstractUser):
username = models.CharField(max_length=50,blank=True, null=True,unique=True)
ema... | StarcoderdataPython |
4866383 | from .worker import Worker
class SingleWorker(Worker):
"""
Wrapper for an ARENA task that runs once at startup.
"""
| StarcoderdataPython |
1681473 | <filename>probeye/definition/sensor.py
# standard library
from typing import Union, List, Tuple, Optional
# third party imports
import numpy as np
# local imports
from probeye.subroutines import process_spatial_coordinates
class Sensor:
"""
Base class for a sensor of the forward model. In its simplest form ... | StarcoderdataPython |
5001347 | <reponame>KIRITOLTR/adversarial
from pylearn2.utils import serial
import sys
_, model_path = sys.argv
model = serial.load(model_path)
from pylearn2.gui.patch_viewer import make_viewer
space = model.generator.get_output_space()
from pylearn2.space import VectorSpace
from pylearn2.config import yaml_parse
import numpy as... | StarcoderdataPython |
4905875 | <gh_stars>1-10
from core import Files
from library.stigma.application import Box
from library.stigma.helper import kivyBuilder
kivyBuilder(Files.apppath, 'model', 'builder', 'Popup.kv')
class GamePopup(Box):
def __init__(self):
super(GamePopup, self).__init__() | StarcoderdataPython |
11313147 | <reponame>imshubham27/Hacktoberfest-2020
# Python3 program to print DFS traversal
# from a given given graph
from collections import defaultdict
# This class represents a directed graph using
# adjacency list representation
class Graph:
# Constructor
def __init__(self):
# default dictionary to stor... | StarcoderdataPython |
5143474 | from trackers.opencv_tracker import CSRTTracker, KCFTracker
from trackers.pysot_trackers import SiamMaskTrackerV2, SiamRPNTracker
from trackers.siamese_mask_tracker import SiamMaskTracker
tracker_symbols = [
"SiamMask",
"SiamMaskV2",
"SiamRPN",
"CSRT",
"KCF",
]
def factory(symbol_str, is_cpu=Tru... | StarcoderdataPython |
3519213 | from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
# Create your models here.
class Blog(models.Model):
author= models.CharField(max_length=100)
title = models.CharField(max_length=100, unique=True)
content = models.TextField()
category_id = models.... | StarcoderdataPython |
3445129 | <filename>code/cnn.py
import torch.nn as nn
from torch.autograd import Variable
class CNN(nn.Module):
def __init__(self, in_shape, n_classes):
super().__init__()
c, w, h = in_shape
pool_layers = 2
fc_h = int(h / 2**pool_layers)
fc_w = int(w / 2**pool_layers)
self.fe... | StarcoderdataPython |
8100437 | <filename>utils.py
# -*- coding: utf-8 -*-
import sys
from pathlib import Path
def setup_folder(path):
"""
Prepare the empty folder.
Parameters
----------
path : String
Designated empty folder. All existing files are deleted.
"""
# Create the folder if necessary.
Path(path).mkd... | StarcoderdataPython |
4813147 | <reponame>StephanSiemen/blendernc
#!/usr/bin/env python3
import time
import numpy as np
# TODO: Add debug - logger option as a setting of the Add-On
class Timer:
def __init__(self):
self.timestamps = {}
self.nolabel = []
self.tmp = []
def tick(self, label=""):
if label == ""... | StarcoderdataPython |
6609024 | import pytest
@pytest.mark.dependency(depends=[
'tests/test_0001_html.py::test_attribute_dict',
'tests/test_0001_html.py::test_attribute_list',
], scope='session')
def test_node_api():
pass
| StarcoderdataPython |
3597449 | """[Named module]
"""
# Copyright 2020 BlueCat Networks (USA) Inc. and its affiliates
#
# 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
#
# Unles... | StarcoderdataPython |
3395136 | from ReportGenMarkdown import *
class ReportGenFactory:
def __init__(self):
self.report_to_gen = {
"Markdown": ReportGenMarkdown,
}
def get_report_gen(self, report_gen, max_number_of_classes, portfolio_info, report_repository, github_branch):
if report_gen in self.report_t... | StarcoderdataPython |
5050791 | <filename>scripts/next_step_assignment_imp_ssqc.py
#!/usr/bin/env python
from EPPs.common import StepEPP
from pyclarity_lims.entities import Protocol
class AssignNextStep(StepEPP):
_use_load_config = False # prevent the loading of the config file
"""
This script assigns all output artifacts in a containe... | StarcoderdataPython |
8191993 | import yaml
from .types import Variable
class VarsParser:
vars_to_remove = [
# Special variables
# https://docs.ansible.com/ansible/latest/reference_appendices/special_variables.html
'ansible_check_mode', 'ansible_dependent_role_names', 'ansible_diff_mode', 'ansible_forks',
'ansib... | StarcoderdataPython |
9623632 | def cvd_condensate(z, z2, temp, p, Gp, Np, Vo):
"""
Calculate volatile oil-gas ratio of condensate from Constant-Volume Depletion (CVD) Study
Walsh and Towler (1995)
Inputs
z: measured gas-phase compressibility factor (array)
z2: measured two-phase compressibility factor (array)
p: measured... | StarcoderdataPython |
11316245 | import pygame
class MapCursor(object):
def __init__(self, x, y, image, frame=0, visible=True):
self.x = x
self.y = y
self.image = image
self.frame = frame
self.visible = visible
def render(self, dest: pygame.Rect):
if self.visible:
self.image.render(... | StarcoderdataPython |
8106430 | # This is a very very very very very very very very very very very very very very very very very very very very very long line.
# pylint: disable=line-too-long
"""Make sure enable/disable pragmas work for messages that are applied to lines and not syntax nodes.
A disable pragma for a message that applies to nodes is a... | StarcoderdataPython |
9758830 | import numpy as np
import pandas as pd
from lifetimes.utils import coalesce, calculate_alive_path, expected_cumulative_transactions
from scipy import stats
__all__ = [
'plot_period_transactions',
'plot_calibration_purchases_vs_holdout_purchases',
'plot_frequency_recency_matrix',
'plot_probability_alive... | StarcoderdataPython |
3446067 | from heapq import heappush, heappop
class Heap():
_list: list
def __init__(self) -> None:
self._list = list()
def push(self, elem):
heappush(self._list, elem)
def pop(self):
elem = heappop(self._list)
return elem
def __len__(self):
return len(self._list)
... | StarcoderdataPython |
3443652 | <reponame>jdehotin/Clockworkfordynamo<filename>nodes/1.x/python/View.SetPhase.py
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.Elements)
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistenc... | StarcoderdataPython |
110317 | from cky import CKY
from chart import CHART
import json
def main():
with open("text.txt") as f:
sentence = f.read().split()
print("sentence : %s\n" %sentence)
with open("rule.json", 'r') as f:
json_dict = json.load(f)
grammar = json_dict["gram"]
dictionary = json_dict["... | StarcoderdataPython |
1807245 | """ You are given two strings s1 and s2 of equal length consisting of letters "x"
and "y" only. Your task is to make these two strings equal to each other. You
can swap any two characters that belong to different strings, which means:
swap s1[i] and s2[j]. Return the minimum number of swaps required to make ... | StarcoderdataPython |
3418989 | from graphene import ID, Int, String
class IDInput:
id = ID(required=True)
class CreateUploadInput:
kind = Int(required=True)
name = String(required=True)
mimetype = String(required=True)
| StarcoderdataPython |
1627059 | import os
import autofit as af
from test_autolens.integration import integration_util
from test_autolens.simulate.interferometer import simulate_util
from autofit.optimize.non_linear.mock_nlo import MockNLO
def run(
module,
test_name=None,
non_linear_class=af.MultiNest,
config_folder="config",
po... | StarcoderdataPython |
3343588 | """Test the validation module"""
import os
import re
import sys
import tempfile
import warnings
from functools import partial
from time import sleep
import pytest
import numpy as np
from scipy.sparse import coo_matrix, csr_matrix
from sklearn.exceptions import FitFailedWarning
from sklearn.model_selection.tests.test_... | StarcoderdataPython |
3593954 | import numpy
from src import Gear
class Flank:
def __init__(self, side, pressure_angle, beta, mn, z):
self.__side = side
self.__normal_pressure_angle = pressure_angle
self.__transverse_pressure_angle = calc_transverse_pressure_angle(pressure_angle, beta)
self.__base_circle_diamete... | StarcoderdataPython |
11386264 | import os
from httplib import HTTPConnection
from jinja2 import Environment, FileSystemLoader
from vmw.vco.generated.VSOWebControlService_types import *
from vmw.ZSI.parse import ParsedSoap
class OperationResponse(object):
tpl_env = Environment(loader=FileSystemLoader(os.path.dirname(__file__) + '/xml/responses'... | StarcoderdataPython |
135203 | <reponame>Maarten-vd-Sande/ANANSE<filename>ananse/network.py
#!/usr/bin/env python
# Copyright (c) 2009-2019 <NAME> <<EMAIL>>
#
# This module is free software. You can redistribute it and/or modify it under
# the terms of the MIT License, see the file COPYING included with this
# distribution.
"""Build gene regulator... | StarcoderdataPython |
3233860 | #!/usr/bin/env python
# -*- coding:UTF-8 -*-
# Copyright (c) 2014 <NAME>
#
# 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 us... | StarcoderdataPython |
9632020 | #!/usr/bin/env python
import socket
import sys
TCP_IP = '127.0.0.1'
TCP_PORT = 5000
BUFFER_SIZE = 20000
PROGRAM = "begin()\nfor i in range(4):\n\tforward(2);\n\tright()\nend()\n"
# Use: ./robot_program_client.py <HOST> <PORT>
if __name__ == "__main__":
if (len(sys.argv)>1):
TCP_IP = sys.argv[1]
TCP_PORT =... | StarcoderdataPython |
5115614 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from solution import Solution
# n = 4
# edges = [[1, 0], [1, 2], [1, 3]]
n = 6
edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
sol = Solution()
res = sol.findMinHeightTrees(n, edges)
print(res)
| StarcoderdataPython |
12847958 | #!/usr/bin/env python
"""
==============
Weighted Graph
==============
An example using Graph as a weighted network.
"""
# Author: <NAME> (<EMAIL>)
import matplotlib.pyplot as plt
import networkx as nx
def readEdgeFile(edgeFileName, pageRankFileName):
import os
assert(os.path.exists(edgeFileName))
page_ra... | StarcoderdataPython |
134256 | <filename>fem/utilities/command_dispatcher/test.py
import inspect
def check_types(*args):
def check_args(func, *args2):
types = tuple(map(type, args2))
for i in range(len(types)):
if not isinstance(types[i], args[i]):
raise TypeError("Argument types for %s%s do not ma... | StarcoderdataPython |
3593279 | <filename>python/python/code_o4/test_sum_matrix.py
from sum_matrix import add_matrix
def test_func_adds_list_vlaues():
x = [[1,2,3], [4,5,6], [7,8,9]]
actual = add_matrix(x)
expected = [6, 15, 24]
assert actual == expected
def test_empty_matrix_returns_zero():
x = [[]]
actual = add_matrix(x)
... | StarcoderdataPython |
1906829 | number = int(input())
def less(number):
arr = []
for i in range(1, number+1):
if i**2 <= number:
arr.append(str(i**2))
else:
break
return " ".join(arr)
print(less(number))
| StarcoderdataPython |
3542944 | <filename>generate_3DMarket_bodymesh.py
"""
Demo of HMR.
Note that HMR requires the bounding box of the person in the image. The best performance is obtained when max length of the person in the image is roughly 150px.
When only the image path is supplied, it assumes that the image is centered on a person whose leng... | StarcoderdataPython |
11345133 | <filename>bitbucket_server/scan_bitbucket_server.py
from argparse import ArgumentParser
import stashy
import pprint
import re
import datetime
parser = ArgumentParser()
parser.add_argument("-s", "--server", dest="server", required=True,
help="The Bitbucket Server host URL, formatted as https://hostn... | StarcoderdataPython |
130942 | <filename>tests/garage/experiment/test_local_runner.py
import gym
import pytest
import torch
from garage.envs import GarageEnv, normalize
from garage.experiment import deterministic, LocalRunner
from garage.plotter import Plotter
from garage.sampler import LocalSampler
from garage.torch.algos import PPO
from garage.to... | StarcoderdataPython |
11373051 | <reponame>meigrafd/Sample-Code
#!/usr/bin/python
# coding: utf-8
#
# http://www.forum-raspberrypi.de/Thread-bild-per-raspistill-in-python?pid=146362#pid146362
#
import time, picamera, RPi.GPIO as GPIO, signal
#------------------------------------------------------------------------
PIR_PIN = 17
# to use RaspberryPi gp... | StarcoderdataPython |
3461738 | def fibonacci(n):
if n in [1,2]:
return 1
return fibonacci(n-2)+fibonacci(n-1)
n=int(input("Give the number to check for Fibonacci: \n"))
print(n," no Fibonacci number is ",fibonacci(n)) | StarcoderdataPython |
6492310 | <filename>mediaplatform/migrations/0017_index_media_item_updated_at_and_published_at.py
# Generated by Django 2.1.1 on 2018-09-25 15:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mediaplatform', '0016_add_download_mediaitem_permission'),
]
... | StarcoderdataPython |
1681818 | <reponame>12remember/QRLtoDatabase<gh_stars>1-10
import plyvel
import argparse
import base64
import binascii
from datetime import datetime
import json
import sys
from qrl.core.PaginatedData import PaginatedData
from qrl.core.PaginatedBitfield import PaginatedBitfield
from qrl.core.misc.db import DB
from qrl.generated... | StarcoderdataPython |
11357103 |
def doc2vec(raw_data,param):
if param['method']=='bow':pass
| StarcoderdataPython |
292270 | import inspect
import os
import datetime
from .inspect_utils import get_parent_frame_file
__author__ = 'weijia'
def find_root_path(file_path, root_folder_name):
in_file_path = file_path
folder_name = None
while folder_name != root_folder_name:
folder_name = os.path.basename(file_path)
# l... | StarcoderdataPython |
9760870 | from stix_shifter_utils.utils.base_entry_point import BaseEntryPoint
import json
class EntryPoint(BaseEntryPoint):
def __init__(self, connection={}, configuration={}, options={}):
super().__init__(options)
if connection:
self.setup_transmission_simple(connection, configuration) | StarcoderdataPython |
9682468 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('df_user', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='receiveinfo',
name='a... | StarcoderdataPython |
9786170 |
import statistics
class SimulationStatistics:
def __init__(self, simulationResultList):
self.simulationResultList = simulationResultList
def PrintSimulationStatistics(self):
minMoves = min(self.simulationResultList, key=lambda x: x.moves)
maxMoves = max(self.simulationResultList... | StarcoderdataPython |
5059696 | <gh_stars>0
# Generated by Django 2.2.6 on 2019-10-30 09:18
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('neighbourhood', '0001_initial'),
]
operations = [
migrations.A... | StarcoderdataPython |
6703663 | from datetime import datetime
from api import utils
from exchanges.exchange import Exchange
from strategies.strategy import Strategy
class Runner(Strategy):
def __init__(self, exchange: Exchange, timeout=60, *args, **kwargs):
super().__init__(exchange, timeout, *args, **kwargs)
self.buy_price = 0... | StarcoderdataPython |
11278203 | <reponame>Ubtohts/infinitydownloader<filename>Home/models.py
from django.db import models
# Create your models here.
class song(models.Model):
song = models.CharField(max_length=122)
| StarcoderdataPython |
1627185 | <reponame>bpow/CNVpytor<gh_stars>0
from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
exec(open('cnvpytor/version.py').read())
setup(
name='CNVpytor',
version=__version__,
author='<NAME>, <NAME>, <NAME>',
author_email='<EMAIL>',
packages=['cnvpytor'],... | StarcoderdataPython |
11390552 | # Copyright 2018 Datawire Inc.
#
# 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... | StarcoderdataPython |
9667818 | <filename>sitemap.py
#!/usr/bin/env python
__author__ = '<NAME>'
import cgi
import os
#from google.appengine.ext import webapp
#from google.appengine.ext.webapp.util import run_wsgi_app
import webapp2 as webapp
from datetime import datetime
from google.appengine.api import datastore
from google.appengi... | StarcoderdataPython |
1932113 | import argparse
from collections import Counter
from collections import defaultdict
from functools import reduce
from operator import add
from string import Formatter
import input
import requests
from termcolor import colored
NODE_LOGS = "/app/kibana#/discover?_g=(time:(from:now-1y,to:now))&_a=(columns:!(_source),ind... | StarcoderdataPython |
154288 | # $Id: module_index.py 2790 2008-02-29 08:33:14Z cpbotha $
class emp_test:
kits = ['vtk_kit']
cats = ['Tests']
keywords = ['test', 'tests', 'testing']
help = \
"""Module to test DeVIDE extra-module-paths functionality.
"""
| StarcoderdataPython |
3389750 | <filename>game_map.py
from __future__ import annotations
from typing import Iterable, Iterator, Optional, TYPE_CHECKING
import numpy as np
from numpy.lib.shape_base import tile
from tcod.console import Console
from entity import Actor, Item
import tile_types
if TYPE_CHECKING:
from engine import Engine
from e... | StarcoderdataPython |
1839274 | import os
import pytest
from ._util import (
assert_realizes_as,
configured_file_sources,
find,
user_context_fixture,
)
SCRIPT_DIRECTORY = os.path.abspath(os.path.dirname(__file__))
FILE_SOURCES_CONF = os.path.join(SCRIPT_DIRECTORY, "basespace_file_sources_conf.yml")
skip_if_no_basespace_access_toke... | StarcoderdataPython |
11223835 | <filename>metaappscriptsdk/examples/db_api/db_upload_data.py<gh_stars>1-10
import os
from metaappscriptsdk import MetaApp
META = MetaApp()
log = META.log
os.chdir(os.path.dirname(os.path.abspath(__file__)))
__DIR__ = os.getcwd() + "/"
upload_file = open(__DIR__ + 'assets/load_data_sample.tsv', 'rb')
configuration ... | StarcoderdataPython |
8113183 | from django.db import models
from django.utils import timezone
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.utils.translation import gettext_lazy as _
from django.contrib.auth import get_user_model
class UserProfileManager(BaseUserManager):
def create_us... | StarcoderdataPython |
6809 | #!/usr/bin/python3
def args(args):
lenn = len(args) - 1
if lenn == 0:
print("0 arguments.")
elif lenn == 1:
print("{0} argument:".format(lenn))
print("{0}: {1}".format(lenn, args[lenn]))
elif lenn > 1:
print("{0} arguments:".format(lenn))
for i in range(lenn):
... | StarcoderdataPython |
6505228 | from Tile import tile
class coal (tile):
def __init__(self,parentWorld,colRow):
super().__init__(parentWorld,colRow,14,1,255)
self.durability = 40
self.drop = 7
def setter(parentWorld, colRow):
x = coal(parentWorld, colRow)
return x
| StarcoderdataPython |
1806693 | <filename>world.py
"""
Copyright 2011 <NAME> & contributors. 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
... | StarcoderdataPython |
6458928 | from django.urls import re_path
from app import consumers
websocket_urlpatterns = [
re_path(r'ws/(?P<user_name>\w+)/$', consumers.Consumer.as_asgi()),
] | StarcoderdataPython |
3222590 | import panscore
def load(filename:str)->panscore.Score:
#打开文件,返回panscore.Score对象
#由于编码不确定,先用二进制打开文件
with open(filename,'rb') as f:
file=f.read()
#读取编码
if(b"Charset=UTF-8" in file):
encoding="utf-8"
else:
encoding="shift-JIS"
#分块
blocks=[]
block=... | StarcoderdataPython |
9786173 | #!/usr/bin/env python
# Copyright (c) 2011, <NAME>, <NAME>, TU Darmstadt
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
#... | StarcoderdataPython |
1878908 | from pathlib import Path
from datetime import datetime, timedelta
from src.settings import envs
from airflow import DAG
from airflow.models import Variable
from airflow.operators.python_operator import PythonOperator
from airflow.utils.dates import days_ago
from airflow.hooks.postgres_hook import PostgresHook
import lo... | StarcoderdataPython |
5135920 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the superReducedString function below.
def superReducedString(s):
i=0
while i < len(s):
if i+1 == len(s):
break
if s[i] == s[i+1]:
s = s.replace(s[i]+s[i+1], '',1)
i = 0
... | StarcoderdataPython |
33527 | # -*- coding: utf-8 -*-
import redis
import os
import telebot
import math
import random
import threading
from telebot import types
from emoji import emojize
from pymongo import MongoClient
token = os.environ['TELEGRAM_TOKEN']
bot = telebot.TeleBot(token)
admins=[441399484]
games={}
client1=os.environ['database']
clie... | StarcoderdataPython |
9632854 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2017-10-31 13:59
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('csyllabusapi', '0009_courseprogram'),
]
operations = [
migrations.Rem... | StarcoderdataPython |
8056494 | <reponame>linzehui/fastNLP
"""
Pipe用于处理通过 Loader 读取的数据,所有的 Pipe 都包含 ``process`` 和 ``process_from_file`` 两种方法。
``process(data_bundle)`` 传入一个 :class:`~fastNLP.io.DataBundle` 类型的对象, 在传入的 `data_bundle` 上进行原位修改,并将其返回;
``process_from_file(paths)`` 传入的文件路径,返回一个 :class:`~fastNLP.io.DataBundle` 类型的对象。
``process(data_bundle)`` 或... | StarcoderdataPython |
82081 | import uuid
import cv2
OUTPUT_IMAGE_FOLDER = "./output/"
OUTPUT_FILE_TYPE = ".jpg"
def save_image_with_internal_name(img):
internal_name = str(uuid.uuid1()) + OUTPUT_FILE_TYPE
cv2.imwrite(OUTPUT_IMAGE_FOLDER + internal_name, img)
return internal_name
| StarcoderdataPython |
9686504 | <filename>Python_Hard_Way_W2/ex31_newgame.py
print("""You enter a dark room with two doors.
Do you go through door #1 which leads to a castle or door #2 that leads to an underwater mission?""")
door = input("> ")
if door == "1":
print("There's a drawbridge that isn't open.")
print("What will you do to get across?"... | StarcoderdataPython |
5106011 | <filename>innvestigate/tests/utils/tests/test_dryrun.py
# Begin: Python 2/3 compatibility header small
# Get Python 3 functionality:
from __future__ import\
absolute_import, print_function, division, unicode_literals
from future.utils import raise_with_traceback, raise_from
# catch exception with: except Exception ... | StarcoderdataPython |
172353 | <reponame>MeowMeowLady/Towards-Neuro-Seg-Macaque-Brain<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Created on 19-7-31 下午6:02
IDE PyCharm
@author: <NAME>
this script is used to split training and validation sets by generating list-txt.
"""
from os.path import join as opj
import random
from glob import glob
import os
t... | StarcoderdataPython |
8195393 | import unittest, os
from URLShortener import URLShortener
import string, random
def generateRandomString(size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
class TestURLShortener(unittest.TestCase):
def setUp(self):
self.dbfile = "/tmp/testshorten... | StarcoderdataPython |
1797006 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import math
class QueueNode:
def __init__(self, priority, data=None):
assert type(priority) is int and priority >= 0
self.priority = priority
self.data = data
def __repr__(self):
return str((self.priority, self.data))
class Priority... | StarcoderdataPython |
9706386 | <filename>Qbox2.py
import sys
from sys import stdin, stdout
def maxSum(arr, n, k):
res = 0
for i in range(k):
res += arr[i]
curr_sum = res
for i in range(k,n):
curr_sum += arr[i] - arr[i-k]
res = max(res, curr_sum)
return res
def minSum(arr,n,k):
win_sum=0
... | StarcoderdataPython |
5136699 | import rsa.utils.plot_utils as pu
import gym
#from gym.wrappers import LazyFrames
import os
import numpy as np
import moviepy.editor as mpy
class SimpleVideoSaver(gym.Wrapper):
def __init__(self, env: gym.Env, video_dir,
from_render=False,
speedup=1,
camera=No... | StarcoderdataPython |
11294481 | __title__ = 'spacy_symspell'
__version__ = '0.1.2'
__summary__ = 'spaCy pipeline component for spelling correction using sysmepll.'
__url__ = 'https://github.com/xwiz/spacy_symspell'
__author__ = 'Xwiz'
__email__ = '<EMAIL>'
__license__ = 'MIT' | StarcoderdataPython |
5187682 | <reponame>smhooten/MRI-Learn
import numpy as np
import matplotlib.pyplot as plt
import scipy.io
from MRInet import CNN_SUBJECT_LEVEL
SAVE_DIR = './CNN_SUBJECT_LEVEL_RESULTS2/'
# HYPERPARAMETER SELECTIONS
batch_size = 10
tra_val_split = 0.8
epochs = [10, 20, 30]
learning_rates = [1e-8, 1e-6, 1e-4]
# FEATURE SELECTIO... | StarcoderdataPython |
8051817 | <gh_stars>10-100
foo = 1
| StarcoderdataPython |
1914099 | <filename>apple/bundling/clang_support.bzl
# Copyright 2017 The Bazel 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
#
# http://www.apache.org/licenses/LICEN... | StarcoderdataPython |
8067561 | <reponame>ertyurk/bugme<filename>app/routes/v1/api.py
from fastapi import APIRouter, Depends
from .endpoints import users, brands, apps, bugs, slack, clickup, jira
from app.middlewares.auth.jwt_bearer import JWTBearer
token_listener = JWTBearer()
router = APIRouter()
router.include_router(users.router, prefix="/user... | StarcoderdataPython |
6634915 | import openml
def download_and_transform():
"""Download data from openml and apply basic transformations."""
dataset = openml.datasets.get_dataset(42092)
df, y, _, _ = dataset.get_data(
dataset_format="dataframe", target=dataset.default_target_attribute
)
df["price"] = y
df = df[(df["... | StarcoderdataPython |
394600 | <filename>compute_hyperv/tests/unit/cluster/test_driver.py<gh_stars>10-100
# Copyright 2016 Cloudbase Solutions SRL
# 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 Licens... | StarcoderdataPython |
1841026 | <gh_stars>1-10
from Crypto.PublicKey import RSA
import numpy as np
# Generate Keys
key = RSA.generate(2048)
# Get keys form RSA Key
public_key = key.publickey().exportKey('PEM')
pubkey = key.publickey().n
pkey = pubkey.to_bytes(256, 'big')
reversed_pubkey = np.flip(np.frombuffer(bytearray(pkey), dtype=np.uint8, count... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.