id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
3276990 | from .utils import iter_flatten, set_seed, get_config_from_args, \
default_argument_parser, log_args, generate_kfold, cross_validation
from .logging import setup_logger
from .get_dataset_api import get_dataset_api
| StarcoderdataPython |
1734628 | import math
import sys
import itertools
import itertools
import collections
def sa(Type= int):
return [Type(x) for x in input().split()]
def solve(t):
n = int(input())
s = input()
cc = collections.defaultdict(int)
for i in range(len(s)-1):
cc[s[i:i+2]] += 1
result = max(cc.items(), key= lambda x: x... | StarcoderdataPython |
129333 | <reponame>msgoff/transitions<filename>tests/test_markup.py
try:
from builtins import object
except ImportError:
pass
from transitions.core import Enum
from transitions.extensions.markup import MarkupMachine, rep
from transitions.extensions import MachineFactory
from transitions.extensions.factory import Hierar... | StarcoderdataPython |
3320838 | class Solution(object):
def minMoves(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return 0 if not nums else sum(nums) - min(nums) * len(nums)
s = Solution()
print(s.minMoves([1, 2, 3]))
# https://discuss.leetcode.com/topic/66737/it-is-a-math-question | StarcoderdataPython |
4810610 | <filename>tests/test_tides_api.py
from .context import showtime
from showtime.tidesapi import TidesApiClient
from datetime import datetime
from showtime.tides_util import get_tides
def test_tides_client_returns_result():
dt = datetime.utcnow()
start_date = '{0}-{1}-{2}'.format(dt.year, dt.month, dt.day)
ac... | StarcoderdataPython |
1622051 | """Retina dataset."""
import re
import tensorflow_datasets as tfds
_DESCRIPTION = """\
Retinal OCT image dataset reflecting Drusen, DME, CNV and Normal
"""
_CITATION = """\
title = {Retinal OCT image data}
author = {paultimothymooney}
publisher = {Kaggle}
url = {https://www.kaggle.com/paultimothymooney/kermany2018 ... | StarcoderdataPython |
146916 | import os
import time
import logger
import random
import tensorflow as tf
import gym
import numpy as np
from collections import deque
from config import args
from utils import set_global_seeds, sf01, explained_variance
from agent import PPO
from env_wrapper import make_env
def main():
env = make_env()
set_gl... | StarcoderdataPython |
3267352 | <reponame>JohnnyHao/Py-Spider<filename>SpiderDouban.py
#!/usr/bin/python
#-*- coding: utf-8 -*-
#encoding=utf-8
import urllib2
import urllib
from BeautifulSoup import BeautifulSoup
def getAllImageLink():
html = urllib2.urlopen('http://www.dbmeizi.com').read()
soup = BeautifulSoup(html)
liResult = soup.fin... | StarcoderdataPython |
3399546 | """
Scripts to manage Mailman mailing lists.
"""
from .utils import confirm, DocOptArgs, entrypoint
from ..plumbing.common import Owner
from ..tasks import mailman
@entrypoint
def create(opts: DocOptArgs, owner: Owner):
"""
Create a Mailman mailing list.
If SUFFIX is omitted, the list will be named afte... | StarcoderdataPython |
3360180 | # Copyright 2016-2020 Blue Marble Analytics 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 ag... | StarcoderdataPython |
4829847 | <reponame>jisazaTappsi/mastermind
#!/usr/bin/env python
"""Test for code.py"""
import unittest
from shatter.code import Code
from tests.generated_code import code_functions as f
from tests.testing_helpers import common_testing_code
from shatter.custom_operator import CustomOperator
__author__ = '<NAME>'
class Cod... | StarcoderdataPython |
1608990 | <gh_stars>1-10
# Copyright 2017 Neural Networks and Deep Learning lab, MIPT
#
# 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 requi... | StarcoderdataPython |
1760025 | <filename>Spark/DL_H2O.py
from pysparkling import *
hc = H2OContext.getOrCreate(sc)
import time
import h2o
from h2o.estimators.deeplearning import H2OAutoEncoderEstimator, H2ODeepLearningEstimator
input1=h2o.import_file("/home/admin/RECO/cluster8.csv",sep=",")
input_df = input1.as_data_frame(use_pandas=True)
inp... | StarcoderdataPython |
76841 | <filename>bayesapi/fips.py
import csv
import os
from snaql.factory import Snaql
def read_fips(fn):
with open(fn) as fips_file:
reader = csv.reader(fips_file, delimiter=',')
cols = ['state-name', 'state-code', 'county-code','county-name','class-code']
return [ dict(zip(cols, row)) for row ... | StarcoderdataPython |
34493 | <filename>cell.py
import torch
import torch.nn as nn
import torch.nn.functional as F
class HiddenGate(nn.Module):
def __init__(self, hidden_size, input_size, bias, nonlinearity="sigmoid"):
super(HiddenGate, self).__init__()
self.linear = nn.Linear(
3*hidden_size + input_size + hidden_... | StarcoderdataPython |
3286956 | import numpy as np
import cv2
class Net(object):
def __init__(self, model_path, use_cpu=False, prefix='prefix',
pad=52, max_mp=5, gpu_fraction=None):
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
self.pad = pad
self.max_megapixels = max_mp if max_mp is... | StarcoderdataPython |
3217356 | # coding=UTF-8
#
# Copyright 2017 Google Inc. 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 ap... | StarcoderdataPython |
3321957 | <reponame>itemmanager/bungieapi
# generated by update to not change manually
import dataclasses as dt
import typing as t
from bungieapi.json import to_json
@dt.dataclass(frozen=True)
class EntityActionResult:
entity_id: int
result: "PlatformErrorCodes"
def to_json(self) -> t.Mapping[str, t.Any]:
... | StarcoderdataPython |
4838735 | # Generated by Django 2.1.3 on 2018-11-05 14:02
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('home', '0024_auto_20181105_1131'),
]
operations = [
migrations.RenameField(
model_name='semester_1',
old_name='professerr_na... | StarcoderdataPython |
192838 | from conans import ConanFile, CMake, tools
import os
class Conan(ConanFile):
name = 'DiligentEngine'
version = '2.5'
homepage = 'https://github.com/DiligentGraphics/DiligentEngine'
description = 'A Modern Cross-Platform Low-Level 3D Graphics Library and Rendering Framework'
topics = ('conan', 'Dili... | StarcoderdataPython |
3312837 | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | StarcoderdataPython |
4811181 | lista = []
def Datos():
print "Introduzca 3 numeros enteros: "
i = 0
while i < 3:
lista.append(input())
i += 1
def Mostrar():
print "\nNumeros ingresados: \n"
for elemento in lista:
print elemento | StarcoderdataPython |
1757343 | <reponame>meetri/cryptolib<filename>libs/modules/tradewallet.py
import random,uuid,os
from datetime import datetime
from mongowrapper import MongoWrapper
from twiliosms import TwilioSms
class TradeWallet(object):
def __init__( self, config = {}):
self.buys = []
self.rejected = []
self.se... | StarcoderdataPython |
1674143 | <filename>faker/providers/color/he_IL/__init__.py<gh_stars>1-10
from collections import OrderedDict
from .. import Provider as ColorProvider
localized = True
class Provider(ColorProvider):
"""Implement color provider for ``he_IL`` locale."""
"""Source : https://he.wikipedia.org/wiki/%D7%95%D7%99%D7... | StarcoderdataPython |
3388616 | <filename>src/wms_layers.py
# This work is based on original code developed and copyrighted by TNO 2020.
# Subsequent contributions are licensed to you by the developers of such code and are
# made available to the Project under one or several contributor license agreements.
#
# This work is licensed to you under t... | StarcoderdataPython |
1766315 | <gh_stars>0
import itertools, struct
class BinaryObject(object):
_fields_ = []
def __init__(self):
self._total_size = 0
def __len__(self):
return self._total_size
def __repr__(self):
result = ['{']
for slot, fmt in self._fields_:
if slot is None:
... | StarcoderdataPython |
54023 | <reponame>HBOMAT/AglaUndZufall
#!/usr/bin/python
# -*- coding utf-8 -*-
#
# zufall - Funktionen
#
#
# This file is part of zu... | StarcoderdataPython |
3240402 | """
Unit and regression test for the alchemicalitp package.
"""
# Import package, test suite, and other packages as needed
import alchemicalitp
import pytest
import os
from pkg_resources import resource_filename
from tempfile import NamedTemporaryFile
@pytest.fixture
def urea():
return alchemicalitp.top.Topology(... | StarcoderdataPython |
2266 | #!/usr/bin/env python
# coding=utf-8
from setuptools import setup, find_packages
with open('README.md', encoding='utf-8') as f:
readme = f.read()
with open('LICENSE', encoding='utf-8') as f:
license = f.read()
with open('requirements.txt', encoding='utf-8') as f:
reqs = f.read()
pkgs = [p for p in find_... | StarcoderdataPython |
3225469 | string = "THIS SHOULD ALL BE LOWERCASE."
print(string.lower())
string = "this should all be uppercase."
print(string.upper())
string = "ThIs ShOuLd Be MiXeD cAsEd."
print(string.swapcase()) | StarcoderdataPython |
1703843 | <reponame>Virksaabnavjot/MapperReducer<filename>train/Mapper.py
#!/usr/bin/env python
import sys
# Mapper to return 10 passengers by age groups
# Data source: https://www.kaggle.com/c/titanic/data
# Data header: "PassengerId" "Survived" "Pclass" "Name" "Sex" "Age" "SibSp" "Parch" "Ticket" "Fare" "Cabin" "Embarke... | StarcoderdataPython |
158111 | import copy
from musicscore.basic_functions import flatten
class Tree(object):
"""
A simple Tree class
"""
def __init__(self, label=None, *args, **kwargs):
super().__init__(*args, **kwargs)
self._children = []
self._up = None
self._leaves = []
self.label = lab... | StarcoderdataPython |
103773 | # Copyright 2020 Softwerks 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 to in writing... | StarcoderdataPython |
4832568 | <filename>pyglet/libs/x11/xinput.py<gh_stars>1000+
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 <NAME>
# Copyright (c) 2008-2021 pyglet contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modifi... | StarcoderdataPython |
1743531 | <reponame>pg42870/SIB<gh_stars>0
import numpy as np
from .model import Model
from ..util.util import sigmoid, add_intersect
class LogisticRegression(Model):
def __init__(self, gd=False, epochs=1000, lr=0.001):
"""Linear regression Model
epochs: number of epochs
lr: learning rate for GD
"""
super(Logistic... | StarcoderdataPython |
3297198 | <filename>BPt/dataset/tests/test_encoding.py
import numpy as np
import pandas as pd
import pytest
from .datasets import (get_fake_dataset, get_fake_dataset7,
get_fake_multi_index_dataset)
from ..Dataset import Dataset
def test_to_category():
df = Dataset([1, 2, 3], columns=['0'])
df = ... | StarcoderdataPython |
1679486 | import boto3
import boto3.session
import json
from keydra.providers.base import BaseProvider
from keydra.providers.base import exponential_backoff_retry
from keydra.exceptions import DistributionException
from typing import Dict, NamedTuple, Optional
from keydra.exceptions import RotationException
from keydra.clien... | StarcoderdataPython |
6382 | <filename>utils/functions.py
import torch
from torch import nn
import math
#0 left hip
#1 left knee
#2 left foot
#3 right hip
#4 right knee
#5 right foot
#6 middle hip
#7 neck
#8 nose
#9 head
#10 left shoulder
#11 left elbow
#12 left wrist
#13 right shoulder
#14 right elbow
#15 right wrist
def random_rotation(J3d):
... | StarcoderdataPython |
3392247 | <reponame>deeplycloudy/brawl4d
""" Support for LMA data display in brawl4d.
These are meant to be lightweight wrappers to coordinate data formats
understood by the lmatools package.
"""
import numpy as np
from lmatools.flashsort.autosort.LMAarrayFile import LMAdataFile
from stormdrain.bounds import Bou... | StarcoderdataPython |
1735149 | # Generated by Django 2.1.2 on 2019-01-04 13:24
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Component",
fields=[
(
"id",... | StarcoderdataPython |
108739 | <gh_stars>1-10
from django.http import JsonResponse
def index_view(request):
"""
Function returns basic information about our project.
"""
data = {
'name': 'Mikaponics API Web-Service',
'version': 1.0,
}
return JsonResponse(data)
| StarcoderdataPython |
1624367 | r"""
This folder contains all of the Tortoise ORM model classes
"""
from .guilds import GuildModel
from .members import MemberModel
__all__ = ("GuildModel", "MemberModel")
| StarcoderdataPython |
1789011 | <gh_stars>0
from .... pyaz_utils import _call_az
def set(account_name, container_name, tags, allow_protected_append_writes_all=None, resource_group=None):
'''
Set legal hold tags.
Required Parameters:
- account_name -- Storage account name. Related environment variable: AZURE_STORAGE_ACCOUNT.
- co... | StarcoderdataPython |
103785 | import pickle
from hashlib import sha256
from urlparse import urlparse
from xml.dom import minidom
from fetch_remote_file import *
class Reader():
cache = '/tmp/'
expire = 5
feeds = []
hashes = []
stories = []
def __init__(self):
if not os.path.exists(self.cache):
os... | StarcoderdataPython |
27086 | <reponame>victor-gil-sepulveda/PhD-HIVProteaseMutation
"""
Created on 25/8/2014
@author: victor
"""
import prody
import numpy
class CurationSelections():
LIGAND_SELECTION = "hetero not water not ion"
HEAVY_LIGAND_SELECTION = "hetero and not water and not ion and not hydrogen"
PROTEIN_CHAIN_TEMPLATE = "pr... | StarcoderdataPython |
1660328 | <reponame>AutoDash/AutoDash<gh_stars>1-10
class IndexedRect(object):
def __init__(self, i, x1, y1, x2, y2):
if x1 > x2:
x1, x2 = x2, x1
if y1 > y2:
y1, y2 = y2, y1
self.x1 = x1
self.x2 = x2
self.y1 = y1
self.y2 = y2
self.i = i
de... | StarcoderdataPython |
4824951 | #!/usr/bin/env python2
from pwn import *
context.log_level = 1000
with tempfile.NamedTemporaryFile() as fd:
s = randoms(12)
fd.write(s)
fd.flush()
l = listen(0)
l.spawn_process(['./ropasaurusrex-85a84f36f81e11f720b1cf5ea0d1fb0d5a603c0d'])
p = process(["./doit.py", "SILENT", "HOST=localhost", ... | StarcoderdataPython |
1766425 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2018, <NAME>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status':... | StarcoderdataPython |
1725523 | '''
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).
Implement the MyQueue class:
void push(int x) Pushes element x to the back of the queue.
int pop() Removes the element from the front of the que... | StarcoderdataPython |
91970 | '''The framework module contains the logic used in building the graph and
inferring the order that the nodes have to be executed in forward and backward
direction.
Based on FrEIA (https://github.com/VLL-HD/FrEIA)'''
import torch.nn as nn
from torch.autograd import Variable
import FrEIA.dummy_modules as dummys
clas... | StarcoderdataPython |
1609420 | # Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack.package import *
class Hpcviewer(AutotoolsPackage):
"""Uses version-test-pkg, as a build dependency"""
... | StarcoderdataPython |
3247214 | import os
import argparse
# late import of alembic because it destroys loggers
def get_config(directory, x_arg=None, opts=None):
from alembic.config import Config as AlembicConfig
class Config(AlembicConfig):
def get_template_directory(self):
package_dir = os.path.abspath(os.path.dirname(_... | StarcoderdataPython |
3357537 | import functools
from copy import deepcopy
from abc import abstractmethod, ABCMeta
from ..compare import compare
class BaseMatcher(object):
"""
BaseMatcher implements the basic HTTP request matching interface.
"""
__metaclass__ = ABCMeta
# Negate matching if necessary
negate = False
def... | StarcoderdataPython |
48150 | import numpy as np
import pandas as pa
import time
from sklearn.metrics import pairwise_distances
from scipy.sparse import csr_matrix
class Kmeans:
def __init__(self,data,k,geneNames,cellNames,cluster_label=None,seed=None):
self.data=data
self.k=k
self.geneNames=geneNames
self.cellN... | StarcoderdataPython |
3321654 | import six
from .node import Node
@six.python_2_unicode_compatible
class StockExchange(Node):
"""Represents a Website on CrunchBase"""
KNOWN_PROPERTIES = [
'name',
'short_name',
'symbol',
'created_at',
'updated_at',
]
def __str__(self):
return u'{name... | StarcoderdataPython |
4818149 | """
Compute language embeddings for the labels
NB: we release our language embeddings so you won't need to run this script. We only provide it as indication and in case you wish to compute word embedding for new words.
We use a Word2vec model trained on GoogleNews:
https://drive.google.com/file/d/0B7XkCwpI5KDYNlNUTTl... | StarcoderdataPython |
190433 | <reponame>nishi-yuki/trimtr-api
import unittest
import random
from trimtr.trimmer import Trimmer
class TestTrimmer(unittest.TestCase):
def setUp(self):
self.trimmer = Trimmer.get_instance()
# 文と文の間は改行される
def test_new_line_between_sentences(self):
original_sentence = "How are you? I am fin... | StarcoderdataPython |
3330780 | """ Display some information about a user """
from registrar import AbstractCommand, bot_command
from discord import embeds
from discord.enums import Status
@bot_command
class Command(AbstractCommand):
""" Template for bot command classes. """
_name = 'tellmeabout'
_aliases = ['tellmeabout']
_enabled... | StarcoderdataPython |
91821 | n,k=map(int,input().split());a=[int(i) for i in input().split()];m=sum(a[:k]);s=m
for i in range(k,n):
s+=(a[i]-a[i-k])
if s>m:m=s
print(m)
| StarcoderdataPython |
1791425 | '''
<NAME>
Rule to detect binding to 0.0.0.0
Jan 21, 2019
'''
from ansiblelint import AnsibleLintRule
class InvalidBindingRule(AnsibleLintRule):
id = 'SECURITY:::BINDING_TO_ALL:::'
shortdesc = 'Binding to 0.0.0.0'
description = 'Check for use for binding to 0.0.0.0'
tags = { 'security' }
def m... | StarcoderdataPython |
3234533 | import requests
import argparse
import os
from bs4 import BeautifulSoup
import youtube_dl
from termcolor import colored
from banner import banner
def downloader(courseTitle, dl, qualityCode="18"):
if not os.path.exists(courseTitle):
os.mkdir(courseTitle)
for mod, lecs in dl.items():
mod = cours... | StarcoderdataPython |
3260310 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import cv2
# Prepare object pointes
nx = 8
ny = 6
# Make a list of calibration images
fname = '../images/calibration_test.png'
img = cv2.imread(fname)
# convert to grayscale
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Find t... | StarcoderdataPython |
3395107 | from ftmstore import Dataset, settings
def get_dataset(name, origin, database_uri=None):
database_uri = database_uri or settings.DATABASE_URI
return Dataset(name, origin, database_uri=database_uri)
| StarcoderdataPython |
3252127 | #!/usr/bin/python
#
# Simple subunit testrunner for python
# Copyright (C) <NAME> <<EMAIL>> 2007
#
# Licensed under either the Apache License, Version 2.0 or the BSD 3-clause
# license at the users choice. A copy of both licenses are available in the
# project source as Apache-2.0 and BSD. You may not use this fi... | StarcoderdataPython |
3256990 | <gh_stars>0
import pytest
import requests
from typing import Dict, Union, List
def _print_kg(kg: Dict[str, Dict[str, Dict[str, Dict[str, Union[List[str], str, None]]]]]):
nodes_by_qg_id = kg["nodes"]
edges_by_qg_id = kg["edges"]
for qnode_key, node_ids in sorted(nodes_by_qg_id.items()):
print(f"{q... | StarcoderdataPython |
3287941 | # -*- coding: utf-8 -*-
import pandas as pd
from py2neo import Graph, Node, Relationship, NodeMatcher
# 读取csv文件
movies_df = pd.read_csv(r'./movies.csv')
actors_df = pd.read_csv(r'./actors.csv')
# 连接Neo4j服务
graph = Graph(host="localhost://7474", auth=("neo4j", "jc147369"))
# 创建电影节
for i in range(movies_df.shape[0])... | StarcoderdataPython |
1739218 | #!/usr/bin/env python3
import argparse
import torch
import torch.jit
import torch.nn as nn
import torch.nn.functional as F
from generate_cnn_model import PolicyHead, ValueHead
class TransformerModel(nn.Module):
def __init__(self, input_channel_num, block_num, channel_num, policy_channel_num, board_size):
... | StarcoderdataPython |
1788768 | <gh_stars>10-100
"""
This script constructs a MILP model for AES-like primitives, which can aid in
finding optimal parameter sets against differential attacks by counting the
minimum number of active S-boxes in a differential trail.
It uses the Gurobi Solver to solve the MILP instance, hence you need
a Gurobi license ... | StarcoderdataPython |
1762544 | # Generated by Django 2.0.5 on 2018-05-05 23:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('work', '0005_auto_20180505_2310'),
]
operations = [
migrations.AlterField(
model_name='article',
name='description',... | StarcoderdataPython |
1738684 | import sys
import string
import tensorflow as tf
from tensorflow.python.ops import control_flow_ops
from aster.core import standard_fields as fields
from aster.c_ops import ops
def _apply_with_random_selector(x, func, num_cases):
"""Computes func(x, sel), with sel sampled from [0...num_cases-1].
Args:
x: i... | StarcoderdataPython |
1762119 | <reponame>KarrLab/bpforms<gh_stars>1-10
""" Test of bpforms.core
:Author: <NAME> <<EMAIL>>
:Date: 2019-01-31
:Copyright: 2019, Karr Lab
:License: MIT
"""
from bpforms import core
from bpforms.alphabet import dna
from bpforms.alphabet import protein
from bpforms.alphabet import rna
from wc_utils.util.chem import Empir... | StarcoderdataPython |
1772725 | <reponame>kamoliddeenov/translitobot
from aiogram import types
from aiogram.dispatcher.filters.builtin import CommandHelp
from loader import dp, db
from utils.misc.msg_dict import texts
@dp.message_handler(CommandHelp())
async def bot_help(message: types.Message):
lang = await db.select_user(telegram_id=message.... | StarcoderdataPython |
1751552 | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--incognito")
driver = webdriver.Chrome(chrome_options=chrome_options)
# driver = webdriver.Chrome('chromedriver.exe', chrome_options=self.browserProfile)
d... | StarcoderdataPython |
4829676 | # Python example to check if a class is
# subclass of another
class Base(object):
pass # Empty Class
class Derived(Base):
pass # Empty Class
# Driver Code
print(issubclass(Derived, Base))
print(issubclass(Base, Derived))
d = Derived()
b = Base()
# b is not an instance of Derived
print(isinstance(b, D... | StarcoderdataPython |
3223554 | <filename>03-graph-algorithms/1_graph_decomposition/toposort_dfs.py
import sys
class Graph:
def __init__(self, n, edges):
self._vertices_count = n
self._build_adjacency_list(edges)
# Time Complexity: O(|E|)
# Space Complexity: O(1)
def _build_adjacency_list(self, edges):
... | StarcoderdataPython |
3289800 | <filename>scripts/turtlebot.py<gh_stars>10-100
from math import pi, sqrt, atan2, cos, sin
import numpy as np
import matplotlib.pyplot as plt
import rospy
import tf
from geometry_msgs.msg import Twist, Pose2D
from nav_msgs.msg import Odometry
from obstacle_detector.msg import Obstacles, CircleObstacle, SegmentObstacle
... | StarcoderdataPython |
74539 | <filename>app.py<gh_stars>0
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import pandas as pd
## verbo en espanol a conjugacion en mapudungun
verbos=pd.read_csv('verbs.csv',header=0,sep=',')
verbos = verbos.sort_values(['esp', 'map... | StarcoderdataPython |
114199 | <reponame>istrategylabs/django-flashbriefing<filename>tests/test_models.py
import datetime
import pytest
from flashbriefing.models import Feed, Item, ItemType
@pytest.mark.django_db
def test_item_type_audio():
feed = Feed.objects.create(title='FEED')
item = Item.objects.create(
feed=feed, title='ITEM... | StarcoderdataPython |
96595 | # Copyright 2020 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | StarcoderdataPython |
1758097 | # 一个重构的时间类,通过str可以得到moviepy裁切电影的标准时刻字符串
class Tick:
@property
def hour(self):
return self.__hour
@hour.setter
def hour(self, value: int):
self.__hour = value
@property
def min(self):
return self.__min
@min.setter
def min(self, value: int):
self.__min =... | StarcoderdataPython |
4809673 | """
Censor 2 ----> CENSOR 1
Designed to be run by the evaluator.
TCP Censor that synchronizes on first SYN only, works 100% of the time, sends 5 RSTs to client.
"""
import layers.packet
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import IP, TCP
from censors.censor impor... | StarcoderdataPython |
183598 | <reponame>UCSD-E4E/vmman-mangrove
#!/usr/bin/python3
import docker
import argparse
import configparser
import json
import time
from tabulate import tabulate
import sys
class DockerAutomation():
@staticmethod
def start_container(container_ind, client):
print(config["ids"][container_ind])
co... | StarcoderdataPython |
3218024 | <reponame>aawarner/BLT-ASIC<gh_stars>1-10
"""Copyright (c) 2019 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.1 (the "License"). You may obtain a copy of the
License at
https://developer.cisco.com/docs/licenses
All use of the mat... | StarcoderdataPython |
1775529 | <gh_stars>0
# @date 2018-08-23
# @author <NAME>, All rights reserved without prejudices.
# @license Copyright (c) 2018 Dream Overflow
# HTTPS+WS connector for bitmex.com
import time
import json
import requests
from datetime import datetime, timedelta
from common.utils import UTC
from .apikeyauthwithexpires import AP... | StarcoderdataPython |
3348357 | import torch
from torch.distributions import Beta, Normal, TransformedDistribution
from torch.distributions.transforms import AffineTransform
class TransformedDistributionEx(TransformedDistribution):
def entropy(self):
"""
Returns entropy of distribution, batched over batch_shape.
Returns:... | StarcoderdataPython |
188313 | from .generated import access_ui
from .generated import data_sheet_ui
from .generated import form_item_ui
from .generated import form_ui
from .generated import item_boolean_checkboxes_ui
from .generated import item_choice_radio_ui
from .generated import item_datetime_ui
from .generated import item_single_line_ui
from .... | StarcoderdataPython |
1775647 | <filename>framework/lib/dlju/maven_junit.py
import capture_junit as cj
import re
import os
tests_begin = """-------------------------------------------------------
T E S T S
-------------------------------------------------------"""
def findBeginningOfTests(output):
""" Find where the test running begins
Pa... | StarcoderdataPython |
1600533 | import multiprocessing as mp
mp.set_start_method('spawn', force=True)
import argparse
import os
import time
import yaml
import numpy
import logging
from easydict import EasyDict
import pprint
from tensorboardX import SummaryWriter
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.opt... | StarcoderdataPython |
128814 | <filename>models/Connection.py
from genie.testbed import load
from prettyprinter import pprint
class PYATSConnection:
def __init__(self):
self.__testbed = load("./res/testbeds/testbed.yaml")
def __find_device_by_ip(self, ip):
for device_name, device in self.__testbed.devices.items():
if ip == str(device.conn... | StarcoderdataPython |
3279567 | #coding:utf-8
import argparse
import os
import numpy as np
import paddlehub as hub
import paddle.fluid as fluid
from paddle.fluid.dygraph import Linear
from paddle.fluid.dygraph.base import to_variable
from paddle.fluid.optimizer import AdamOptimizer
# yapf: disable
parser = argparse.ArgumentParser(__doc__)
parser.ad... | StarcoderdataPython |
127711 | <reponame>jgayfer/Spirit<gh_stars>10-100
from discord.ext import commands
import discord
import asyncio
from cogs.utils import constants
from cogs.utils.message_manager import MessageManager
class Core:
"""Core functionality required for the bot to function"""
def __init__(self, bot):
self.bot = bot... | StarcoderdataPython |
168591 | <gh_stars>100-1000
class Solution:
def matrixScore(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
if not A or not A[0]: return 0
n, m = len(A), len(A[0])
tot = n*2**(m-1)
for i in range(1, m):
zero = sum(A[j][0]^A[j][i] fo... | StarcoderdataPython |
1659071 | <reponame>sys-bio/rrplugins
from teplugins import *
try:
modelPlugin = Plugin("tel_test_model")
noisePlugin = Plugin("tel_add_noise")
chiSquarePlugin = Plugin("tel_chisquare")
#Generate internal test data
modelPlugin.execute()
modelData = modelPlugin.TestData
... | StarcoderdataPython |
3256301 | <gh_stars>1-10
import requests
import sys
class app:
def __init__(self, token):
self.token = token
self.headers = {'Authorization': token}
def execute(self):
return requests.get('https://discord.com/api/v6/guilds/0/members', headers=self.headers)
def main():
print(... | StarcoderdataPython |
3294898 | import sys,os
from . import config
def main(args):
MS_fin=args.MS_fin#LCL.mzML/Subject3_rep3_021213_Fx100mM.mzML
MS_db=args.MS_db #~/flashscratch/LCL/all_jp/tmp/proteome_ref_merged.fa
outdir=args.outdir
cmd1= args.java_path+' -Xmx8g -jar '+args.MSGF_path+' -s '+MS_fin+' -d '+MS_db+' -e 0 -tda 1 -maxLength 13 -minL... | StarcoderdataPython |
47847 | <gh_stars>0
from libra_client.lbrtypes.event import EventHandle
from libra_client.canoser import Struct, Uint64
from libra_client.move_core_types.move_resource import MoveResource
class CredentialResource(Struct, MoveResource):
MODULE_NAME = "DualAttestation"
STRUCT_NAME = "Credential"
_fields = [
... | StarcoderdataPython |
24722 | from .validator import (
And,
Attr,
Chain,
Const,
Contains,
ExcMax,
ExcMin,
Float,
Macro,
Max,
Min,
MultipleOf,
Not,
Or,
Pattern,
Proto,
Type,
Validator,
Xor,
)
__all__ = [
"And",
"Attr",
"Chain",
"Const",
"Validator",
... | StarcoderdataPython |
1621467 | <filename>experiments/project_generators/histogram_per_query_generate_500_dbpedia_cleaned_full_nindices_1.py
import json
base_raw = """
{
"name": "histogram-generate-per-query-%d-500-dbpedia-cleaned-full-nindices-1",
"description": "Generate histogram/counters for index and table usage, repetition will be 5 tim... | StarcoderdataPython |
3293677 | <reponame>nicorellius/pdxpixel
import logging
from django.shortcuts import render, HttpResponseRedirect, get_object_or_404
from django.contrib.auth import authenticate, login, logout
from django.views.generic.base import View
from django.contrib import messages
from django.utils.decorators import method_decorator
from... | StarcoderdataPython |
3316849 | <gh_stars>0
from sys import argv
from os.path import exists
script, from_file, to_file=argv
print(f"Copying from{from_file} to {to_file}")
in_file=open(from_file)
indata=in_file.read()
print(f"The input file is {len(indata)} bytes long")
print(f"Does the output file exist?{exists(to_file)}")
print("Ready,hit RETUR... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.