id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
124935 | import os
import scicopia.arangodoc as arangodoc
from scicopia.utils.arangodb import connect, select_db
def connection(col):
# use a config to a test database
config = arangodoc.read_config()
arangoconn = connect(config)
db = select_db(config, arangoconn, create=True)
if db.hasCollection(col):
... | StarcoderdataPython |
118669 | import json
import numpy as np
def to_ndarray(obj, dtype=np.float64):
"""
Greedily and recursively convert the given object to a dtype ndarray.
"""
if isinstance(obj, dict):
for k in obj:
obj[k] = to_ndarray(obj[k])
return obj
elif isinstance(obj, list):
try:
... | StarcoderdataPython |
1637864 | <reponame>Rothamsted-Ecoinformatics/YieldBookDataTools<gh_stars>0
import pytesseract
import cv2
import numpy as np
import re
from pytesseract.pytesseract import Output
img = cv2.imread('D:\\Code\\python\\workspace\\YieldBookDataTools\\Text Mining\\YieldBook1965_010.jpg')
img = cv2.resize(img, None, fx=1.5, fy=1.5, i... | StarcoderdataPython |
1629323 | <reponame>fabiocoutoaraujo/CursoVideoPython
# 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89
# a, b, c
n = int(input('Digite um número: '))
i = 3
a = 0
b = 1
print(f'Sequência de fibonacci: {a}, {b}', end='')
while i <= n:
c = a + b
print(f', {c}', end='')
a = b
b = c
i += 1
print('.')
| StarcoderdataPython |
3273904 | <gh_stars>0
from colourscheme import *
from table import Table
from barchart import BarChart, BarChart3D, PrettyBarChart
from linegraph import LineGraph, InterpolatingLineGraph
from piechart import PieChart, PieChart3D
from rasterizer import *
| StarcoderdataPython |
1788611 | <reponame>fletchgraham/colosseum<gh_stars>0
from tests.utils import W3CTestCase
class TestFlexMarginNoCollapse(W3CTestCase):
vars().update(W3CTestCase.find_tests(__file__, 'flex-margin-no-collapse'))
| StarcoderdataPython |
3232937 | <filename>GeeksForGeeks/tree_traversals.py
# Author: <NAME>
# preorder posrorder and inorder traversal in a binary tree
# Link: https://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/
# Define a Node for tree
class Node:
def __init__(self,val):
self.val = val
self.left = Non... | StarcoderdataPython |
70703 | import gzip
import os
import sys
import torch
import torch.nn as nn
from torch.autograd import Variable
import math
import torch.nn.functional as F
import numpy as np
from torchtext.utils import download_from_url
from pytorch_pretrained_bert import BertTokenizer, BertModel, BertForMaskedLM
## Make the the multiple att... | StarcoderdataPython |
3314624 | <filename>venv/lib/python2.7/site-packages/logilab/common/test/unittest_ureports_text.py
# copyright 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# contact http://www.logilab.fr/ -- mailto:<EMAIL>
#
# This file is part of logilab-common.
#
# logilab-common is free software: you can redistribute it and/o... | StarcoderdataPython |
3202255 | <reponame>jaapbrasser/rbkcli
"""Essential module, parameters shared for rbkcli."""
import os
BASE_FOLDER = os.path.expanduser('~/rbkcli')
TARGETS_FOLDER = BASE_FOLDER + '/targets'
CONF_FOLDER = BASE_FOLDER + '/conf'
LOGS_FOLDER = BASE_FOLDER + '/logs'
SCRIPTS_FOLDER = BASE_FOLDER + '/scripts'
CMDLETS_FOLDER ... | StarcoderdataPython |
1611502 | # Copyright (c) 2021 Huayun Inc.
# hostha is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the
# Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
# http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANT... | StarcoderdataPython |
68488 | <gh_stars>0
# lower case because appears as wcl section and wcl sections are converted to lowercase
META_HEADERS = 'h'
META_COMPUTE = 'c'
META_WCL = 'w'
META_COPY = 'p'
META_REQUIRED = 'r'
META_OPTIONAL = 'o'
FILETYPE_METADATA = 'filetype_metadata'
FILE_HEADER_INFO = 'file_header'
USE_HOME_ARCHIVE_INPUT = 'use_home_a... | StarcoderdataPython |
1759604 | class Stack:
def __init__(self):
self.stack = []
def isEmpty(self):
return self.stack == []
def push(self, item):
self.stack.append(item)
def pop(self):
if (self.isEmpty()):
return None
return self.stack.pop()
def peek(self):
if (self... | StarcoderdataPython |
3288524 | <reponame>seeM/reinforcement-learning
import numpy as np
class Bandit():
"""
A k-armed bandit problem with stationary, unit-variance Gaussian-
distributed rewards and randomly generated Gaussian-distributed values.
Parameters
----------
n_arms : int
The number of arms (or actions)
... | StarcoderdataPython |
105508 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "gwells.settings")
from django.core.management import execute_from_command_line
from django.conf import settings
if settings.DEBUG:
if os.environ.get('RUN_MAIN') or os.enviro... | StarcoderdataPython |
1780353 | <reponame>MilkywayPwns/infprj2
import database
# this function updates the highscore of the current player
def update(name, score):
# check if we should update our score
scores = database.execute_query("SELECT * from scores WHERE name='{}'".format(name))
updateScore = True
if not len(scores):
... | StarcoderdataPython |
3254001 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Convert spark event log JSON to CSV
# @ <NAME>
from sets import Set
import argparse
import json
class SparkEvent:
prefix = "SparkListener"
def __init__(self, data):
self.event = data["Event"][len(SparkEvent.prefix):]
self.raw = "\... | StarcoderdataPython |
1747728 | <gh_stars>0
#
# Copyright (C) 2007, <NAME>
#
#http://rl-glue-ext.googlecode.com/
#
# 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 |
3231713 | <gh_stars>0
from django.shortcuts import render
from .models import Video
from django.db.models import Q
from django.http import HttpResponse
# Create your views here.
def index(request):
return render(request,'video/index.html',locals())
# 搜索
def search(request):
search_text = request.GET['search_text'] # ... | StarcoderdataPython |
1603649 | import testinfra
def test_apparmor_is_installed(host):
apparmor = host.package("apparmor")
assert apparmor.is_installed
def test_apparmor_utils_is_installed(host):
apparmor_utils = host.package("apparmor-utils")
assert apparmor_utils.is_installed
def test_apparmor_is_loaded(host):
apparmor_sta... | StarcoderdataPython |
1763755 | <reponame>aidiss/disciplines
# -*- coding: utf-8 -*-
"""Justifications for interdisciplinary work
This module checks what is the justification for interdisciplinary work.
It cheks it based on text that are available
Args:
authors
concepts
data
claim
theory
Data:
career paths : (remember biolo... | StarcoderdataPython |
3304426 | from keras.datasets import reuters
from keras.utils.np_utils import to_categorical
import numpy as np
from keras import models
from keras import layers
import matplotlib.pyplot as plt
(train_data, train_labels), (test_data, test_labels) = reuters.load_data(num_words=10000)
def vectorize_sequences(sequences, dimension... | StarcoderdataPython |
86360 | <filename>addons/io_scene_gltf2_msfs/blender/imp/gltf2_blender_image.py
# Copyright 2018-2021 The glTF-Blender-IO authors, FlyByWire Simulations, bestdani.
#
# 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 th... | StarcoderdataPython |
1602606 | def get_website_url(file_id, **kwargs):
return f"https://drive.google.com/drive/folders/{file_id}"
| StarcoderdataPython |
15200 | <reponame>Jalagarto/translator
#!/usr/bin/python3
import tkinter as tk
from tkinter import messagebox as msg
from tkinter.ttk import Notebook
from tkinter import ttk
import tkinter.font as font
import requests
class LanguageTab(tk.Frame):
def __init__(self, master, lang_name, lang_code):
super().__init_... | StarcoderdataPython |
87940 | <reponame>FMsunyh/keras-fpn<filename>core/utils/iou.py
#!/usr/bin/python3
"""
Copyright 2018-2019 Firmin.Sun (<EMAIL>)
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/li... | StarcoderdataPython |
1625330 | <reponame>DzenMorm/team_work_tattoo
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.fields.html5 import EmailField, DateField
from wtforms.validators import InputRequired, ValidationError
from .models import User
class UserForm(FlaskForm):
name = StringField('Имя', valida... | StarcoderdataPython |
1634522 | <gh_stars>1-10
from traitlets import Unicode
import json
from pathlib import Path
from traitlets import Int
from sepal_ui import sepalwidgets as sw
from sepal_ui import mapping as sm
from sepal_ui import color
import ipyvuetify as v
import pandas as pd
import ee
from ipyleaflet import WidgetControl
from component imp... | StarcoderdataPython |
4811236 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
This work is in free public domain.
This module is an extesion to module skaitvardis.
It spells numeral together with unit declension, e.g.
7s, 12h, 100$
'''
import re
from skaitvardis import *
# Daiktavardis ė : gervė
INoun3e=Inflection(affrication=(
s... | StarcoderdataPython |
4808055 | <reponame>FelixSchwarz/log_utils
# -*- coding: utf-8 -*-
# Copyright (c) 2020 <NAME>
# The source code contained in this file is licensed under the MIT license.
# SPDX-License-Identifier: MIT
import logging
from .log_proxy import l_
__all__ = ['CallbackLogger']
class CallbackLogger(logging.Logger):
"""
A `... | StarcoderdataPython |
3217699 | #!/usr/bin/env python
import os
import argparse
def get_cmd(task, sub_task, model_tag, gpu, data_num, bs, lr, source_length, target_length, patience, epoch, warmup,
gpu_type, res_fn):
cmd_str = 'bash exp_with_args.sh %s %s %s %d %d %d %d %d %d %d %d %d %s %s' % \
(task, sub_task, model_... | StarcoderdataPython |
68772 | <gh_stars>100-1000
import numpy as np
import os
import constants
from numpy.linalg import inv
from dataloader import indoor_scenes
import torch
from collections import OrderedDict, Counter
from tqdm import tqdm
def project_image_to_world(x, y, depth, cam2world, depth_intrinsic):
I = torch.zeros(4, depth.shape[0]).... | StarcoderdataPython |
46916 | <reponame>sophiaas/e3nn
# pylint: disable=not-callable, no-member, invalid-name, line-too-long, wildcard-import, unused-wildcard-import, missing-docstring, no-value-for-parameter
import unittest
from functools import partial
import torch
from e3nn import o3
class Tests(unittest.TestCase):
def test_irrep_closur... | StarcoderdataPython |
1735338 | import tkinter.filedialog
from tkinter.messagebox import showerror
import tkinter as tk
from route import Route
import matplotlib
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handl... | StarcoderdataPython |
3367754 | <gh_stars>0
from django.contrib import admin
from .models import (
Overlay,
)
@admin.register(Overlay)
class OverlayAdmin(admin.ModelAdmin):
pass
| StarcoderdataPython |
1680540 | <filename>common/code/snippets/security/blind_sqli_dyn_field_len.py
#!/usr/bin/env python3
# Reference:
# https://spencerdodd.github.io/2017/06/22/kioptrix-2/
import sys
import requests
chars = "abcdefghijklmnopqrstuvwxyz01234567890.()<>*^%$@!"
target = "192.168.56.101"
url = "http://192.168.56.101/index.php"
port =... | StarcoderdataPython |
1685241 | <filename>djmodels/__main__.py
"""
Invokes djmodels-admin when the djmodels module is run as a script.
Example: python -m djmodels check
"""
from djmodels.core import management
if __name__ == "__main__":
management.execute_from_command_line()
| StarcoderdataPython |
1727904 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 15 10:04:59 2021
@author: 18530
"""
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
name = "Hello World"
return name
@app.route('/good')
def good():
name = "Good"
return name
## おまじない
if __name__ == "__main__":
... | StarcoderdataPython |
123382 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime,timedelta
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.operators.dagrun_operator import TriggerDagRunOperator
default_args = {'owner': 'afroot03','retries': 2, 'retry_delay': timedelta(minutes=1... | StarcoderdataPython |
197215 | <filename>tamarco/core/settings/backends/etcd.py
import asyncio
import logging
import os
from concurrent.futures._base import CancelledError, TimeoutError
from typing import NewType, TypeVar
import aio_etcd
import ujson
from etcd import EtcdNotDir, EtcdResult
from tamarco.core.settings.backends.interface import Setti... | StarcoderdataPython |
3263117 | class style:
BOLD = "\033[1m"
LOW_OPAQUE = "\033[2m"
UNDERLINE = "\033[4m"
BLINK = "\033[5m"
REV_FOREGND_BACKGND = "\033[7m"
PASSWORD = <PASSWORD>"
RESET_ALL = "\033[0m"
class fgndColor:
DEFAULT = "\033[39m"
BLACK = "\033[30m"
RED = "\033[31m"
GREEN = "\033[32m"
YELLOW =... | StarcoderdataPython |
1699788 | <filename>pose_speed.py
import os
import sys
import cv2
import time
import pickle
import argparse
import torch.distributed as dist
import torch.multiprocessing as mp
from tqdm import tqdm
from PIL import Image, ImageDraw
from torchvision import transforms
from torch.nn.parallel import DistributedDataParallel
from util... | StarcoderdataPython |
3258948 | from oim_logging import get_oim_logger
import os
import requests
from requests.auth import HTTPBasicAuth
import enum
class JIRABOARD(bytes, enum.Enum):
def __new__(cls, value, jiraproject, jiraboard):
obj = bytes.__new__(cls)
obj._value_ = value
obj.project = jiraproject
obj.boardn... | StarcoderdataPython |
3248212 | import RPi.GPIO as GPIO
import signal
import time
import sys
GPIO.setmode(GPIO.BOARD)
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('192.168.5.110', 3333)
sock.bind(server_address)
sock.listen(1)
def sigint_handler(signum, instant):
... | StarcoderdataPython |
115373 | <filename>exerc_20.py
# <NAME>
# ADS UNIFIP 2020.1
# Patos-PB 03/04/2020
'''
Leia um valor inteiro correspondente à idade de uma pessoa em dias e informe-a em anos, meses e dias
Obs.: apenas para facilitar o cálculo, considere todo ano com 365 dias e todo mês com 30 dias.
Nos casos de teste nunca haverá uma situação ... | StarcoderdataPython |
82090 | import re
import json
import requests
import esprima
import ast_2_js
requests = requests.Session()
url_regex = re.compile(r"https:\/\/jsbin\.com\/[\w\W]+?\/")
null = None
false = False
true = True
document = None
this = None
def start(obj, *args, **kwargs):
return obj
def parse_jsbin(url):
headers = { "refere... | StarcoderdataPython |
3292463 | ################################################################################
#
# Implementation of Cross-entropy loss.
#
# Author(s): <NAME>
################################################################################
import torch as t
import torch.nn.functional as F
##########################################... | StarcoderdataPython |
3254727 | <reponame>AndresJejen/TempPrecipAnalisisAndServer_AFLORE
from honoluluserver.domain.station import Station
def test_station_model_init():
station = Station(
"Station1",
"Station1Name",
3,
5,
55
)
assert station.station == "Station1"
assert station.name == "Stat... | StarcoderdataPython |
94636 | <filename>pokermon/envs/holdem/env.py
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 <NAME> (<EMAIL>)
# Copyright (c) 2018 <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 w... | StarcoderdataPython |
65269 | <gh_stars>100-1000
# Check the various features of the ShTest format.
#
# RUN: rm -f %t.xml
# RUN: not %{lit} -j 1 -v %{inputs}/shtest-format --xunit-xml-output %t.xml > %t.out
# RUN: FileCheck < %t.out %s
# RUN: FileCheck --check-prefix=XUNIT < %t.xml %s
# END.
# CHECK: -- Testing:
# CHECK: PASS: shtest-format :: a... | StarcoderdataPython |
193176 | <reponame>ismlkrkmz/Dragonfire<filename>dragonfire/config.py
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
.. module:: config
:platform: Unix
:synopsis: the module that contains the configuration for the API of Dragonfire.
.. moduleauthor:: <NAME> <<EMAIL>>
"""
import os
class Config():
"""Class that ... | StarcoderdataPython |
3276871 | #!/usr/bin/python
import sdk_common
# Block in charge of deploying artifacts
class ArtifactDeployer(sdk_common.BuildStepUsingGradle):
def __init__(self, logger=None):
super(ArtifactDeployer, self).__init__('Artifact deployment', logger)
self.username = self.common_config.get_config().get_artifacto... | StarcoderdataPython |
1709808 | <filename>client-py/tests/test_keygen.py
from casperlabs_client import consts
def test_account_key_files_are_created(account_keys_directory):
for key_algorithm in consts.SUPPORTED_KEY_ALGORITHMS:
for file_suffix in (
consts.ACCOUNT_PUBLIC_KEY_FILENAME_SUFFIX,
consts.ACCOUNT_PRIVATE... | StarcoderdataPython |
178740 | # -*- coding: utf-8 -*-
"""
# @file name : compute_flops.py
# @author : TingsongYu https://github.com/TingsongYu
# @date : 2020-02-29
# @brief : 观察resnet56 及 ghost-resnet-56
"""
import os
import sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(BASE_DIR, '..'))
from ... | StarcoderdataPython |
3357426 | class RegionError(Exception):
"""
异常基类
"""
class RegionNotFoundError(RegionError):
"""
无此地区
"""
class RegionNoSuperiorError(RegionError):
"""
此地区无上级
"""
class RegionNoSubordinateError(RegionError):
"""
此地区无下级
"""
| StarcoderdataPython |
3203428 | <gh_stars>0
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 Hewlett Packard Enterprise Development LP
#
# 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... | StarcoderdataPython |
1707163 | def findDecision(obj): #obj[0]: Coupon, obj[1]: Education, obj[2]: Occupation
# {"feature": "Coupon", "instances": 8147, "metric_value": 0.4722, "depth": 1}
if obj[0]>1:
# {"feature": "Education", "instances": 5903, "metric_value": 0.4656, "depth": 2}
if obj[1]>1:
# {"feature": "Occupation", "instances": 3341,... | StarcoderdataPython |
81971 | <reponame>lace/polliwog
import numpy as np
from vg.compat import v2 as vg
from ..tri import FACE_DTYPE
def slice_triangles_by_plane(
vertices,
faces,
point_on_plane,
plane_normal,
faces_to_slice=None,
ret_face_mapping=False,
):
"""
Slice the given triangles by the given plane.
- T... | StarcoderdataPython |
3381901 | from __future__ import print_function
#
# $Id$
#
# loads scored results from different
# evaluation methods and averages them
#
# INPUT
# optional:
# -i [] : absolute input path (default: pwd/../validation)
# -o [] : absolute output path (default: pwd)
# --help : prints usage
#
# OUTPUT: for each target in each datase... | StarcoderdataPython |
3271588 | from .customstockenv import CustomStockEnv
class CustomStockEnvDefault(CustomStockEnv):
def __init__(self, data, config):
super(CustomStockEnvDefault, self).__init__(data, config)
self.prediction = False
def _predict_response(self, data):
print("Incorrect flow. Cannot predict for this env...")
exit()
| StarcoderdataPython |
3237356 | <gh_stars>1-10
from __future__ import print_function
from __future__ import absolute_import
import requests
from .exceptions import (StreamableApiClientException,
StreamableApiServerException)
from .utils import Authentication
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__version__ = '1.0.1'... | StarcoderdataPython |
4823784 | # Generated by Django 3.2.8 on 2021-11-11 20:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('appointments', '0003_remove_appointment_is_remember'),
]
operations = [
migrations.AddField(
model_name='appointment',
... | StarcoderdataPython |
35245 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('facilities', '0001_auto_20160328_1426'),
]
operations = [
migrations.AddField(
model_name='facilityunit',
... | StarcoderdataPython |
1621802 | from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('about/', views.index),
path('how-use/', views.index),
path('how-it-works/', views.index),
path('contacts/', views.index),
path('ingredient/<int:pk>', views.index),
path('search-results/', views.ind... | StarcoderdataPython |
1623367 | <filename>aiu/__init__.py
from .archiveit_collection import ArchiveItCollection, ArchiveItCollectionException
from .trove_collection import TroveCollection, TroveCollectionException
from .pandora_collection import PandoraCollection, PandoraSubject, PandoraCollectionException
from .timemap import convert_LinkTimeMap_to_... | StarcoderdataPython |
1727506 | <gh_stars>1-10
from argparse import ArgumentParser
import os
from mmseg.apis import inference_segmentor, init_segmentor, show_result_pyplot
from mmseg.core.evaluation import get_palette
from mmsegmentation.tools.prepare_segmentation_data import get_list_file_in_folder
img_dir='/home/cuongnd/PycharmProjects/open-mmla... | StarcoderdataPython |
3399041 | from django.conf.urls import patterns, include, url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^polls/', include('polls.urls', namespace='polls')),
url(r'^pages/', include('django.contrib.flatpages.urls')),
url(r'^adm... | StarcoderdataPython |
1781586 | import sys
sys.path.append(r'../')
from imagepy.core import app
app.startup.start() | StarcoderdataPython |
186019 | <filename>database/database.py
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 17 18:26:30 2020
@author: Bengi
"""
import sqlite3
from sqlite3 import Error
def sql_connection():
try:
conn = sqlite3.connect('db.sqlite')
cursor = conn.cursor()
except Error:
print(Error)
... | StarcoderdataPython |
1629972 | import logging
import os
logger = logging.getLogger()
class FileMetadata(object):
__slots__ = 'path', 'name'
def __init__(self):
self.path = None
self.name = None
def __repr__(self):
return 'my path is: ' + self.path
def findFiles(rootPath, fileSuffix='.txt'):
logger.debug... | StarcoderdataPython |
3358587 | <reponame>troylee/chinesetextnorm
#!/usr/bin/env python
#
# This script reads in a HTK MLF format label file and converts the
# encoded contents to GBK encoding.
#
import string, codecs
fin=open('vom_utt_wlab.mlf')
fout=codecs.open('vom_utt_wlab.gbk.mlf', encoding='gbk', mode='w')
while True:
sr=fin.readline()
... | StarcoderdataPython |
1672916 | <reponame>johnsbuck/MapGeneration
"""Sorts
This script contains different sorts and selection algorithms for later use.
Was mainly used for custom sorting with different comparables and practice.
"""
def mergesort(points, idx, p=None, r=None, descending=False):
if p is None:
p = 0
if r is None:
... | StarcoderdataPython |
131470 | """
shortly.app
~~~~~~~~~~~
Shortly app inspired by http://werkzeug.pocoo.org/docs/tutorial/.
:copyright: (c) 2014 by fsp.
:license: BSD.
"""
from flask import Flask
app = Flask(__name__)
from shortly import settings
app.config.from_object(settings)
import shortly.views
| StarcoderdataPython |
14076 | # Generated by Django 2.0.2 on 2018-02-17 12:17
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('printapp', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='historybayar',
name=... | StarcoderdataPython |
3376273 | <reponame>tianyu94/geetest
import random
P0_v0 = {
't': 37, 's': 0, 0: 134982529, 1: 254232810, 2: 164556709, 3: 234907349, 4: 134685994, 5: 35463984, 6: 258277946,
7: 12518857, 8: 44638621, 9: 93783641, 10: 212253739, 11: 62792472, 12: 186688352, 13: 109500232, 14: 182488077,
15: 261196188, 16: 26354094, ... | StarcoderdataPython |
3213543 | """
@Author: <NAME>
@Email: <EMAIL>
"""
JSON_FILE_FORMAT = 'JSON'
PKL_FILE_FORMAT = 'PKL'
NPY_FILE_FORMAT = 'NPY'
NPZ_FILE_FORMAT = 'NPZ'
SPARSE_NPZ_FILE_FORMAT = 'SPARSE_NPZ'
JOBLIB_FILE_FORMAT = 'JOBLIB'
OPTIMIZER_SGD = 'sgd'
OPTIMIZER_ADAM = 'adam'
OPTIMIZER_RMS = 'rms'
RELU = 'relu'
LEAKY_RELU = 'leaky_relu'
TAN... | StarcoderdataPython |
3250326 | <reponame>TWoolhouse/Libraries
from typing import Any, Iterator, Optional, Sequence, T, Union
from collections import deque
class LinkedList(Sequence[T]):
def __init__(self, value: T, next: Optional['LinkedList[T]']=None):
self.value: T = value
self.next: Union[LinkedList[T], None] = next
def ... | StarcoderdataPython |
4835881 | <gh_stars>0
from .app import CowinAPIsData
| StarcoderdataPython |
3284970 | from typing import List, Optional
import numpy as np
import torch
import torch.nn as nn
from pts import Trainer
from pts.model import PTSEstimator, Predictor, PTSPredictor, copy_parameters
from pts.transform import (
InstanceSplitter,
Transformation,
Chain,
RemoveFields,
ExpectedNumInstanceSample... | StarcoderdataPython |
75346 | <reponame>slash-segmentation/DP2
#http://www.scipy.org/Cookbook/Interpolation
from scipy import ogrid, sin, mgrid, ndimage, array
import numpy
x,y = ogrid[-1:1:3j,-1:1:3j]
fvals = sin(x)*sin(y)
newx,newy = mgrid[-1:1:6j,-1:1:6j]
x0 = x[0,0]
y0 = y[0,0]
dx = x[1,0] - x0
dy = y[0,1] - y0
# make indicies go from 0 to ... | StarcoderdataPython |
1761340 | <gh_stars>0
# Import libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Import dataset
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, :-1].values
Y = dataset.iloc[:, -1].values
print(f"X = {X}")
print(f"Y = {Y}")
print()
# Split Dataset: Training Set and Test Set
X... | StarcoderdataPython |
1656085 | from errors import *
from pymongo.collection import Collection
class Helper:
"""
Methods that simplify MongoDB collection reading and writing.
id_structure
- must be a string
- example of an id_structure: "_id": 1122334455667788
_id is the id_structure in... | StarcoderdataPython |
185617 | <reponame>iterait/cxflow
"""
Config module providing util functions for handling YAML configurations.
"""
from typing import Tuple, Any, Iterable, Optional
import logging
from copy import deepcopy
import ruamel.yaml
from .yaml import load_yaml, reload
def parse_arg(arg: str) -> Tuple[str, Any]:
"""
Parse CL... | StarcoderdataPython |
194420 | from d6tflow.tasks import TaskData
from d6tflow.targets.h5 import H5PandasTarget, H5KerasTarget
class TaskH5Pandas(TaskData):
"""
Task which saves to HDF5
"""
target_class = H5PandasTarget
target_ext = 'hdf5'
class TaskH5Keras(d6tflow.tasks.TaskData):
"""
Task which saves to HDF5
"""
... | StarcoderdataPython |
1782808 | #<pycode(py_idp)>
#----------------------------------------------------------------------------
# P R O C E S S O R M O D U L E S C O N S T A N T S
#----------------------------------------------------------------------------
# ----------------------------------------------------------------------
# p... | StarcoderdataPython |
172245 | <reponame>TengGao/pandasxlframer
from setuptools import setup, find_packages
with open("README.md", encoding="utf-8") as f:
readme = f.read()
setup(
name="PandasXlFramer",
version="0.11",
description="PandasXlFramer",
long_description=readme,
long_description_content_type="text/markdown",
... | StarcoderdataPython |
77319 | <filename>v0.1/concentration_ponds/utils/SizePond.py
import classes as cl
import datetime
import formulas as f
import json
import math
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.dates import (MONTHLY, DateFormatter, rrulewrapper, RRuleLocator, drange)
import numpy as np
import pandas as pd
from p... | StarcoderdataPython |
694 | from datetime import datetime
from difflib import unified_diff
from logging import basicConfig, getLogger, INFO
import os
from pathlib import Path
import shutil
import subprocess
import sys
import yaml
from urllib.parse import urlparse
from notebook import notebookapp
from IPython.core.display import HTML
WORKDIR = ... | StarcoderdataPython |
1722546 | <reponame>invinst/CPDBv2_backend
from officers.index_aliases import officers_index_alias
from officers.indexers import (
OfficersIndexer,
OfficerCoaccusalsIndexer,
)
class OfficerSummaryTestCaseMixin(object):
def setUp(self):
officers_index_alias.write_index.delete(ignore=404)
officers_ind... | StarcoderdataPython |
1680689 | #!/usr/bin/env python
# encoding: utf-8
"""
testOverrideSet.py
Created by <NAME> on 27 Sep 2015.
Licensed under a 3-clause BSD license.
Revision history:
27 Sep 2015 <NAME>
Initial version
"""
from __future__ import division
from __future__ import print_function
import unittest
import numpy as np
import w... | StarcoderdataPython |
133716 | from typing import Any, Mapping
from ghaudit.query.sub_query_common import SubQueryCommon
from ghaudit.query.utils import PageInfo
class OrgRepoQuery(SubQueryCommon):
FRAGMENTS = ["frag_org_repo_fields.j2", "frag_org_repo.j2"]
def __init__(self) -> None:
SubQueryCommon.__init__(
self,
... | StarcoderdataPython |
4803308 | <reponame>joshlam123/optimization_algorithms<gh_stars>0
import math
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import pandas as pd
import seaborn as sns
import random
# Display all floats rounded off to 1 decimal place
pd.options.display.float_format = '{:,.1f}'.format
# ... | StarcoderdataPython |
1692855 | <filename>blog_api/apps/core/fields.py
from django.db import models
from .utils import generate_slug, generate_unique_slug
class AutoSlugField(models.SlugField):
def __init__(self, *args, populate_from=None, max_length=100, db_index=True, allow_unicode=False, **kwargs):
super().__init__(*args, max_length... | StarcoderdataPython |
4823562 | <reponame>Zillow-Project-JG-DN/clustering-project-jgdn
# Basic libraries
from env import host, user, password # Database credentials
import wrangle
import pandas as pd
import numpy as np
import numpy as np
# Vizualization Tools
import matplotlib.pyplot as plt
import seaborn as sns
# Modeling Tools
from sklearn.mode... | StarcoderdataPython |
3322479 | """flagstat subcommand tests"""
# (c) 2015-2021 <NAME> <<EMAIL>>
import json
import pytest
from click.testing import CliRunner
from crimson.cli import main
from .utils import get_test_path
@pytest.fixture(scope="module")
def flagstat_fail():
runner = CliRunner()
in_file = get_test_path("samtools_flagstat_n... | StarcoderdataPython |
157811 | <reponame>Sembian/ADL_LRS
__version__ = "0.2.6.1"
| StarcoderdataPython |
186804 |
import pytest
from nr.util.keyvalue.sqlite import SqliteDatastore
def test_sqlite_datastore():
ds = SqliteDatastore(':memory:')
kv = ds.get_namespace('foobar')
assert list(ds.get_namespaces()) == ['foobar']
with pytest.raises(KeyError) as excinfo:
kv.get('spam')
assert str(excinfo.value) == repr("fo... | StarcoderdataPython |
1762248 | r"""
Transfer learning deal Module.
Consist of the utils for transfer learning.
How to use the module to transfer weights as follows first, second, last.
"""
import torch
from collections import OrderedDict
from src.visual.utils.log import LOGGER
from src.visual.utils.general import delete_list_indices
def get_nam... | StarcoderdataPython |
4808150 | <gh_stars>0
import disco
import pathlib
DISCO_EMAIL = '<EMAIL>'
DISCO_PASSWORD = 'password'
disco.set_credentials(DISCO_EMAIL, DISCO_PASSWORD, save_to_config=True)
script_id = disco.upload_file('server.py', pathlib.Path('server.py'))
job = disco.Job.create(script_id, upload_requirements_file=False)
job.start()
(tas... | StarcoderdataPython |
1680201 | import os
import sys
# Import the Flask Framework
from flask import Flask, request, render_template
isDev = os.environ["SERVER_SOFTWARE"].find('Development') == 0
app = Flask( __name__ )
# Note: We don't need to call run() since our application is embedded within
# the App Engine WSGI application server.
@app.route... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.