id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
137926 | <filename>Sioux Falls odme/Sioux_Falls_multi_OD_pairs/ODME-seed_6000/path4gmns/path.py
""" Find shortest path given a from node and a to node
Two path engines are provided:
1. C++ engine which is a special implementation of the deque implementation in
C++ and built into path_engine.dll.
2. Python engine which provi... | StarcoderdataPython |
4828943 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.proto import hsm_pb2
'''
Hierarchical softmax utility methods that can be used to:
1) create TreeProto structure given list of word_ids or NodeProtos... | StarcoderdataPython |
3346858 | # -*- coding: utf-8 -*-
"""This file contains a plugin for cron syslog entries."""
import pyparsing
from plaso.containers import time_events
from plaso.lib import definitions
from plaso.parsers import syslog
from plaso.parsers.syslog_plugins import interface
class CronTaskRunEventData(syslog.SyslogLineEventData):
... | StarcoderdataPython |
1761413 | #coding:utf-8
'''
Created on 2013-7-4
@author: Hayden
'''
from django import template
register = template.Library()
@register.inclusion_tag('ueditorjs.html', takes_context=True)
def ueditor(context,editor_id):
return {"editor_id":editor_id}
| StarcoderdataPython |
1640021 | <reponame>addison-schwamb/WorkingMemoryModelingAdapted<filename>train_posthoc_clst.py
"""
main file to train/test RNN and perform posthoc tests on WashU cluster
written in Python 3.8.3
@ Elham
"""
#input string format: "{\"g\":<val>,\"pg\":<val>,\"fb_var\":<val>,\"input_var\":<val>,\"n_train\":<val>,\"encoding\":<val... | StarcoderdataPython |
3304029 | import json
import mockito
import pytest
from carrot_cli.rest import pipelines, request_handler
@pytest.fixture(autouse=True)
def unstub():
yield
mockito.unstub()
@pytest.fixture(
params=[
{
"id": "cd987859-06fe-4b1a-9e96-47d4f36bf819",
"return": json.dumps(
... | StarcoderdataPython |
3209603 | <filename>paralleldomain/decoding/nuimages/common.py
from collections import defaultdict
from threading import RLock
from typing import Any, Callable, Dict, Generator, Hashable, List, Optional, Tuple, TypeVar
import numpy as np
from pyquaternion import Quaternion
from paralleldomain.decoding.common import create_cach... | StarcoderdataPython |
190504 | <gh_stars>0
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/02_losses.ipynb (unless otherwise specified).
__all__ = [
"LabelSmoothingCrossEntropy",
"log_t",
"exp_t",
"compute_normalization_fixed_point",
"compute_normalization",
"tempered_softmax",
"bi_tempered_logistic_loss",
"BiTempere... | StarcoderdataPython |
1785940 | <reponame>jspaaks/vak
import vak.config
def test_config_attrs_class(
all_generated_configs_toml_path_pairs,
default_model,
):
"""test that instantiating Config class works as expected"""
for config_toml, toml_path in all_generated_configs_toml_path_pairs:
if default_model not in str(toml_path)... | StarcoderdataPython |
125168 | <gh_stars>1-10
""" Module containing classes to generate common filters.
NOTE THAT ALL FILTERS ASSUME HIGH INPUT IMPEDANCE!!
"""
from math import pi
from graph import Node, Edge, Graph
from resistor import Resistor
from capacitor import Capacitor
from opamp import Opamp
from filter import Filter
class LowPassFilte... | StarcoderdataPython |
3342027 | import os
from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile
import factory
from intake import models
from user_accounts.models import Organization
SAMPLE_FORM_PATH = os.path.join(
settings.REPO_DIR, 'tests/sample_pdfs/sample_form.pdf')
def get_sf_pubdef(*args, **kwar... | StarcoderdataPython |
2491 | from openpype.modules.ftrack.lib import BaseEvent
from openpype.modules.ftrack.lib.avalon_sync import CUST_ATTR_ID_KEY
from openpype.modules.ftrack.event_handlers_server.event_sync_to_avalon import (
SyncToAvalonEvent
)
class DelAvalonIdFromNew(BaseEvent):
'''
This event removes AvalonId from custom attri... | StarcoderdataPython |
89521 | import logging
import os
import signal
import subprocess
import tempfile
from typing import List, Sequence, Optional, Tuple, Union
import numpy as np
import pandas as pd
import prctl
import soundfile as sf
from d3m import container, utils
from d3m.base import utils as base_utils
from d3m.metadata import base as metada... | StarcoderdataPython |
1773521 | <gh_stars>1-10
#!/usr/bin/env python
"""
This script remove all pyc files and all __pycache__ directory.
"""
from __future__ import print_function, division, unicode_literals
import sys
import os
import shutil
def rm_pycaches(top):
count = 0
for dirpath, dirnames, filenames in os.walk(top):
for d in... | StarcoderdataPython |
1649647 | <gh_stars>0
from __future__ import absolute_import, division, print_function, unicode_literals
from amaasutils.logging_utils import DEFAULT_LOGGING
from amaasutils.random_utils import random_string
import random
import unittest
from amaascore.asset_managers.asset_manager import AssetManager
from amaascore.asset_manag... | StarcoderdataPython |
1770263 | from __future__ import absolute_import
from ..version_info import PY3
if PY3:
from urllib.parse import *
else:
from urllib import quote, unquote, quote_plus, unquote_plus, urlencode
| StarcoderdataPython |
1716429 | #!/usr/bin/env python3
import numpy as np
from Core import RISM_Obj
from dataclasses import dataclass, field
import Util
from scipy.special import spherical_jn
@dataclass
class DRISM(object):
data_vv: RISM_Obj
diel: float
adbcor: float
data_uv: RISM_Obj = None
chi: np.ndarray = field(init=False)
... | StarcoderdataPython |
1769509 | # -*- coding: utf-8 -
#
# This file is part of tproxy released under the MIT license.
# See the NOTICE for more information.
import sys
# backports socketio
import io
import inspect
import socket
try:
import errno
except ImportError:
errno = None
EBADF = getattr(errno, 'EBADF', 9)
EINTR = getattr(errno, 'EI... | StarcoderdataPython |
1684454 | """Module dendicated for list conversions to data structures, needed for DataFrame construction"""
from typing import Any, Dict, List, Tuple
from markdown_frames.type_definitions import apply_converter, get_type
class InvalidDataException(Exception):
"""Exception thrown when Invalid table input is provided."""
... | StarcoderdataPython |
162453 | from ..error_types import ValidationError
from .selections import cursor, DOCUMENT_BEGIN, select_comments, select_element, select_key, selection
from ..constants import (
BEGIN,
END,
DOCUMENT,
FIELD,
FIELDSET_ENTRY,
FIELD_OR_FIELDSET_OR_LIST,
LIST_ITEM,
MULTILINE_FIELD_BEGIN
)
class Va... | StarcoderdataPython |
61131 | <gh_stars>1-10
from typing import Optional
from db.scaffold import Scaffold
from telegram import models as tg_models
class GetTelegramChannelById(Scaffold):
def get_telegram_channel_by_id(
self,
channel_id: int,
) -> Optional['tg_models.TelegramChannel']:
if channel_id is Non... | StarcoderdataPython |
120130 | <filename>game/consumers.py
import re
import logging
from channels import Group
from channels.sessions import channel_session
from .models import Game, GameSquare
from channels.auth import http_session_user, channel_session_user, channel_session_user_from_http
log = logging.getLogger(__name__)
from django.utils.decorat... | StarcoderdataPython |
178665 | <filename>pip_services3_components/log/CachedLogger.py
# -*- coding: utf-8 -*-
"""
pip_services3_components.log.CachedLogger
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Cached logger implementation
:copyright: Conceptual Vision Consulting LLC 2018-2019, see AUTHORS for more details.
:license: MI... | StarcoderdataPython |
68959 | <reponame>php568/FlapPyBird-master
# -*- coding: utf-8 -*-
a = ['doge1','doge2','doge3','doge4']
print(a)
| StarcoderdataPython |
3370819 | """
Functions and classes for manipulating and reading the state of a SCAII environment.
"""
class State():
"""
The current state of the environment. This can be used directly, but it is likely
much easier to use the State wrapper provided by your environment, which extends
this class.
"""
de... | StarcoderdataPython |
116662 | # -*- coding: utf-8 -*-
import dateparser
import scrapy.loader
from rannts_crawler import items
from . import base
class MeetupsSpider(base.Spider):
name = "meetups"
start_urls = [
"https://rannts.ru/meetups"
]
def parse(self, response):
for result in self.follow_urls(
... | StarcoderdataPython |
1767292 | <filename>board.py
import pygame, time
from pygame.locals import *
from random import shuffle
from constants import *
from player import *
class Tile(pygame.Rect):
def __init__(self, x, y, size, is_safe):
pygame.Rect.__init__(self, x, y, size, size)
if is_safe:
self.color = SAFE_TILE
... | StarcoderdataPython |
3322627 | #!/usr/bin/env python3
import boto3
from botocore.exceptions import ClientError
# from botocore.errorfactory import BadRequestException
import os
import logging
# logger = logging.getLogger()
services = {
"access-analyzer.amazonaws.com": "IAM Access Analyzer",
# "guardduty.amazonaws.com": "AWS GuardDuty", # ... | StarcoderdataPython |
4826716 | # -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# ConfDB media streams <name> audio syntax
# ----------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# -------------------------------------... | StarcoderdataPython |
1587 | import pytest
from jina.enums import RemoteAccessType
from jina.flow import Flow
from jina.parser import set_pea_parser, set_pod_parser
from jina.peapods.pods import BasePod
from jina.peapods.runtimes.remote.ssh import SSHRuntime
from jina.proto import jina_pb2
@pytest.mark.skip('works locally, but until I findout h... | StarcoderdataPython |
1730253 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
###################################################
#........../\./\...___......|\.|..../...\.........#
#........./..|..\/\.|.|_|._.|.\|....|.c.|.........#
#......../....../--\|.|.|.|i|..|....\.../.........#
# Mathtin (c) #
#############... | StarcoderdataPython |
4831310 | from armstrong.dev.tasks import *
from fabric.api import local, task
settings = {
'DEBUG': True,
'INSTALLED_APPS': (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'armstrong.hatband',
'armstrong.hatband.t... | StarcoderdataPython |
95116 | <gh_stars>1-10
import math, os
# Kernel parameters
hs = 25 # spatial bandwidth in meters
ht = 15 # temporal bandwidth in days
hs2 = pow(int(hs), 2) #videogame-trick
# regular grid resolution
xRes = 10 # x resolution
yRes = 10 # y resolution
tRes = 10 # t resolution
# Read ... | StarcoderdataPython |
51227 | import numpy as np
import unittest
import pytest
from pysph.base.particle_array import ParticleArray
import pysph.tools.mesh_tools as G
from pysph.base.utils import get_particle_array
# Data of a unit length cube
def cube_data():
points = np.array([[0., 0., 0.],
[0., 1., 0.],
... | StarcoderdataPython |
1670142 | # from app import app
import urllib.request, json
from .models import News, NewsSource
from datetime import datetime
today = datetime.today().strftime('%Y-%M-%D')
# News = news.News
# NewsSource = news_source.NewsSource
#Getting api key
apiKey = None
#Getting the news api base url
base_url = None
source_url = Non... | StarcoderdataPython |
74783 | class Pessoa:
olhos = 2
def __init__(self,*filhos, nome = None, idade = 35):
self.idade = idade
self.nome = nome
self.filhos = list(filhos)
def cumprimentar(self):
return 'Olá mundo!'
if __name__ == '__main__':
marcio = Pessoa(nome='Marcio')
max = Pessoa(marcio, no... | StarcoderdataPython |
1672986 | <reponame>mbassale/genetic-algorithms-books<filename>ch4/elitism.py
from deap import tools
from deap import algorithms
def eaSimpleWithElitism(population, toolbox, cxpb, mutpb, ngen, stats=None,
halloffame=None, verbose=__debug__):
"""This algorithm is similar to DEAP eaSimple() algorithm, with the mo... | StarcoderdataPython |
1724922 | <filename>models/aspp_3d.py
import torch
import torch.nn as nn
import torch.nn.functional as F
class _ASPPModule(nn.Module):
def __init__(self, inplanes, planes, kernel_size, padding, dilation):
super(_ASPPModule, self).__init__()
self.atrous_conv = nn.Conv3d(inplanes, planes, kernel_size=kernel_s... | StarcoderdataPython |
3238884 | <reponame>googlearchive/py-gfm<gh_stars>1-10
# Copyright (c) 2013, the Dart 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.
import gfm
from test_case import TestCase
class TestMultili... | StarcoderdataPython |
3210600 | <gh_stars>1-10
import torch
import pandas as pd
from laylm.trainer import metrics
from laylm.config import label as label_cfg
from laylm.config import token as token_cfg
def annoset_inputs(data_dict, device):
input_ids = torch.tensor(data_dict['token_ids'], dtype=torch.long)
mask = torch.tensor(data_dict... | StarcoderdataPython |
1769579 | <reponame>kelvin95/EPOSearch
# lenet base model for Pareto MTL
import torch
import torch.nn as nn
class RegressionTrain(torch.nn.Module):
def __init__(self, model):
super(RegressionTrain, self).__init__()
self.model = model
self.loss = nn.BCELoss(reduction='none')
def forward(self, ... | StarcoderdataPython |
3393143 | import matplotlib.patches as patches
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
def draw_rectangle(ax, x, y, width, height, **kwargs):
rectangle = patches.Rectangle((x, y), width, height, **kwargs)
ax.add_patch(rectangle)
return rectangle
def draw_line(ax, x, y, **kwargs):
l... | StarcoderdataPython |
112499 | from .config import SECRET
from .dispatcher import dp
__all__ = ["dp", "SECRET"]
| StarcoderdataPython |
1754264 | import argparse
import logging
import pygame
import random
import config
import board
import player
class Text(object):
def __init__(self, text, position, **kwargs):
font_name = kwargs.get('font', 'freesansbold.ttf')
font_size = kwargs.get('size', 32)
self.font = pygame.font.Font(font_nam... | StarcoderdataPython |
4827809 | <reponame>Jorge-DevOps/API_HealthTech
from django.http import response
from django.shortcuts import render
from django.shortcuts import render
# Create your views here.
from rest_framework import generics, permissions
from rest_framework.response import Response
from knox.models import AuthToken
from .serializers impo... | StarcoderdataPython |
3398448 | <reponame>Nyapy/FMTG
import sys
sys.stdin = open('3020.txt')
N,H = map(int, input().split())
up = []
down = []
cnt = [0 for _ in range(H)]
for _ in range(N//2):
down.append(int(sys.stdin.readline()))
up.append(int(sys.stdin.readline()))
up.sort()
down.sort()
for i in range(H):
l = 0
r = N // 2
... | StarcoderdataPython |
3248794 | from django.apps import AppConfig
class KwikpostsConfig(AppConfig):
name = 'kwikposts'
verbose_name = 'Posts, Comments, Likes'
| StarcoderdataPython |
91716 | <reponame>daniilpeshkov/OPI_labs
import requests
import time
def get_usd_exchange():
data = requests.get('https://www.cbr-xml-daily.ru/daily_json.js').json()
return float(data['Valute']['USD']['Value'])
def main():
print('Курс доллара:', get_usd_exchange() )
if __name__ == '__main__':
main()
| StarcoderdataPython |
115370 | <gh_stars>10-100
import pytest
import torch
from timm.scheduler import CosineLRScheduler
from src.optim.timm_lr_scheduler import TimmCosineLRScheduler
def test_lr():
n_epochs = 310
model = torch.nn.Linear(3, 3)
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.03)
kwargs = ... | StarcoderdataPython |
8087 | <filename>src/collectors/rabbitmq/rabbitmq.py
# coding=utf-8
"""
Collects data from RabbitMQ through the admin interface
#### Notes
* if two vhosts have the queues with the same name, the metrics will collide
#### Dependencies
* pyrabbit
"""
import diamond.collector
try:
from numbers import Number
Numb... | StarcoderdataPython |
3263299 | import numpy as np
class CrossValidationMetricsResultPrinter:
""" Prints mean values of metrics obtained by a cross validation process.
"""
def print_metrics_report(self, metrics):
""" Print metric names and its mean values obatined by a cross_validation procedure.
:param metrics: dicti... | StarcoderdataPython |
17840 | <reponame>rdbende/Sun-Valley-messageboxes<gh_stars>1-10
import tkinter as tk
from tkinter import ttk
from functools import partial
def popup(parent, title, details, icon, *, buttons):
dialog = tk.Toplevel()
result = None
big_frame = ttk.Frame(dialog)
big_frame.pack(fill="both", expand=True)
big_... | StarcoderdataPython |
11278 | <reponame>Mannan2812/azure-cli-extensions
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# -------------------------------------------... | StarcoderdataPython |
3326443 | <reponame>imapex/suggestions
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-08-21 13:44
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('reddit', '0002_submission_foo'),
]
operations = [
migra... | StarcoderdataPython |
4818801 | from rlcard.utils import *
from rlcard.games.whist.utils import cards2list
import os
class Env(object):
'''
The base Env class. For all the environments in RLCard,
we should base on this class and implement as many functions
as we can.
'''
def __init__(self, config):
''' Initialize th... | StarcoderdataPython |
4823722 | """Sherlock Notify Module
This module defines the objects for notifying the caller about the
results of queries.
"""
from result import QueryStatus
from colorama import Fore, Style, init
class QueryNotify():
def __init__(self, result=None):
self.result = result
return
def star... | StarcoderdataPython |
85258 | # based on <NAME>'s talk “Lexical scanning in Go”
# http://youtu.be/HxaD_trXwRE
# http://golang.org/src/pkg/text/template/parse/lex.go
LEFT_DELIM = '{{'
RIGHT_DELIM = '}}'
PIPE = '|'
LEFT_LINK_DELIM = '[['
RIGHT_LINK_DELIM = ']]'
LEFT_COMMENT_DELIM = '<!--'
RIGHT_COMMENT_DELIM = '-->'
class Lexer:
def __init__(self)... | StarcoderdataPython |
1794678 | import os
import aiohttp
from asyncinit import asyncinit
from wow.fight import Fight
API_URL = "https://www.warcraftlogs.com:443/v1/report/"
@asyncinit
class WarcraftlogsAPI():
async def __init__(self, code: str):
self.code = code
self.log_info = await self.get_log_info()
async def get_log... | StarcoderdataPython |
3213866 | from datasets import fashion200k
from datasets import fashion_iq
from datasets import shoes
from datasets import vocabulary
import numpy as np
import tensorflow as tf
# python read_glove.py --dataset='fashion_iq' --data_path='datasets/fashion_iq/image_data'
# python read_glove.py --dataset='shoes' --data_path=''
# py... | StarcoderdataPython |
31187 | import string
import spacy
from text_studio.utils.timer import timer
from text_studio.transformer import Transformer
class SpacyTokenizer(Transformer):
def setup(self, stopwords=None, punct=None, lower=True, strip=True):
spacy.cli.download("en_core_web_sm")
self.nlp = spacy.load(
"en_... | StarcoderdataPython |
3339359 | <gh_stars>0
from datetime import tzinfo
import sys
from decimal import Decimal
from enum import Enum
import uuid
from dateutil import parser
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models import QuerySet, Model
from django.db.models.fields.files import FieldFile
from django.utils.funct... | StarcoderdataPython |
3327303 | """
Unit and regression test for the mapsci package.
"""
# Import package, test suite, and other packages as needed
import mapsci
import pytest
import sys
import os
import logging
import random
logger = logging.getLogger(__name__)
temperature = 273 # [K]
bead_library = {
"CO2": {'epsilon': 353.55, 'sigma': 3.741... | StarcoderdataPython |
24156 | <gh_stars>0
import os
from pyfakefs import fake_filesystem_unittest
from devbox.utilities.manifest_parser import ManifestParser
class TestManifestParser(fake_filesystem_unittest.TestCase):
def setUp(self):
self.setUpPyfakefs()
def test_manifest_parser(self):
# Arrange
self.fs.CreateF... | StarcoderdataPython |
4831531 | <reponame>tianxin1860/FSL-Mate<gh_stars>100-1000
import paddle
from paddlefsl.backbones import ConvBlock, Conv, RCConv1D
def conv_block_test():
train_input = paddle.ones(shape=(1, 1, 28, 28), dtype='float32')
conv = paddle.nn.Sequential(
ConvBlock(in_channels=1, out_channels=32, pooling_size=(2, 2)),
... | StarcoderdataPython |
4805638 | #!/usr/bin/env python3
"""
SpiderBob is a crawler that uses Scrapy to scrape
SpongeBob dialogue from transcripts that are hosted
on the SpongeBob wiki.
"""
import scrapy
class SpiderBob(scrapy.Spider):
"""
SpiderBob class, scrapes SpongeBob dialogue
"""
name = "SpiderBob"
allowed_domains = ["spon... | StarcoderdataPython |
3205853 | from gazette.spiders.base import FecamGazetteSpider
class ScRomelandiaSpider(FecamGazetteSpider):
name = "sc_romelandia"
FECAM_QUERY = "cod_entidade:226"
TERRITORY_ID = "4215208"
| StarcoderdataPython |
1782886 | <filename>python/test_result.py
# Containing whole result of prediction
class TestResultClass(object):
# Class Name (ex: xxxx)
name = None
# Class Label (ex: 4)
label = None
# Class Score
score = 0
# Class Box coodinate ([xmin, ymin, xmax, ymax])
box = None
class TestResultImage(obj... | StarcoderdataPython |
17747 | <reponame>asmeurer/advent-of-code<filename>2020/day11.py
test_input = """
L.LL.LL.LL
LLLLLLL.LL
L.L.L..L..
LLLL.LL.LL
L.LL.LL.LL
L.LLLLL.LL
..L.L.....
LLLLLLLLLL
L.LLLLLL.L
L.LLLLL.LL
"""
test_input2 = """
.......#.
...#.....
.#.......
.........
..#L....#
....#....
.........
#........
...#.....
"""
test_input3 = """
... | StarcoderdataPython |
122229 | import sqlite3
from collections import deque
conn = sqlite3.connect('clean.sqlite') # cleaned db for connection and true country analysis
cur = conn.cursor()
person_cur = conn.cursor()
def person_is_resident(pers_id, country_id):
person_cur.execute('''SELECT tc FROM True_countries WHERE id = ?''', (pers_id,))
... | StarcoderdataPython |
1768523 | # pylint: skip-file
# type: ignore
from asyncio import coroutine
from . import exceptions
from . import templatenodes as nodes
from . import environment
from . import interpolatedstr
from . import expression
from .platform import bs4
from .utils import delayedupdater
class RenderFactory:
AVAILABLE = {}
@cla... | StarcoderdataPython |
1743356 | import tensorflow as tf
import numpy as np
import sys
import json
import sys
sys.path.append('../')
from lm.modeling import GroverModel, GroverConfig, _top_p_sample, sample
from sample.encoder import get_encoder, format_context, _tokenize_article_pieces, extract_generated_target
from tqdm import tqdm
import argparse
... | StarcoderdataPython |
1787230 | from .db import db, ma
from .default_method_result import DefaultMethodResult
class ContactType(db.Model):
__tablename__ = 'ContactTypes'
# Defining the columns
contacttypeid = db.Column(db.Integer, primary_key=True,autoincrement=True)
name = db.Column(db.String(100), unique=False, nullable=False)
... | StarcoderdataPython |
157313 | #!/usr/bin/env python
# $Id$
#------------------------------------------------------------------------
# NAME: events_chooser.py -
# HISTORY: -
# 2017-07-21 <EMAIL> -
# Fixing _OnCharHook for Linux.
# 2017-03-31 <EMAIL> -
# Added EVT_CHAR_HOOK.
# 2016-08-15 <EMAIL> -
# New State and event na... | StarcoderdataPython |
3278839 | import sys
from copy import deepcopy
from itertools import chain, product
def parse_seats(instream):
return [list(iter(l.strip())) for l in instream if l.strip()]
def find_adjacent(r, c, seats):
candidates = [(r + rd, c + cd) for (rd, cd) in product([-1, 0, 1], [-1, 0, 1]) if (rd, cd) != (0, 0)]
return... | StarcoderdataPython |
4843303 | #!/usr/bin/env python
# Copyright 2020 <NAME>
# License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import math
from itertools import permutations
from typing import List, Tuple
import edit_distance as ed
def wer(hyp: List[str], ref: List[str]) -> Tuple[float]:
"""
Compute edit distance betwee... | StarcoderdataPython |
1737461 | import asyncio
import logging
from santaka.stock.utils import update_stocks, update_currency, YAHOO_UPDATE_COOLDOWN
logger = logging.getLogger(__name__)
async def run_periodic_task(name, update_func, cooldown):
while True:
try:
await update_func()
except Exception as e:
l... | StarcoderdataPython |
81603 | <reponame>PTST/UiPath_Orchestrator
import unittest
import os,sys,inspect
current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parent_dir = os.path.dirname(current_dir)
sys.path.insert(0, parent_dir)
from Orchestrator import Orchestrator
import os
import time
from datetime imp... | StarcoderdataPython |
3217849 | # Copyright (C) 2019 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""A mixin for objects that can be cloned"""
import itertools
import datetime
from collections import defaultdict
import sqlalchemy as sa
from werkzeug import exceptions
from ggrc import db
from ggrc.m... | StarcoderdataPython |
23651 | <reponame>BartWojtowicz/cne
from .cne import CNE
__version__ = "0.0.dev"
| StarcoderdataPython |
1722915 | from tronx import app
from pytube import YouTube
from pyrogram.types import Message
from tronx.helpers import (
gen,
)
app.CMD_HELP.update(
{"utube": (
"utube",
{
"yvinfo [link]" : "Get a youtube video information . . .",
"yvdl [link]" : "Download any video from YouTube . . ."
}
)
}
)
@app.on_m... | StarcoderdataPython |
157633 | from django.contrib import admin
from .models import ProjectSubmission, LeaderboardSettings
import logging
logger = logging.getLogger(__name__)
def recompute_mean_average_precision(modeladmin, request, queryset):
if not ProjectSubmission.objects.filter(is_solution=True).exists():
return
for submissi... | StarcoderdataPython |
3250265 | <filename>model2lstm.py
import numpy as np
import pdb
import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn.utils.rnn import pad_sequence
from torch.autograd import Variable
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
class Decoder_attention(nn.M... | StarcoderdataPython |
3347538 | <reponame>kaaass/BGmi<gh_stars>100-1000
import datetime
import os
from collections import defaultdict
from icalendar import Calendar, Event
from bgmi.config import SAVE_PATH
from bgmi.front.base import BaseHandler
from bgmi.lib.constants import BANGUMI_UPDATE_TIME
from bgmi.lib.models import Download, Followed
clas... | StarcoderdataPython |
163946 | <reponame>yatwql/HanLP<gh_stars>1-10
# -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2022-01-25 19:09
import hanlp
amr_parser = hanlp.load(hanlp.pretrained.amr.AMR3_SEQ2SEQ_BART_LARGE)
amr = amr_parser('The boy wants the girl to believe him.')
print(amr)
| StarcoderdataPython |
3310744 | <reponame>yoniv/home-assignment
# Generated by Django 3.1.3 on 2020-11-06 17:23
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Users'... | StarcoderdataPython |
155567 | # -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
z1 = []
z2 = []
for i in range(m.num_stages):
for j in range(101):
z1.append(m.policy[i,j][0])
z2.append(m.policy[i,j][1])
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x ... | StarcoderdataPython |
5696 | # --------------
#Importing header files
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
#Code starts here
data = pd.read_csv(path)
data['Rating'].hist()
data = data[data['Rating']<=5]
data['Rating'].hist()
#Code ends here
# --------------
# code starts here
total_null = data.isnull().sum... | StarcoderdataPython |
1751952 | <reponame>iacopoerpichini/EasyCaptureFLIR<gh_stars>10-100
from typing import Union, Tuple, List
import numpy as np
import cv2
import PySpin
from .videocapture import VideoCapture
from .utils import warn
class VideoCaptureEX(VideoCapture):
"""Open a FLIR camera for video capturing.
VideoCaptureEX class is s... | StarcoderdataPython |
158178 | <reponame>cppseminar/APC<filename>functions/stop-vm/__init__.py
import contextlib
import datetime
import json
import logging
from ..shared import testers
import azure.functions as func
def main(mytimer: func.TimerRequest) -> None:
tester = testers.get_tester_config(name="default")
stop_after = tester.stop_a... | StarcoderdataPython |
1745077 | <reponame>davidleitw/RaspberryPiYoloV4<gh_stars>0
import os
from dotenv import load_dotenv
class envReader(object):
def __init__(self):
load_dotenv()
def getenv(self, key:str)->str:
return os.getenv(key)
class Config(object):
def __init__(self):
self.reader = envReader()
... | StarcoderdataPython |
1647554 | <filename>payment/migrations/0013_auto_20210603_1045.py
# Generated by Django 3.2 on 2021-06-03 08:45
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('payment', '0012_alter_paymenttransaction_payment_type'),
]
opera... | StarcoderdataPython |
106686 | from .configuration import ModelName, Configuration, getConfiguration
from .dataset import StrikeThroughType, StruckDataset
from .utils import PadToSize, composeTransformations, getModelByName
__all__ = ["ModelName", "Configuration", "getConfiguration", "StrikeThroughType", "StruckDataset", "PadToSize",
"co... | StarcoderdataPython |
4829077 | <filename>Chapter9_Packages/2_HTML_Doc/setup.py
# Option 1: python setup.py develop
# Option 2: python setup.py bdist_wheel & pip install ./fastvector-0.1.0-py3-none-any.whl
from setuptools import setup
def get_readme():
with open('README.md') as f:
return f.read()
def get_license():
with open('LICE... | StarcoderdataPython |
4808632 | <reponame>davidweichiang/flatcat
from __future__ import unicode_literals
import collections
import datetime
import logging
import re
import sys
import bz2
import codecs
import gzip
import locale
import os
import tarfile
from contextlib import contextmanager
from . import get_version
from .categorizationscheme import... | StarcoderdataPython |
1659199 | <reponame>CodeProcessor/sports-events-detection
#!/usr/bin/env python3
"""
@Filename: combine_datasets.py
@Author: dulanj
@Time: 15/01/2022 10:18
"""
import os
import shutil
scrum_dataset = "/home/dulanj/MSc/sports-events-detection/training_pipeline/data/Rugby-Scrum-V2.v2i.yolov5pytorch"
lineout_dataset... | StarcoderdataPython |
1709517 | <reponame>kgbhat/nsx-t<filename>python/basics/rate-limits.py<gh_stars>10-100
#!/usr/bin/env python
"""
NSX-T SDK Sample Code
Copyright 2019 VMware, Inc. All rights reserved
The BSD-2 license (the "License") set forth below applies to all
parts of the NSX-T SDK Sample Code project. You may not use this
file except ... | StarcoderdataPython |
41937 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.23 on 2020-01-20 05:23
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("jobs", "0013_add_job_id_field_in_submission_model")]
operations = [
migrations.RenameField(
... | StarcoderdataPython |
1695731 | from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from watch.models import *
# Create your views here.
@login_required(login_url='/accounts/login/')
def index(request):
'''
user profile
'''
current_user = request.user
user = user_profile.objec... | StarcoderdataPython |
3245695 | import os
import unittest
from pymosa_mimosa26_interpreter import data_interpreter
from pymosa_mimosa26_interpreter.testing.tools.test_tools import compare_h5_files
class TestRawChunkSize(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.temp_output_files = []
@classmethod
def tearD... | StarcoderdataPython |
58348 | import importlib
import ipaddress
classes_cache = {}
instance_cache = {}
def get_class(type:str):
cls = classes_cache.get(type)
if cls:
return cls
raise TypeError(f'wrong type {type}. not subclass of BaseType')
def get_instance(type:str,**option):
key = ','.join('{}={}'.format(k,v) for k, v ... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.