id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
6558351 | <filename>Dataset/Leetcode/test/101/786.py
class Solution:
def XXX(self, root: TreeNode) -> bool:
def symmetric(node1, node2): #定义判断两个子树是否对称函数
if node1 is None and node2 is None: #如果两个子树的根节点都是空的,则对称返回True
return True
elif node1 is None or node2 is None... | StarcoderdataPython |
6590392 | <reponame>alessandrolenzi/yaga
import itertools
import random
from typing import Iterable, Sequence, TypeVar
from yaga_ga.evolutionary_algorithm.individuals import IndividualStructure
from yaga_ga.evolutionary_algorithm.operators.multiple_individuals.base import (
MultipleIndividualOperator,
)
from yaga_ga.evolut... | StarcoderdataPython |
4821557 | <filename>problems/139_word_break.py
'''
URL: https://leetcode.com/problems/word-break
Time complexity: O(n^2)
Space complexity: O(n^2 + m) n is size of string, m is size of word dictionary
'''
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[s... | StarcoderdataPython |
12807666 | <reponame>KaizIqbal/clickgen
from pathlib import Path
import pytest
from clickgen.packer import pack_win
from clickgen.packer.windows import REQUIRED_CURSORS
def test_windows_packer_raises(x11_tmp_dir: Path, theme_name, comment, website):
x11_tmp_dir.joinpath("Work.ani").write_text("test")
with pytest.rais... | StarcoderdataPython |
11382820 | # -*- coding: utf-8 -*-
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# A Fathead parser for wikiHow articles.
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# The data should exist in the data/html directory. If it doesn't, make
# sure that the ./fetch.sh script has been run to scrape the html data
# from the wikiHow website. Y... | StarcoderdataPython |
6674756 | global free
global database_ip
global database_user
global database_password
global database_name
global node_password | StarcoderdataPython |
5138243 | '''
Escreva um programa que receba dois números e um sinal, e faça a operação matemática definida pelo sinal.
'''
numero_1 = float(input('Digite o primeiro numero: '))
numero_2 = float(input('Digite o segundo numero: '))
sinal = input('Digite o sinal da operação: ').strip()
resultado = eval('numero_1 {} numero_2'.fo... | StarcoderdataPython |
9673574 | # Copyright (c) 2020 Graphcore Ltd. All rights reserved.
from examples_tests.test_util import SubProcessChecker
from pathlib import Path
import pytest
root_dir = Path(__file__).parent.parent
build_dir = root_dir.joinpath('test_cmake_build')
class TestBuildAndRun(SubProcessChecker):
def setUp(self):
bui... | StarcoderdataPython |
3215419 | import autodisc as ad
import goalrepresent as gr
def get_system_config():
system_config = ad.systems.Lenia.default_config()
system_config.version = "pytorch_fft"
system_config.use_gpu = True
return system_config
def get_system_parameters():
system_parameters = ad.systems.Lenia.default_system_param... | StarcoderdataPython |
3353460 | from http.server import HTTPServer, BaseHTTPRequestHandler
import json
import re
from fake_os_places_api_entry import FakeOSPlacesAPIEntry
_postcode_to_uprn = {"LS287TQ": 10000000,
"BB11TA": 1000000,
"LE674AY": 1000,
"L244AD": 2000,
... | StarcoderdataPython |
6594871 | <filename>fairapp/apps.py
from django.apps import AppConfig
class FairappConfig(AppConfig):
name = 'fairapp'
| StarcoderdataPython |
3449067 | <filename>doframework/core/pwl.py
import itertools
import numpy as np
from numpy import linalg
from scipy.spatial import ConvexHull
from typing import Callable, Any, List
from dataclasses import dataclass, field
from doframework.core.utils import sample_standard_simplex
def constraint(x: float, y: float, z: float, co... | StarcoderdataPython |
9670057 | # coding: utf-8
import logging
import time
from pony import orm
from ._base import db, BaseModel
import collipa.models
class Notification(db.Entity, BaseModel):
sender_id = orm.Optional(int)
receiver_id = orm.Optional(int)
""" 提醒类型
'reply' : 评论提醒
'answer' : 回复提醒
'mention' : 提及... | StarcoderdataPython |
8046677 | <reponame>ferras/metaflow-service-clone
from aiohttp import web
import json
from .utils import read_body, format_response, handle_exceptions
import asyncio
from ..data.postgres_async_db import AsyncPostgresDB
class MetadataApi(object):
_metadata_table = None
lock = asyncio.Lock()
def __init__(self, app):
... | StarcoderdataPython |
5065857 | import matplotlib.pyplot as plt
def plot_line(ax, normal, offset, **style):
# line equation: Ax + By = C
A, B = normal.real, normal.imag
C = offset
x0 = C * A
y0 = C * B
L = 10
sx = x0 - B * L
sy = y0 + A * L
ex = x0 + B * L
ey = y0 - A * L
line, = ax.plot([sx, ex], [sy, ey... | StarcoderdataPython |
9640152 | """
Copyright (c) Facebook, Inc. and its affiliates.
"""
import logging
import sys
import os
import torch
GEOSCORER_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "geoscorer/")
sys.path.append(GEOSCORER_DIR)
from geoscorer_wrapper import ContextSegmentMergerWrapper
import spatial_utils as su
import ... | StarcoderdataPython |
5018938 | import numpy
import chainer
from chainer import cuda
from chainer.functions.loss import black_out
from chainer import link
from chainer.utils import walker_alias
class BlackOut(link.Link):
"""BlackOut loss layer.
.. seealso:: :func:`~chainer.functions.black_out` for more detail.
Args:
in_size ... | StarcoderdataPython |
8110256 | # -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. 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 requir... | StarcoderdataPython |
9672883 | import unittest
class UnitTestCounts(unittest.TestCase):
"""Tests for ensuring the counter in the status bar is correct for unit tests."""
def test_assured_fail(self):
self.assertEqual(1, 2, 'This test is intended to fail.')
def test_assured_success(self):
self.assertNotEqual(1, 2, '... | StarcoderdataPython |
3475343 | <reponame>whoiszyc/benchmarking-gnns<gh_stars>0
import time
from datetime import datetime
import os
import sys
import logging
import random
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from collections import deque
import keras
from keras.models import Sequential
from keras.optimizers import ... | StarcoderdataPython |
5121106 | import lvgl as lv
from widgets import *
import app
import game as g
import time as t
import random as r
class Ball(g.Sprite):
def __init__(self):
super().__init__("ball", 3, 3, "BALL")
#self.direction = [[-1,1][r.randint(0,1)], 0]
self.direction = [1, 1]
def reset(self):
self... | StarcoderdataPython |
9705615 | <filename>pkgs/anaconda-client-1.4.0-py27_0/lib/python2.7/site-packages/binstar_client/inspect_package/pypi.py<gh_stars>0
from __future__ import print_function, unicode_literals
from email.parser import Parser
import json
from os import path
import re
import tarfile
import zipfile
import sys
import pkg_resources
fro... | StarcoderdataPython |
27450 | <reponame>Akuukis/stellaris-dashboard<gh_stars>10-100
PHYSICS_TECHS = {
"tech_databank_uplinks",
"tech_basic_science_lab_1",
"tech_curator_lab",
"tech_archeology_lab",
"tech_physics_lab_1",
"tech_physics_lab_2",
"tech_physics_lab_3",
"tech_global_research_initiative",
"tech_administr... | StarcoderdataPython |
3571121 | '''Split It!: Reformat spreadsheet of inventory results from Caltech.tind.io
Authors
-------
<NAME> <<EMAIL>> -- Caltech Library
Copyright
---------
Copyright (c) 2019 by the California Institute of Technology. This code is
open-source software released under a 3-clause BSD license. Please see the
file "LICENSE" ... | StarcoderdataPython |
244854 | # -*- coding: utf-8 -*-
# 欢迎关注微信公众号“码上”,了解更多教程信息
# website: https://www.05dt.com/
# github: https://github.com/05dt/scrapy
# -*- coding: utf-8 -*-
import scrapy
class BooksSpider(scrapy.Spider):
# 每一个爬虫的唯一标识
name = "books"
# 定义爬虫爬取的起始点,起始点可以是多个,这里只有一个
start_urls = ['http://books.toscrape.com/']
... | StarcoderdataPython |
359135 | # -*- coding: utf-8 -*-
__author__ = 'wei'
import hashlib
import time
import urllib2
import json
import base64
import threading
import uuid
import StringIO
import gzip
import ssl
from GtConfig import GtConfig
from igetui.igt_message import *
from RequestException import RequestException
from igetui.u... | StarcoderdataPython |
3365129 | <reponame>peendebak/PycQED_py3
import os
import time
from imp import reload
from matplotlib import pyplot as plt
import numpy as np
from pycqed.analysis import measurement_analysis as MA
from pycqed.analysis import ramiro_analysis as RA
from pycqed.analysis import fitting_models as fit_mods
import lmfit
import scipy ... | StarcoderdataPython |
103792 | <reponame>Informasjonsforvaltning/jsonschematordf
"""Test suite for the jsonschematordf package."""
| StarcoderdataPython |
5073675 | <filename>lib/googlecloudsdk/api_lib/api_gateway/gateways.py<gh_stars>1-10
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. 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 Lic... | StarcoderdataPython |
6499387 | class ACS711EX:
def __init__(self, MCP3008, channel):
self.MCP3008 = MCP3008
self.channel = channel
def GetCurrent(self):
return abs(36.7 * self.MCP3008.read_adc(self.channel) / 1023.0 - 18.35)
| StarcoderdataPython |
1680258 | from garage.tf.distributions.diagonal_gaussian import DiagonalGaussian
RecurrentDiagonalGaussian = DiagonalGaussian
| StarcoderdataPython |
1825617 | <reponame>blu3r4y/AdventOfCode2020<gh_stars>1-10
# Advent of Code 2020, Day 14
# (c) blu3r4y
from collections import namedtuple, defaultdict
from itertools import product
from aocd.models import Puzzle
from funcy import print_calls, collecting
from parse import parse
Assignment = namedtuple("Assignment", "addr val")... | StarcoderdataPython |
11266087 | <reponame>steinelu/WebCrawler_py2.7
# -*- coding: utf-8 -*-
"""
Created on Mon May 29 21:15:15 2017
@author: Lukas
"""
import sqlite3
class DB():
def __init__(self, path = None):
try:
self.conn = sqlite3.connect('crwlr.db')
self.db = self.conn.cursor()
except... | StarcoderdataPython |
12864345 | <reponame>NovikovMA/python_training_mantis
# -*- coding: utf-8 -*-
__author__ = 'M.Novikov'
from model.project import Project # Проекты Mantis
from pony.orm import * # Работа с базой данных
from pymysql.converters import dec... | StarcoderdataPython |
1937131 | from fastapi import responses
from typing_extensions import Literal
def invalid_collection_response(
collections: list,
mode: Literal["create", "read"]) -> responses.JSONResponse:
response_error_mssg = {
"create": "api collection already exists",
"read": "api collection not found"... | StarcoderdataPython |
44850 | import normalize
norm = normalize.normalize("heightdata.png", 6, 6)
class TestNormArray:
"""test_norm_array references requirement 3.0 because it shows 2x2 block area of (0,0),
(0,1), (1,0), (1,1), this area will for sure be a 2x2 block area"""
# \brief Ref : Req 3.0 One pixel in topographic image sha... | StarcoderdataPython |
9688701 | <reponame>alvaroscelza/pre-commit-hooks
# -*- coding: utf-8 -*-
import re
from pre_commit_hooks.loaderon_hooks.util.template_methods.files_bunches_checker_template_method import \
FileBunchesCheckerTemplateMethod
class ViewFieldsOrderChecker(FileBunchesCheckerTemplateMethod):
def __init__(self, argv):
... | StarcoderdataPython |
6533223 | # -*- coding: utf-8 -*-
"""
Created on Wed May 10 19:42:51 2017
@author: sakurai
"""
import numpy as np
import chainer
import chainer.functions as F
import chainer.functions as L
import six
class StatelessSimpleACT(chainer.Chain):
def __init__(self, in_size, s_size, out_size,
epsilon=0.01, max_... | StarcoderdataPython |
12821640 | #!/usr/bin/python3
import pymongo
import re
import os
import json
import shutil
import sys
sys.setrecursionlimit(10000)
PORT=27017
client = pymongo.MongoClient("localhost", PORT)
db = client.cuckoo_db
collection = db.malware_results
required_keys = ["info", "signatures", "target", "debug"]
optional_keys = ["virusto... | StarcoderdataPython |
11239593 | <filename>calibration/validation/validation_plots.py<gh_stars>1-10
import numpy as np
import os
import argparse
import json
import math
import statistics
from scipy.stats import chisquare
import matplotlib.pyplot as plt
from validation import validate_stats
# python validation_plots.py -pre_calibration_stats "F:\Dokum... | StarcoderdataPython |
3389012 | <filename>lazyapi/fast.py
from fastapi import FastAPI, Header, Depends, Body, Form, HTTPException, status, BackgroundTasks
from fastapi.responses import JSONResponse, PlainTextResponse
from starlette.middleware.cors import CORSMiddleware
from starlette.requests import Request
from lazycls.types import *
from .config i... | StarcoderdataPython |
6692546 | # Copyright (C) 2019 Intel Corporation. All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
#
import collections
import board_cfg_lib
PCI_HEADER = r"""
#ifndef PCI_DEVICES_H_
#define PCI_DEVICES_H_
"""
PCI_END_HEADER = r"""
#endif /* PCI_DEVICES_H_ */"""
def get_value_after_str(line, key):
""" Get th... | StarcoderdataPython |
8004094 | <filename>scripts/checkout_ipads.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import time
import signal
import subprocess
import logging
import logging.config
import aeios
# should be replaced with `aeiosutil start`
"""
Run aeios Automation
"""
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__copy... | StarcoderdataPython |
9711852 | # -*- coding:utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. 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... | StarcoderdataPython |
4900616 | from importlib import import_module
from app.objects.secondclass.c_fact import Fact
from app.objects.secondclass.c_relationship import Relationship
from app.objects.secondclass.c_rule import Rule
from app.service.interfaces.i_knowledge_svc import KnowledgeServiceInterface
from app.utility.base_knowledge_svc import Bas... | StarcoderdataPython |
188663 | from trees import *
def fizz_buzz_tree(tree):
node=tree.root
temp=[]
def fizzbuzz(node):
if node.value%3==0 and node.value%5==0:
temp.append('FizzBuzz')
elif node.value%3==0:
temp.append('Fizz')
elif node.value%5==0:
temp.append('Buzz')
el... | StarcoderdataPython |
1794486 |
import hashlib
import struct
from collections import OrderedDict
from typing import IO, Any, Optional, Iterable, Mapping, Dict, \
NamedTuple, ClassVar, TypeVar, Type
from pymap.mailbox import MailboxSnapshot
from .io import FileWriteable
__all__ = ['Record', 'UidList']
_UDT = TypeVar('_UDT', bound='UidList')
... | StarcoderdataPython |
1970312 | <filename>python-files/jounFun.py
arr = ["gta","pubg","fortnite","free-fire","nfs"]
final = " or ".join(arr)
print(final,"You can play this games") | StarcoderdataPython |
5194360 | # coding: utf-8
##
# Copyright (C) 2014 <NAME> <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | StarcoderdataPython |
11264860 | # Django
from django import forms
from django.utils.translation import gettext_lazy as _
from django.forms.models import modelformset_factory
from django.contrib.auth.forms import PasswordChangeForm
# Python
import logging
# Third Party
from betterforms.multiform import MultiModelForm
from phonenumber_field.widgets i... | StarcoderdataPython |
1698572 | <reponame>TheLurkingCat/TIOJ
while True:
output = []
try:
N, B = [int(x) for x in input().split()]
except EOFError:
break
if B:
for x in range(1, 2*N, 2):
output.append('*' * x)
else:
for x in range(1, 2*N, 2):
if x == 1:
output... | StarcoderdataPython |
1816231 | #!/usr/bin/env python
from Bio import SeqIO
import sys
import vcf
import subprocess
from collections import defaultdict
import os.path
import operator
from .vcftagprimersites import read_bed_file
#MASKED_POSITIONS = [2282]
MASKED_POSITIONS = []
reference = sys.argv[1]
vcffile = sys.argv[2]
bamfile = sys.argv[3]
DEPT... | StarcoderdataPython |
262316 | <filename>ravenframework/Runners/DistributedMemoryRunner.py<gh_stars>0
# 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... | StarcoderdataPython |
9669392 | from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Nodedata(models.Model):
time = models.TextField(max_length = 64)
localshortaddr = models.TextField(max_length = 64)
gateway_id = models.TextField(max_length = 64)
slaveId = models.TextField(max_length = 64)
humi... | StarcoderdataPython |
4887920 | from django.db import models
from django.contrib.auth.models import User
class Item(models.Model):
link = models.CharField(max_length=100)
group = models.IntegerField()
category = models.CharField(max_length=100)
title = models.CharField(max_length=100)
date = models.DateTimeField(auto_now_add=Tru... | StarcoderdataPython |
1751835 | <gh_stars>0
import tensorflow as tf
from tensorflow.contrib import rnn
# from tensorflow.contrib import layers
import numpy as np
import datetime
import json
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
S = { # settings
'lc': 3, # layer count
'hu': 256, # num of hidden units
... | StarcoderdataPython |
9689301 | <reponame>djw8605/heroku-blog
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import app, db, models
from app.models import Post
# Initializing the manager
manager = Manager(app)
# Initialize Flask Migrate
migrate = Migrate(app, db)
@manager.command
def periodic():
fr... | StarcoderdataPython |
6498390 | <filename>ping-pong.py
from pygame import*
time=time.Clock()
FPS=60
finish=False
window=display.set_mode((700,500))
display.set_caption('Пинг-понг')
bg=transform.scale(image.load('faild.jpg'),(700,500))
speed_x=1
speed_y=1
class Gamesprite(sprite.Sprite):
def __init__(self, player_image, player_x, player_y, player_... | StarcoderdataPython |
1600252 | class Callback(object):
"""Base class for all utility callbacks and CallbackHandler."""
def on_train_begin(self): pass
def on_epoch_begin(self): pass
# =================================
def on_batch_begin(self): pass # add xb and yb to state_dict
def on_loss_end(self): pass
... | StarcoderdataPython |
213180 | <filename>atcoder/abc/b137.py
K, X = tuple(map(int, input().split()))
start = X - K + 1
end = X + K
print(*range(start, end))
| StarcoderdataPython |
3350189 | <filename>spot-health-checker.py
import pytz
import time
import boto3
import pickle
import datetime
import argparse
from pathlib import Path
### Spot Checker Mapping Data
region_ami = pickle.load(open('./region_ami_dict.pkl', 'rb')) # {x86/arm: {region: (ami-id, ami-info), ...}}
az_map_dict = pickle.load(open('./az_m... | StarcoderdataPython |
5169152 | import argparse
import os
import random
from util import www2fb, processed_text, clean_uri
# output 'cleanedFB.txt', 'names.trimmed.txt', 'transE_*.txt', 'entity2id.txt', 'relation2id.txt'
def get_fb_mids_set(cleanfile, fbsubset):
print('get all mids in the Freebase subset...')
lines_seen = set() # holds lin... | StarcoderdataPython |
9699249 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe import _
import prestashop_erpnext_connector
from prestashop_erpnext_connector.prestapi.prestapi import PrestaShopWebService,PrestaShopWebServiceDict,PrestaShopWebServiceError,PrestaShop... | StarcoderdataPython |
5157829 | from ._AuctionAck import *
from ._AuctionRequest import *
from ._Bid import *
from ._ScheduledTasks import *
from ._Task import *
from ._Winner import *
| StarcoderdataPython |
6551422 | <reponame>nachereshata/bets-cli<filename>src/bets/program_io/matches_output.py
import logging
from pathlib import Path
from typing import List
from tabulate import tabulate
from pandas import DataFrame
from bets.model.match import Match
_log = logging.getLogger(__name__)
def fmt_to_csv(matches: List[Match]) -> str... | StarcoderdataPython |
3218029 | <reponame>dedefer/MAILRU_IM_COMMAND_BOT
import enum
import logging
from logging import getLogger
from mailru_im_command_bot import BadArg, CommandBot, MessageEnv
logging.basicConfig(level=logging.INFO)
class Email(str):
@classmethod
def verbose_classname(cls) -> str:
return cls.__name__
@classm... | StarcoderdataPython |
4900127 | <filename>src/clep/sample_scoring/limma.py
# -*- coding: utf-8 -*-
"""Python wrapper for R-based Limma to perform single sample DE analysis."""
import sys
from typing import List
import click
import numpy as np
import pandas as pd
import rpy2.robjects as ro
from rpy2.rinterface_lib.embedded import RRuntimeError
from ... | StarcoderdataPython |
11308863 | """Common configuration elements for training imitation algorithms."""
import logging
from typing import Any, Mapping, Union
import sacred
from stable_baselines3.common import base_class, policies, torch_layers, vec_env
import imitation.util.networks
from imitation.data import rollout
from imitation.policies import ... | StarcoderdataPython |
6571699 | from __future__ import division
import numpy as np
from numpy.testing import assert_almost_equal
import pytest
from acoustics.power import lw_iso3746
@pytest.mark.parametrize("background_noise, expected", [
(79, 91.153934187),
(83, 90.187405234),
(88, 88.153934187),
])
def test_lw_iso3746(background_no... | StarcoderdataPython |
3503860 | <reponame>gugcz/devfest-rpg
__author__ = 'tivvit'
from google.appengine.ext import ndb
from google.appengine.ext.ndb import msgprop
from protorpc import messages
from backend.cdh_m import Leaderboard_m
class Leaderboard(ndb.Model):
leaderboard = msgprop.MessageProperty(Leaderboard_m) | StarcoderdataPython |
1739187 | <reponame>kaixiang1992/python-flask
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, DATETIME, func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship, backref
from datetime import datetime
# TODO: db_uri
# dialect+driver://username:p... | StarcoderdataPython |
6651553 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'RockValue.ui'
#
# Created by: PyQt5 UI code generator 5.15.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, Qt... | StarcoderdataPython |
8055623 | class Foo(object):
attr = 'baz'
__slots__ = [<warning descr="'attr' in __slots__ conflicts with a class variable">'attr'</warning>, 'bar']
Foo.attr = 'spam'
print(Foo.attr)
foo = Foo()
<warning descr="'Foo' object attribute 'attr' is read-only">foo.attr</warning> = 'spam'
print(foo.attr) | StarcoderdataPython |
11262208 | <reponame>silencehero/snorkel
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from builtins import *
import math
from numbskull.inference import FACTORS
from scipy import sparse
from snorkel.learning.gen_learning impor... | StarcoderdataPython |
168693 | import chess
import numpy as np
class State:
def __init__(self, board=None):
if board is None:
self.board = chess.Board()
else:
self.board = board
def serialize(self) -> np.ndarray:
"""
Convert board into matrix representation for use with numpy.
... | StarcoderdataPython |
11224457 | import os
from elasticsearch import Elasticsearch
from flask import Flask, render_template, request
client = ElasticSearch(
cloud_id = os.environ.get('CLOUD_ID'),
http_auth = (os.environ.get('ES_USER'), os.environ.get('ES_PASSWORD'))
)
app = Flask(__name__)
app.secret_key = os.urandom(16)
@app.route('/')
de... | StarcoderdataPython |
3476219 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'C:/Users/Zeke/Google Drive/dev/python/zeex/zeex/core/ui/sql/add_connection.ui'
#
# Created: Mon Nov 13 22:57:18 2017
# by: pyside-uic 0.2.15 running on PySide 1.2.2
#
# WARNING! All changes made in this file will be lost!
from PySide i... | StarcoderdataPython |
8041910 | <reponame>openforcefield/openff-interchange
"""
Test the behavior of the drivers.all module
"""
from distutils.spawn import find_executable
import pytest
from openff.interchange.drivers.all import get_all_energies
from openff.interchange.testing import _BaseTest
@pytest.mark.slow()
class TestDriversAll(_BaseTest):
... | StarcoderdataPython |
1799373 | <filename>test.py
#!/usr/bin/python
import unittest
import os
import json
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
from geekbench.spiders.geekbench import GeekbenchSpider
json_file = 'geekbench.json'
class TestGeekbench(unittest.TestCase):
"""
System tes... | StarcoderdataPython |
11360875 | <filename>anaf/sales/urls.py
"""
Sales module URLs
"""
from django.conf.urls import url, patterns
from anaf.sales import views
urlpatterns = patterns('anaf.sales.views',
url(r'^(\.(?P<response_format>\w+))?$', views.index, name='sales'),
url(r'^index(\.(?P<response_format... | StarcoderdataPython |
392445 | from datetime import datetime
def getTimestamp():
unformattedTime = datetime.now()
formattedTime = unformattedTime.strftime("%Y%m%d%H%M%S")
return formattedTime
| StarcoderdataPython |
18580 | <filename>homeworks/vecutil.py<gh_stars>1-10
# Copyright 2013 <NAME>
from vec import Vec
def list2vec(L):
"""Given a list L of field elements, return a Vec with domain {0...len(L)-1}
whose entry i is L[i]
>>> list2vec([10, 20, 30])
Vec({0, 1, 2},{0: 10, 1: 20, 2: 30})
"""
return Vec(set(range(... | StarcoderdataPython |
9612440 | #
#
# Takes two arguments, a map file, and a annovar input.
#
import argparse
snps = {}
def process_snps(map_file):
with open(map_file) as map_f:
for line in map_f:
line = line.split("\t")
snp_name = line[1]
snps[snp_name] = []
def process_annovar(annovar):
wit... | StarcoderdataPython |
51596 | <filename>PositionalList.py
class _DoubleLinkedBase:
class _Node:
__slots__ = '_element', '_prev', '_next'
def __init__(self, element, prev, next):
self._element = element
self._prev = prev
self._next = next
def __init__(self):
self._header = self._N... | StarcoderdataPython |
6526117 | from django.urls import path
from .views import PostsListView
urlpatterns = [
path('', PostsListView.as_view(), name='todo-home'), # views.home
]
| StarcoderdataPython |
1656028 | import typing
import asyncio
from datetime import datetime, timedelta
import discord
from discord.ext import commands
from nerdlandbot.translations.Translations import get_text as translate
from nerdlandbot.helpers.TranslationHelper import get_culture_from_context as culture
from nerdlandbot.helpers.channel import get... | StarcoderdataPython |
1992921 | <gh_stars>10-100
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import kaiming_init, normal_init
from mmdet.ops import ConvModule
from ..builder import build_loss
from ..registry import HEADS
@HEADS.register_module
class GridHead(nn.Module):
def... | StarcoderdataPython |
8088967 | <reponame>juestellab/msot-sinogram-denoising<gh_stars>1-10
import torch
def get_scheduler(optimizer, e):
if e.scheduler == 'step':
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, e.scheduler_step_size, e.scheduler_gamma)
elif e.scheduler == 'linear':
def lambda_rule(epoch):
... | StarcoderdataPython |
11286003 | <reponame>kevinyuan/pymtl3
"""
=============================================================================
arbiters_test.py
=============================================================================
This file contains unit tests for the arbiters collection models.
"""
from pymtl3 import *
from pymtl3.stdlib.test_u... | StarcoderdataPython |
6587963 | <filename>revolver/color.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, with_statement
from fabric.colors import red, green, yellow, blue, magenta, cyan, white
| StarcoderdataPython |
2130 | <filename>stickmanZ/__main__.py
from game.game_view import GameView
from game.menu_view import menu_view
from game import constants
import arcade
SCREEN_WIDTH = constants.SCREEN_WIDTH
SCREEN_HEIGHT = constants.SCREEN_HEIGHT
SCREEN_TITLE = constants.SCREEN_TITLE
window = arcade.Window(SCREEN_WIDTH, SCREEN_HEIGHT, SC... | StarcoderdataPython |
1609914 | <reponame>windfall-shogi/feature-annotation<filename>annotation/black_effect/ou.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sonnet as snt
import tensorflow as tf
from .ou_helper import get_short_effect
from ..direction import get_eight_directions, get_opposite_direction
__author__ = 'Yasuhiro'
__date__ =... | StarcoderdataPython |
237355 | import argparse
from experiment import Experiment
parser = argparse.ArgumentParser()
parser.add_argument("--data_dir", default="../data/", type=str, help="root directory all the data will be stored in")
parser.add_argument("--save_dir", default="../saved_models/", type=str, help="root directory model checkpoints wil... | StarcoderdataPython |
6621006 | #!/usr/bin/env python
""" test of psalg_ext.local_minimums, local_maximums, threshold_maximums, local_maximums_rank1_cross
"""
#----------
import sys
import psalg_ext as algos
import numpy as np
#----------
def test01(tname='1', NUMBER_OF_EVENTS=5, DO_PRINT=True) :
print('local extrema : %s' % ('minimums' if tnam... | StarcoderdataPython |
6658220 | <gh_stars>100-1000
import torch
from .base import BaseModule, BaseDurIAN
from .encoder import CBHG
from .alignment import AlignmentModule
from .decoder import Decoder
from .postnet import Postnet
from .duration import DurationModel
from .utils import get_mask_from_lengths
class BackboneModel(BaseModule):
"""
... | StarcoderdataPython |
12843885 | """
********************************************************************************
geometry
********************************************************************************
.. currentmodule:: compas_rhino.geometry
.. rst-class:: lead
Wrappers for Rhino objects that can be used to convert Rhino geometry and data to... | StarcoderdataPython |
1802456 | from .coco_eval import do_coco_evaluation as do_orig_coco_evaluation
from .coco_eval_wrapper import do_coco_evaluation as do_wrapped_coco_evaluation
from maskrcnn_benchmark.data.datasets import AbstractDataset, COCODataset
def coco_evaluation(
dataset,
predictions,
output_folder,
box_only,
iou_typ... | StarcoderdataPython |
8021431 | <gh_stars>1-10
import numpy as np
import cv2
# Load the Haar cascade files
face_cascade = cv2.CascadeClassifier(
'./haar_cascade_files/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(
'./haar_cascade_files/haarcascade_eye.xml')
nose_cascade = cv2.CascadeClassifier(
'./haar_casc... | StarcoderdataPython |
3403516 | from __future__ import print_function
from __future__ import division
from itertools import combinations
import numpy as np
import torch
from sklearn import metrics
from sklearn.cluster import KMeans
from scipy.spatial.distance import squareform, pdist, cdist
#import faiss
from tqdm import tqdm
import evaluation
i... | StarcoderdataPython |
206061 | <reponame>haddocking/haddock3
"""HADDOCK3 FCC clustering module"""
import logging
import os
from pathlib import Path
import toml
from fcc.scripts import calc_fcc_matrix, cluster_fcc
from haddock import FCC_path
from haddock.libs.libparallel import Scheduler
from haddock.libs.libsubprocess import Job
from haddock.mod... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.