id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
1654794 | import pickle
import os
class Knowledge:
"""
先验知识的保存
"""
FILENAME_KNOW = "chatbot.know"
FILENAME_DIALOG = "chatbot.dialog"
def __init__(self, path="./data/", load=True):
self.path = path
self.known = {}
self.dialog = {}
if load:
self.load()
de... | StarcoderdataPython |
3377372 | <filename>run.py
#!/usr/bin/env python
import sys
from jira_migrate.issues import main
if __name__ == "__main__":
sys.exit(main(sys.argv))
| StarcoderdataPython |
1719742 | import cloudmesh
cloudmesh.shell("help")
print cloudmesh.version()
| StarcoderdataPython |
14979 | """Module for BlameInteractionGraph plots."""
import typing as tp
from datetime import datetime
from pathlib import Path
import click
import matplotlib.pyplot as plt
import networkx as nx
import pandas as pd
import plotly.offline as offply
from matplotlib import style
from varats.data.reports.blame_interaction_graph... | StarcoderdataPython |
4809718 | <gh_stars>10-100
# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
from Tea.model import TeaModel
from typing import Dict, List
class ECertQueryHeaders(TeaModel):
def __init__(
self,
common_headers: Dict[str, str] = None,
x_acs_dingtalk_access_token: str = None,... | StarcoderdataPython |
4811349 | import morepath
from .app import App
def run():
morepath.autoscan()
morepath.run(App())
if __name__ == '__main__':
run()
| StarcoderdataPython |
3259088 | # coding: utf-8
"""
EXACT - API
API to interact with the EXACT Server # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
from exact_sync.v1.api.pagination_base_api import PaginationBaseAPI
import ... | StarcoderdataPython |
1614297 | import re
import sys
import shutil
if not sys.version_info >= (3, 3):
print('ERROR: You must be running Python >= 3.3')
sys.exit(1) # cancel project
MODULE_REGEX = r'^[_a-zA-Z][_a-zA-Z0-9]+$'
module_name = '{{ cookiecutter.project_slug}}'
if not re.match(MODULE_REGEX, module_name):
print('ERROR: The pr... | StarcoderdataPython |
3276433 | class PubSub:
def __init__(self, logger, linked_list, bus_factory, async_service, context_service, *args, **kwargs):
super().__init__(*args, **kwargs)
self._logger = logger
self._logger.debug(
f"PubSub: context_service = {context_service}")
self.__daisy_chain_bus = linke... | StarcoderdataPython |
3384382 |
"""Implements basic throttle, brake, steering functionality"""
import rospy
from yaw_controller import YawController
from lowpass import LowPassFilter
from pid import PID
GAS_DENSITY = 2.858
ONE_MPH = 0.44704
#pylint: disable=C0326,trailing-whitespace
class Controller(object):
"""
Use a Yaw controller and ... | StarcoderdataPython |
1739202 | for _ in range(int(input())):
n=int(input())
l=list(map(int,input().split()))
pre=[0]
for i in range(n):
pre.append(l[i]+pre[-1])
d={}
for i in l:
if i in d:
d[i]+=1
else:
d[i]=1
c=0
for i in range(n):
for j in range(i+1,n):
... | StarcoderdataPython |
3372641 | <reponame>alterway/anonymization<filename>anonymization/anonymizers/dateAnonymizers.py
import re
from types import SimpleNamespace
from ..Anonymization import Anonymization
class DateAnonymizer():
'''
Replace the dates with fake ones
Date Formats: DD/MMM/YYYY or DD.MMM.YYYY or DD-MMM-YYYY or DD MMM ... | StarcoderdataPython |
93723 | <gh_stars>100-1000
# This script removes the input reference numbers from html pages.
# They play a useful role in scientific notebooks, but they are really
# just visual clutter in this project.
# Could be an nbconvert setting, but it's an easy enough scripting job.
import os
import sys
print("\nStripping input re... | StarcoderdataPython |
1743735 | import pp
from pp import Port
from pp.routing.connect_bundle import connect_bundle
def test_connect_bundle():
xs_top = [-100, -90, -80, 0, 10, 20, 40, 50, 80, 90, 100, 105, 110, 115]
pitch = 127.0
N = len(xs_top)
xs_bottom = [(i - N / 2) * pitch for i in range(N)]
top_ports = [Port("top_{}".for... | StarcoderdataPython |
3212118 | <reponame>mohammadasim/online-bookstore
import uuid
from django.contrib.auth import get_user_model
from django.db import models
from django.urls import reverse
class CustomerPayment(models.Model):
"""
A django model representing a payment made by a customer
"""
payment_id = models.UUIDField(
... | StarcoderdataPython |
3277042 | """ Extra questions for Lab 08 """
from lab08 import *
# OOP
class Keyboard:
"""A Keyboard takes in an arbitrary amount of buttons, and has a
dictionary of positions as keys, and values as Buttons.
>>> b1 = Button(0, "H")
>>> b2 = Button(1, "I")
>>> k = Keyboard(b1, b2)
>>> k.buttons[0].key
... | StarcoderdataPython |
1628910 | <filename>accounts/migrations/0004_userprofile_wish_list.py<gh_stars>0
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-08-28 12:27
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('product', '0012_auto_20... | StarcoderdataPython |
3270603 | <reponame>kapikantzari/MultiBench<filename>examples/healthcare/mimic_low_rank_tensor.py
import torch
from torch import nn
import sys
import os
sys.path.append(os.getcwd())
from unimodals.common_models import MLP, GRU # noqa
from datasets.mimic.get_data import get_dataloader # noqa
from fusions.common_fusions import L... | StarcoderdataPython |
1777350 | #!/usr/bin/env python
"""
@package mi.dataset.parser.test
@file mi-dataset/mi/dataset/parser/test/test_winch_cspp.py
@author <NAME>
@brief Test code for Winch Cspp data parser
Files used for testing:
20141114-194242-WINCH.LOG
Contains engineering data for CSPP platform
"""
import os
from nose.plugins.attrib impor... | StarcoderdataPython |
1668502 | import math
import cv2
import numpy as np
from dtld_parsing.calibration import CalibrationData
from typing import Tuple
__author__ = "<NAME>, <NAME> and <NAME>"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
class ThreeDPosition(object):
"""
Three dimensional position with respect to a defined frame_id.
... | StarcoderdataPython |
2036 | #!/usr/bin/env python3 -u
# -*- coding: utf-8 -*-
__author__ = ["<NAME>"]
__all__ = ["_StatsModelsAdapter"]
import numpy as np
import pandas as pd
from sktime.forecasting.base._base import DEFAULT_ALPHA
from sktime.forecasting.base._sktime import _OptionalForecastingHorizonMixin
from sktime.forecasting.base._sktime ... | StarcoderdataPython |
4808568 | from itertools import cycle
def xor_data(data, key):
key = [q for q in key]
data = [q for q in data]
return bytes([c ^ k for c, k in zip(data, cycle(key))]) | StarcoderdataPython |
3270502 | <reponame>SimonContreras/MHRiseWiki-discord-bot
import os
import discord
from discord.ext import commands
from src.skill.embed import SkillEmbed
from src.common.embed import CommonEmbed
from src.common.utils import InputParser
from src.orm.queries.header import db_header
from src.orm.queries.skill import db_skill
clas... | StarcoderdataPython |
4840749 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
#
# This application is an example on how to use aiolifx
#
# Copyright (c) 2016 <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 ... | StarcoderdataPython |
3248356 | <filename>Modules/LSTM_Config.py
######################## config ##############################
import tensorflow as tf
from keras.applications import VGG16
from tensorflow import keras
from keras.models import Model
import numpy as np
from random import shuffle
from Modules import PublicModules as lib
from keras.mode... | StarcoderdataPython |
114028 | import sqlite3
db_con = sqlite3.connect("./manga_db.sqlite", detect_types=sqlite3.PARSE_DECLTYPES)
db_con.row_factory = sqlite3.Row
with db_con:
c = db_con.executescript("""
PRAGMA foreign_keys=off;
BEGIN TRANSACTION;
DROP INDEX IF EXISTS id_onpage_on_site;
... | StarcoderdataPython |
41658 | <reponame>Aleksander-Drozd/pycsvw
term_mappings = {
'Cell': 'csvw:Cell',
'Column': 'csvw:Column',
'Datatype': 'csvw:Datatype',
'Dialect': 'csvw:Dialect',
'Direction': 'csvw:Direction',
'ForeignKey': 'csvw:ForeignKey',
'JSON': 'csvw:JSON',
'NCName': 'xsd:NCName',
'NMTOKEN': 'xsd:NMTOK... | StarcoderdataPython |
4826343 | <gh_stars>0
import pandas as pd
import numpy as np
# Store filepath in a variable
path = "Resources/budget_data.csv"
# Read our Data file with the pandas library
df = pd.read_csv(path, encoding="ISO-8859-1")
# Total num of months
months = df["Date"].nunique()
# net P&L
p_and_l = df["Profit/Losses"].sum()
#get num... | StarcoderdataPython |
3295927 | <reponame>PortableProgrammer/Status-Light
# https://github.com/portableprogrammer/Status-Light/
# Module imports
import sys
import signal
import os
import time
import logging
from datetime import datetime
# Project imports
import webex
import office365
import tuya
import env
import const
currentStatus = const.Status... | StarcoderdataPython |
3261849 | <filename>lib/script/who.py
#
# EXAMPLE: A primitive who command
#
__name__ = "who Command"
__author__ = "jh"
__date__ = "Feb 2004"
__version__ = "1.0"
__text__ = "blah blah blah"
__deps__ = []
from mud import *
import server
def __init__() :
register_command("who", \
{
"position" : POS_DEAD,
"function"... | StarcoderdataPython |
1793532 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Hive Colony Framework
# Copyright (c) 2008-2020 Hive Solutions Lda.
#
# This file is part of Hive Colony Framework.
#
# Hive Colony Framework is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by the Apach... | StarcoderdataPython |
52185 | from RPi import GPIO
from time import sleep
# clk = 17
# dt = 18
sw = 24
clk = 12
dt = 25
GPIO.setmode(GPIO.BCM)
GPIO.setup(clk, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(dt, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(sw, GPIO.IN, pull_up_down=GPIO.PUD_UP)
counter = 0
clkLastState = GPIO.input(clk)
try:... | StarcoderdataPython |
1761704 | """
"""
from __future__ import absolute_import, division, print_function
import numpy as np
import pytest
from astropy.utils.misc import NumpyRNGContext
from ..mean_los_velocity_vs_rp import mean_los_velocity_vs_rp
from ...tests.cf_helpers import generate_locus_of_3d_points
__all__ = ('test_mean_los_velocity_vs_rp_co... | StarcoderdataPython |
4842858 | <reponame>SantaSpeen/gitflic
"""
Gitflic authentication wrapper.
"""
import json
import os
import threading
from urllib.parse import quote_plus
import webbrowser
from enum import Enum
from typing import Union
import logging
import requests
from .exceptions import AuthError, GitflicExceptions
from .__version__ import ... | StarcoderdataPython |
1771784 | #instaspy
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class instaspy:
def __init__(self, username, password, target_username):
self.username = username
self.password = password
self.target_username = target_username
self.brow... | StarcoderdataPython |
4829050 | from django import template
register = template.Library()
@register.inclusion_tag('widgets/std_field.html', takes_context=True)
def std_field(context, field, **kwargs):
field.__dict__.update(kwargs)
return {"field": field}
@register.inclusion_tag('widgets/multi_field.html', takes_context=True)
def radio_fi... | StarcoderdataPython |
1771732 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
"""RAMSES RF - a RAMSES-II protocol decoder & analyser.
Schema processor.
"""
# TODO: move max_zones into system-specific location, ?profile
import logging
import re
from types import SimpleNamespace
from typing import Any
import voluptuous as vol
from .const import... | StarcoderdataPython |
77913 | <gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------------------------
# Connect to MongoDB and return the client -
# ---------------------------------------------------------------------------... | StarcoderdataPython |
1707494 | # Copyright 2021 <NAME> (KRR-Oxford). 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/LICENSE-2.0
# Unless required by applicable la... | StarcoderdataPython |
4815952 | <gh_stars>1-10
# Generated by Django 3.2.6 on 2021-08-22 02:30
from django.db import migrations
import wagtail.core.blocks
import wagtail.core.fields
class Migration(migrations.Migration):
dependencies = [
('committees', '0028_auto_20210809_0310'),
]
operations = [
migrations.AlterField... | StarcoderdataPython |
133220 | <reponame>Sketos/PyAutoArray<filename>test_autoarray/unit/structures/test_arrays.py
import os
import numpy as np
import pytest
import shutil
import autoarray as aa
from autoarray.structures import arrays
from autoarray import exc
test_data_dir = "{}/../test_files/array/".format(
os.path.dirname(os.path.realpath(... | StarcoderdataPython |
1724039 | # Copyright 2019-2021 Swiss National Supercomputing Centre (CSCS/ETH Zurich)
# HPCTools Project Developers. See the top-level LICENSE file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
import os
import sys
import reframe as rfm
import reframe.utility.sanity as sn
sys.path.append(os.path.abspath(os.path.join(o... | StarcoderdataPython |
3363129 | <reponame>Rayckey/motion_imitation<gh_stars>1-10
# coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/lic... | StarcoderdataPython |
74020 | import time
import dweepy
import RPi.GPIO as GPIO
KEY = 'tweet_about_me'
OUTPUT_PIN = 18
OUTPUT_DURATION = 10
GPIO.setmode(GPIO.BCM)
GPIO.setup(OUTPUT_PIN, GPIO.OUT)
while True:
try:
for dweet in dweepy.listen_for_dweets_from(KEY):
print('Tweet: ' + dweet['content']['text'])
GPIO.o... | StarcoderdataPython |
86706 | from setuptools import setup, find_packages
setup(
name='GitSpammer',
version='0.1.0',
packages=find_packages(),
install_requires=[
'Click'
],
entry_points={
'console_scripts': [
'gitspam = gitspammer.entry:cli'
],
},
description="Experiment with Git's... | StarcoderdataPython |
1619394 | <gh_stars>0
class GiteeUser:
def __init__(self):
self.id = None
self.giteeLogin = None
self.userLogin = None
def from_record(self, record):
self.id = record[0]
self.giteeLogin = record[1]
self.userLogin = record[2]
| StarcoderdataPython |
4808377 | <reponame>drevicko/senpy
import random
from senpy.plugins import EmotionPlugin
from senpy.models import EmotionSet, Emotion
class RmoRandPlugin(EmotionPlugin):
def analyse_entry(self, entry, params):
category = "emoml:big6happiness"
number = max(-1, min(1, random.gauss(0, 0.5)))
if number... | StarcoderdataPython |
4830547 | from django.contrib import admin
from aditamento.militaries.models import Military
class MilitaryModelAdmin(admin.ModelAdmin):
list_display = ('name', 'cpf')
search_fields = ('name', 'cpf')
admin.site.register(Military, MilitaryModelAdmin)
| StarcoderdataPython |
1723432 | import urllib.request
import json
#from PIL import Image
from Kaspa.modules.abstract_modules.abstractModule import AbstractModule
from Kaspa.modules.extension_modules.knowledge_module.knowledgeModuleDe import KnowledgeModuleDe
from Kaspa.modules.extension_modules.knowledge_module.knowledgeModuleEn import KnowledgeModul... | StarcoderdataPython |
1765017 | <gh_stars>0
import sys
import numpy as np
import math
fname = sys.argv[1]
quantums = []
with open(fname) as f:
content = f.readlines()
content = [x.strip() for x in content]
count = 0
is_quantum = False
quantum = []
for line in content:
if line.startswith("-----------"):
quantum.append(line)
... | StarcoderdataPython |
1786373 | <gh_stars>0
import json
import torch
import PIL
import argparse
import matplotlib
import numpy as np
import torchvision as tv
import matplotlib.pyplot as plt
from torch import nn
from collections import OrderedDict
from train import setup_nn
def main():
# Parse Arguments
parser = argparse.ArgumentParser()
... | StarcoderdataPython |
1712303 | from django.conf.urls import patterns, include, url
from qa.views import QuestionListView, QuestionView, QuestionNewView, \
QuestionUpdateView, QuestionDeleteView, vote_question
urlpatterns = [
url(r'^$', QuestionListView.as_view(), name='questions'),
url(r'^q/(?P<slug_title>[\w-]+)$', QuestionView.as_vie... | StarcoderdataPython |
3228876 | import os
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, Optional
from rich import print
from cookietemple.common.version import load_ct_template_version
from cookietemple.config.config import ConfigCommand
from cookietemple.create.domains.cookietemple_template_struct import ... | StarcoderdataPython |
1688528 | __author__ = 'justinarmstrong'
import pygame as pg
from .. import setup
from .. import constants as c
from . import powerups
from . import coin
class Coin_box(pg.sprite.Sprite):
"""Coin box sprite"""
def __init__(self, x, y, contents='coin', group=None):
pg.sprite.Sprite.__init__(self)
self.... | StarcoderdataPython |
4838374 | class ClassNames:
RECURRENCE_EVENTS = "recurrence-events"
NO_RECURRENCE_EVENTS = "no-recurrence-events"
CLASSES = [
ClassNames.RECURRENCE_EVENTS,
ClassNames.NO_RECURRENCE_EVENTS
]
FEATURES = [
"age",
"menopause",
"tumor-size",
"inv-nodes",
"node-caps",
"deg-malig",
"breast"... | StarcoderdataPython |
3271052 | <reponame>ahmedkhalf/SimpleShell
from subprocess import check_call, CalledProcessError
import readline
while True:
try:
command = input("$ ")
except EOFError:
break
except KeyboardInterrupt:
print()
continue
if command.strip() == "exit":
break
else:
... | StarcoderdataPython |
3362924 | <gh_stars>0
#!/usr/bin/env python3
from .arguments import arguments
from . import capture, cleanup
from .compileVideo import compileVideo
from .interface import banner, print_statusline
from .logger import logging
from time import sleep
def main():
# print program banner if verbose is set
if arguments["--verb... | StarcoderdataPython |
58436 | <reponame>smarie/python-doit-api<filename>doit_api/main.py
import sys
from inspect import isgeneratorfunction
from os.path import exists
import platform
try:
from typing import Callable, Union, List, Tuple, Dict, Optional, Type, Any
from pathlib import Path
DoitAction = Union[str, List, Callable, Tuple[C... | StarcoderdataPython |
83231 | #
# elkme - the command-line sms utility
# see main.py for the main entry-point
#
__version__ = '0.6.0'
__release_date__ = '2017-07-17'
| StarcoderdataPython |
1758703 | <filename>test-rst2.py
import io
import os
import select
import socket
import time
import utils
# 以下はnetwork namespaceを新たに作成するためか、tcp_fin_timeoutの変更等が継承されないためコメントアウト
# utils.new_ns()
port = 1
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
s.bind(('127.0.0.1', port))
s.listen(16)
tcpdump = utils.tcpdump_st... | StarcoderdataPython |
96489 | """MPC Algorithms."""
import torch
from torch.distributions import MultivariateNormal
from rllib.util.parameter_decay import Constant, ParameterDecay
from .abstract_solver import MPCSolver
class MPPIShooting(MPCSolver):
"""Solve MPC using Model Predictive Path Integral control.
References
----------
... | StarcoderdataPython |
3393912 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-23 21:56
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('snorna', '0002_clinical_genomic_analysis_snorna_expression'),
]
operations = [
... | StarcoderdataPython |
184287 | <gh_stars>1-10
#!/usr/bin/env python
import pytest
"""
Test 1805. Number of Different Integers in a String
"""
@pytest.fixture(scope="session")
def init_variables_1805():
from src.leetcode_1805_number_of_different_integers_in_a_string import Solution
solution = Solution()
def _init_variables_1805():
... | StarcoderdataPython |
42994 | <reponame>josborne-noaa/PyFerret<gh_stars>10-100
'''
Template for creating a PyFerret Python External Function (PyEF).
The names of the functions provided should not be changed. By
default, PyFerret uses the name of the module as the function name.
Copy this file using a name that you would like to be the function
n... | StarcoderdataPython |
3334883 | from .pytorch_helpers import cuda_to_numpy
import numpy as np
from .costum_loss_functions import CostumMetric, INetworkLossFunction
import torch
import torch.nn.functional as F
class Accuracy(CostumMetric):
def __init__(self):
self.mode = 'max'
self.__name__ = 'acc'
def __call__(self, y_pred... | StarcoderdataPython |
1636277 | from aioazstorage import TableClient
from os import environ
from datetime import datetime
from uuid import uuid1
from time import time
from asyncio import set_event_loop_policy, Task, gather
try:
from uvloop import get_event_loop, EventLoopPolicy
set_event_loop_policy(EventLoopPolicy())
except ImportError:
... | StarcoderdataPython |
4814952 | import datetime
from database.database_schemas import Schemas
from database.dsstox.generic_substances import GenericSubstances
from database.dsstox.source_substances import SourceSubstances
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey
from sqlalchemy.dialects.mysql import FLOAT
from sqlalchemy.... | StarcoderdataPython |
3252573 | """String utils module"""
import re
def replace_ascii(str):
# Substitute swedish characters for sensible counterparts
str = str.replace(u'\xc5','A')
str = str.replace(u'\xe5','a')
str = str.replace(u'\xc4','A')
str = str.replace(u'\xe4','a')
str = str.replace(u'\xd6','O')
str = str.replace... | StarcoderdataPython |
3369657 | """
Unique usernames
You get an list of names and need to return a list of unique usernames.
For a duplicate name, add the next integer after the name
For example:
Input
['Julie', 'Emma', 'Zoe', 'Liam', 'Emma']
Output
['Julie', 'Emma', 'Zoe', 'Liam', 'Emma1']
Input
['Julie', 'Zoe', 'Zoe', 'Liam', 'Emma', 'Zoe']
Outp... | StarcoderdataPython |
4803189 | <reponame>atamraka/PythonExamples<gh_stars>0
'''
Created on May 14, 2017
@author: rujina
'''
'''
select any 6 columns out of the columns inside csv file attached to this email and write it in other csv files
with the same column names.(do not select adjacent coloumns)
'''
# with open('write.csv', 'wb') as csv_write_f... | StarcoderdataPython |
3305447 | <reponame>nacknime-official/freelancehunt-api<gh_stars>1-10
#!usr/bin/python3
"""`Freelancehunt Documentation - Profiles API <https://apidocs.freelancehunt.com/?version=latest#7dfb1bc1-4d54-46d8-9c01-75b7a32f3db6>`_."""
from typing import List, Optional, Tuple, Union
from ..core import FreelancehuntObject
from ..models... | StarcoderdataPython |
20539 | from abaqusConstants import *
from .OdbPart import OdbPart
from .OdbStep import OdbStep
from .SectionCategory import SectionCategory
from ..Amplitude.AmplitudeOdb import AmplitudeOdb
from ..BeamSectionProfile.BeamSectionProfileOdb import BeamSectionProfileOdb
from ..Filter.FilterOdb import FilterOdb
from ..Material.Mat... | StarcoderdataPython |
138714 | import hydra
from hydra.core.config_store import ConfigStore
from omegaconf import OmegaConf
from configs import TrainConfig
from jerex import model, util
cs = ConfigStore.instance()
cs.store(name="train", node=TrainConfig)
@hydra.main(config_name='train', config_path='configs/docred_joint')
def train(cfg: TrainCon... | StarcoderdataPython |
197832 | <gh_stars>10-100
from apiwrapper.endpoints.endpoint import Endpoint
from apiwrapper.endpoints.monetary_account import MonetaryAccount
class DraftPayment(Endpoint):
__endpoint_draft_payment = "draft-payment"
@classmethod
def _get_base_endpoint(cls, user_id, account_id):
endpoint = MonetaryAccount... | StarcoderdataPython |
3203919 | <reponame>PoncinMatthieu/skrm
from __future__ import print_function
import os
import getopt
import sys
import subprocess
import re
def exit_with_usage(error=0, msg=""):
if error != 0:
print("Error: " + msg)
print("usage: ./skrm [OPTIONS] [COMMANDS] [TAGS]")
print("skrm stands for simple keyring m... | StarcoderdataPython |
1757447 | import os.path
import sys
from download import download
import numpy as np
import pandas as pd
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + (os.path.sep + '..')*2)
import Coberny as cyb
from Coberny.url import *
def test_indice1():
url = 'https://raw.githubusercontent.com/ABernard27/PROJET-group... | StarcoderdataPython |
1748594 | <gh_stars>1-10
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from optparse import make_option
import os
import sys
import glob
import shutil
try:
set
except NameError:
from sets import Set as set # Python 2.3 fallback
# Based on the collectmedia management c... | StarcoderdataPython |
111468 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
version = "0.0.25"
setuptools.setup(
name="commondtools",
version=version,
author="<NAME>",
author_email="<EMAIL>",
description="Common D-tools.",
long_description=long_description,
long_description_cont... | StarcoderdataPython |
3204141 | <filename>algorithms/sorting/selection_sort.py<gh_stars>1-10
"""
Selection sort always out performs the bubble sort. It is aunstable.
Selection sort also does fewer swap operations, and by extension memory writes
than Bubble sort. In the worst case, it does n-1 swap operations
The core principle in selection... | StarcoderdataPython |
167733 | <filename>Sem5SLLPYTHON/FINALS/partb/1b/1.py
def remdup(a):
return list(set(a))
l=[]
for i in range(0,5):
l.append(input())
print(l)
rev = l[::-1]
print(rev)
print(remdup(l))
print([i for i in range(0,10) if i%2==0])
| StarcoderdataPython |
4836244 | <reponame>chiragmatkar/testplan<gh_stars>0
"""
This file is base on the difflib from python standard library (version: 2.7.9)
it provides diff (context/unified) functions with more options like GNU diff,
including: --ignore-space-change, --ignore-whitespace, --ignore-blank-lines
Due to the different algorithm, its outp... | StarcoderdataPython |
3269048 | #!/usr/bin/python
# Can enable debug output by uncommenting:
#import logging
#logging.basicConfig(level=logging.DEBUG)
import math
import Turbo_I2C.MPU6050 as MPU6050
sensor = MPU6050.MPU6050()
sensor.read_raw_data()
print 'Temp = {0:0.2f} *C'.format(sensor.read_temp())
print 'Pitch = {0:0.2f} grader '.format(sen... | StarcoderdataPython |
83060 | from django.db import models
from django.db.models import Case, F, Q, Value, When
from psqlextra.expressions import HStoreRef
from psqlextra.fields import HStoreField
from .fake_model import get_fake_model
def test_query_annotate_hstore_key_ref():
"""Tests whether annotating using a :see:HStoreRef expression wo... | StarcoderdataPython |
110143 | # Copyright 2017 Battelle Energy Alliance, LLC
#
# 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 t... | StarcoderdataPython |
1798595 | <reponame>paulmassen/kibitzr
import os
import logging
import pkgutil
import importlib
logger = logging.getLogger(__name__)
def dummy_notify_factory(notify_func):
def factory(conf, value):
return notify_func
return factory
def load_notifiers():
path = os.path.dirname(os.path.abspath(__file__))
... | StarcoderdataPython |
21436 | from time import time
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))
from singly_linkedlist.singly_linkedlist import SinglyLinkedList
start = time()
linked_list = SinglyLinkedList()
for i in range(100000):
linked_list.insert_head(111111111111)
end = time()
print("Took {0} sec... | StarcoderdataPython |
189873 | <reponame>yoshihikosuzuki/pbcore<gh_stars>0
from nose.tools import assert_equal, assert_true, assert_false
from numpy.testing import assert_array_equal
from StringIO import StringIO
from pbcore.io import BasH5Collection
from pbcore import data
def lookupSomeReadsByName(bc):
pass
def test():
for fofn in data.... | StarcoderdataPython |
3221949 | <filename>vsts/vsts/work/v4_0/models/capacity_patch.py
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -------------... | StarcoderdataPython |
184119 | <reponame>kilinger/marathon-rocketchat-hubot
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('projects', '0002_auto_20160122_0305'),
]
operations = [
migrations.AddField(
... | StarcoderdataPython |
54499 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Name: sorting.py
# Purpose: Music21 class for sorting
#
# Authors: <NAME>
#
# Copyright: Copyright © 2014-2015 <NAME> and the music21
# Project
# License: BSD, see license.tx... | StarcoderdataPython |
1793038 | <reponame>GmZhang3/data-science-ipython-notebooks<filename>python/python101/basis/distince_test.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import numpy as np
from sklearn.cluster import DBSCAN
def distince(vect1,vect2):
dist = (vect1-vect2)*((vect1-vect2).T)
return dist[0,0]
if __name__ == "__main__":
v1... | StarcoderdataPython |
30198 | from enum import Enum
from typing import Tuple, Type, Optional
class Mode(Enum):
SIMPLE = "s"
EXTENDED = "e"
def __str__(self) -> str:
return self.value
class Header(Enum):
PATH = "Path"
NAME = "Name"
SIZE = "Size"
MODIFIED = "Modified"
ACCESSED = "Accessed"
INPUT = "Inp... | StarcoderdataPython |
1762400 | # +--------------------------------------------------------------------------+
# | Licensed Materials - Property of IBM |
# | |
# | (C) Copyright IBM Corporation 2009-2014. |... | StarcoderdataPython |
1620730 | import sys
import os
import collections
import nltk.data
import string
import math
import features
import traceback
import time
import argparse
import nltk.corpus
import nltk.stem.porter
import textClasses as tc
import cluster
import fuzzy
import rules
CUE_PHRASE_FILE = 'bonus_words'
STIGMA_WORDS_FILE = 'stigma_word... | StarcoderdataPython |
3328285 | __author__ = '1988'
import drawtree
class node:
def __init__(self,parent,isroot=False):
self.parent=parent
self.root=isroot
self.children=[]
def show(self,i=0,drawtool=drawtree.drawtree().showdraw):
if not drawtool:
return
elif drawtool=='print':
... | StarcoderdataPython |
1668931 | <reponame>zianke/cmdnote
from unittest import TestCase
from unittest.mock import patch
from cmdnote.main import main
from .utils import *
class Test(TestCase):
def test_main(self):
with patch('sys.argv', ['cmdnote']):
with captured_output() as (out, err):
main()
... | StarcoderdataPython |
1760837 | # from contextlib import redirect_stdout, redirect_stderr
# from io import StringIO
from unittest.mock import patch, call
from ..base import IntegrationTests
from ..util import fork
class TestNoProfile(IntegrationTests):
""" Integration tests for no profile. """
@fork()
def test_logout_via_awscli(self):
... | StarcoderdataPython |
51757 | from datetime import timedelta, datetime
from typing import Optional
from fastapi import HTTPException, Depends
from fastapi.security import OAuth2PasswordBearer
from jose import jwt, JWTError
from passlib.context import CryptContext
from pydantic import BaseModel
from db import database as adb
from usermanagement.mod... | StarcoderdataPython |
1636476 | import torch
import torch.nn as nn
import torch.nn.functional as F
class AGNewsmodelWrapper(nn.Module):
def __init__(self, model):
super(AGNewsmodelWrapper, self).__init__()
self.model = model
def compute_bert_outputs( # pylint: disable=no-self-use
self, model_bert, embedding_input, ... | StarcoderdataPython |
16919 | <filename>tests/ut/python/nn/test_activation.py
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.