id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
12845526 | <reponame>nlpming/tensorflow-DSMM
#!/usr/bin/env python
#encoding=utf-8
'''
@Time : 2020/10/25 22:28:30
@Author : zhiyang.zzy
@Contact : <EMAIL>
@Desc : 训练相似度模型
1. siamese network,分别使用 cosine、曼哈顿距离
2. triplet loss
'''
# here put the import lib
from model.bert_classifier import BertClassifier
import os
... | StarcoderdataPython |
176445 | <gh_stars>10-100
# -*- coding: utf-8 -*-
from .blockchainobject import BlockchainObject
from ..block import Block as SyncBlock, BlockHeader as SyncBlockHeader
from ..exceptions import BlockDoesNotExistsException
class Block(BlockchainObject, SyncBlock):
""" Read a single block from the chain
:param int b... | StarcoderdataPython |
3523977 | <reponame>badouralix/adventofcode-2018<filename>day-07/part-1/david.py
from tool.runners.python import SubmissionPy
from collections import defaultdict
from string import ascii_uppercase
import bisect
class DavidSubmission(SubmissionPy):
def run(self, s):
# :param s: input in string format
# :ret... | StarcoderdataPython |
6702079 | import json
from json import JSONDecodeError
from typing import List, Dict, Tuple
import requests
from config import Config
from flask_app.match_score import MatchPlayer, ScoreData
from flask_app.player import Player
from flask_app.schedule import schedule, Match
from flask_app.team import UserTeam
from flask_app.use... | StarcoderdataPython |
9642778 | # This script handles the creation of the PEP 376 .dist-info directory for a
# package.
#
# Copyright (c) 2018 Riverbank Computing Limited <<EMAIL>>
#
# This script is distributed under the terms of the GNU General Public License
# v3 as published by the Free Software Foundation.
#
# This script is supplied WITHOUT ANY... | StarcoderdataPython |
3216977 | r"""
Group algebras of root lattice realizations
"""
# ****************************************************************************
# Copyright (C) 2013 <NAME> <nthiery at users.sf.net>
# <NAME> <anne at math.ucdavis.edu>
# <NAME> <mshimo at vt.edu>
# ... | StarcoderdataPython |
92803 | <filename>Python_Core/ArithmeticExamApplication/arithmetic.py
from random import choice, randint
class MiniCalculator:
def __init__(self):
self.operations = {
"+": MiniCalculator.addition,
"-": MiniCalculator.subtraction,
"*": MiniCalculator.multiplication,
}
... | StarcoderdataPython |
257743 | # from zhihu_user_info.util.SpiderUtil import SpiderUtil
from zhihu_user_info.util.SaveUtil import SaveUtil
# from zhihu_user_info.util.Utils import Util
from zhihu_user_info.threadpool.ThreadPool import ThreadPool
import threading
# spider_util = SpiderUtil()
# save_util = SaveUtil()
#
# result_list = [1, 2, 3]
# sav... | StarcoderdataPython |
4972355 | import jax
import jax.numpy as jnp
# takes in a logit distribution, softmax and then sample
def softmax_sample(key, logits, _, temp=1):
return jax.random.categorical(key, logits/temp, -1).astype(jnp.uint32), None
def nucleaus_filter(logits, top_p=0.9, top_k=None):
sorted_logits = jnp.sort(logits)[:, ::-1] #... | StarcoderdataPython |
4940329 | import spacy
nlp = spacy.load("en_core_web_sm")
def extract_entities(text):
for entity in nlp(text).ents:
print("Entity: ", entity.text)
print("Entity Type: %s | %s" % (entity.label_, spacy.explain(entity.label_)))
print("Start Offset of the Entity: ", entity.start_char)
print("En... | StarcoderdataPython |
8050439 | """
evoke definition class for Data objects
schema syntax:
class Widget:
table='widgets' #optional table name - will default to the class name (lowercased). Can provide a database override eg 'mydb.widgets'
name=TAG #first attribute / column name....
number=INT,100,KEY #o... | StarcoderdataPython |
6652875 | <gh_stars>1-10
"""
Day 2 was also relatively straightforward, not much challenge up till now. The only stumbling block was that I first
did not read that the up and down in part 2 no longer changed the depth by themselves. Other than that, smooth sailing.
"""
from utils import Solution
from typing import Any
class D... | StarcoderdataPython |
4891914 | <filename>main/rest/image_file.py<gh_stars>10-100
from django.db import transaction
from django.http import Http404
from ..models import Media
from ..models import Resource
from ..models import safe_delete
from ..models import drop_media_from_resource
from ..schema import ImageFileListSchema
from ..schema import Image... | StarcoderdataPython |
6416853 | from dwim.utils import for_app
@for_app('brew', at_least=2)
def match(command):
return (command.script_parts[1] in ['uninstall', 'rm', 'remove']
and "brew uninstall --force" in command.stdout)
def get_new_command(command):
command.script_parts[1] = 'uninstall'
command.script_parts.insert(2, ... | StarcoderdataPython |
3323089 | <reponame>Optimist-Prime/QML-for-MNIST-classification
import sys
import pickle
import numpy as np
from ptrace import ptrace
from tqdm import tqdm
def generate_reduced(feature_data):
new_feature_data = []
for i in tqdm(range(len(feature_data))):
new_feature_data.append(
ptrace(
... | StarcoderdataPython |
194583 | # Copyright (c) 2011, <NAME> <<EMAIL>>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of condition... | StarcoderdataPython |
396632 | <reponame>giovp/SingleCellOpenProblems
from ....tools.decorators import method
from ....tools.utils import check_version
import numpy as np
@method(
method_name="NMF-reg",
paper_name="Slide-seq: A scalable technology for measuring genome-wide expression at high spatial resolution", # noqa: E501
paper_ur... | StarcoderdataPython |
3309364 | <reponame>SlimyMonkey/divePython<filename>roman/stage1/roman1.py
"""Convert to and from Roman numerals
This program is part of "Dive Into Python", a free Python book for
experienced programmers. Visit http://diveintopython.org/ for the
latest version.
"""
__author__ = "<NAME> (<EMAIL>)"
__version__ = "$Revision: 1.2... | StarcoderdataPython |
5179297 | <filename>build_graph/build_mdn.py<gh_stars>1-10
# Copyright 2019 <NAME>
#
# 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 ... | StarcoderdataPython |
6560005 | <reponame>delacruzsebastian-cpu/Examen-final-PROCESAMIENTO-DE-IMAGENES
import numpy as np
import cv2
from hough import *
from orientation_estimate import *
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.utils import shuffle
import os
#<NAME> <NAME>
class Bandera: #Crear cl... | StarcoderdataPython |
248611 | # Generated by Django 3.1 on 2020-09-11 07:25
import crm.models
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Person',
f... | StarcoderdataPython |
1721503 | import torch.nn as nn
from lib import common
ENV_ID = "RoboschoolHalfCheetah-v1"
GAMMA = 0.99
BATCH_SIZE = 256
LR_ACTOR = 0.0003
LR_CRITIC = 0.0003
REPLAY_SIZE = 1000000
REPLAY_INITIAL = 10000
TAU = 0.005
REWARD_STEPS = 1
STEPS_PER_EPOCH = 5000
ETA_INIT = 0.995
ETA_FINAL = 0.999
ETA_BASELINE_EPOCH = 100
ETA_AVG_SIZE =... | StarcoderdataPython |
1933403 | from typing import Optional, Union, List
from graphql.execution import execute_sync
from graphql.language import parse
from graphql.type import (
GraphQLBoolean,
GraphQLField,
GraphQLInterfaceType,
GraphQLList,
GraphQLObjectType,
GraphQLSchema,
GraphQLString,
GraphQLUnionType,
)
class... | StarcoderdataPython |
4827028 | <filename>guests/factory.py
import logging
from importlib import import_module
class Factory(object):
def __init__(self, cfg):
self.log = logging.getLogger("vo2.%s" % __name__)
self.cfg = cfg
def list_vms(self):
vms = []
try:
vms = self.cfg.get("job", "vms").split... | StarcoderdataPython |
50495 | <reponame>jpVm5jYYRE1VIKL/djangocms-bootstrap4<filename>djangocms_bootstrap4/contrib/bootstrap4_content/constants.py
from django.utils.translation import gettext_lazy as _
CODE_TYPE_CHOICES = (
('code', _('Inline code')),
('pre', _('Code block')),
('var', _('Variables')),
('kbd', _('User input')),
... | StarcoderdataPython |
9782308 | from faust_bootstrap.core.app import FaustApplication
class FaustAppTest(FaustApplication):
def get_unique_app_id(self):
return f"dummy-group"
def setup_topics(self):
...
def build_topology(self):
...
| StarcoderdataPython |
3507820 | <filename>kfunction_3Stage.py
#########################################################################################################################
# <NAME>
# The Ohio State University; Moody's Analytics
# Completely open source
# Functions necessary for 3 Stage Global/Local K-function estimation:
# clockwis... | StarcoderdataPython |
3342933 | """
This program is part of MOLDIS: The bigdata analytics platform. Accompanying manuscript
and the complementary web interface can be accessed at : https://moldis.tifrh.res.in/data/bodipy
Python Requirements:
numpy, scipy, scikit-learn, QML
System Requirements:
MOPAC, Obabel, write permission in running directory
Lice... | StarcoderdataPython |
3533612 | <filename>bloodon/tools/calendarutils.py
from calendar import monthrange
from itertools import groupby
from django.utils import formats
import datetime
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
from bloodon.alerts.models import Alert
from base64 import d... | StarcoderdataPython |
3474609 | <reponame>codeic/lpthw
# This line prints sentence
print "I will now count my chickens:"
# This line prints word, then does math
print "Hens", round(25 + 30 / 6)
# This line also prints word and then does some math
print "Roosters", round(100-25*3%4)
# This line prints sentence
print "Now I will count the eggs:"
# ... | StarcoderdataPython |
6561900 | # Copyright (C) 2022 viraelin
# License: MIT
from PyQt6.QtWidgets import QGraphicsItem
from PyQt6.QtGui import QUndoCommand
class PaintCommand(QUndoCommand):
def __init__(self, layer: QGraphicsItem, coords: list, text: str) -> None:
super().__init__()
self.layer = layer
self.coords = coo... | StarcoderdataPython |
1654589 | <gh_stars>0
import inspect
import traceback
import uvicorn
import json
from starlette.applications import Starlette
from starlette.endpoints import HTTPEndpoint
from starlette.responses import JSONResponse
app = Starlette()
@app.route('/{endpoint}/{uid}')
class DeviceEndpoint(HTTPEndpoint):
@staticmethod
as... | StarcoderdataPython |
6585262 | #!/usr/bin/env python2.7
#coding=utf-8
#author@alingse
import json
import sys
# set A,set B, give A - B
# do not need sorted, It use the memory
# all string should be keep as unicode
def get_id_from_A(line_data):
return line_data.strip()
#return json.loads(line_data).get('id')
#return json.loads(line_... | StarcoderdataPython |
1767217 | <reponame>Minres/PySysC
#
# Copyright (c) 2019 -2021 MINRES Technolgies GmbH
#
# SPDX-License-Identifier: Apache-2.0
#
'''
Created on 30.08.2021
@author: eyck
'''
from cppyy import gbl as cpp
class ScModule(cpp.scc.PyScModule):
'''
classdocs
'''
def __init__(self, name):
super().__init__... | StarcoderdataPython |
5036247 | print("Conversor de moedas (Dol; BTC; BAT)")
v = float(input("Insira o valor em R$ a ser convertido: "))
print(
f"""Este valor representa:\n{v*6.10:.2f} BAT\n{v*235940.41:.2f} BTC\n{v*5.63:.2f} Dól"""
)
print("*Cotação de: 07/01/2022 às 18:29")
| StarcoderdataPython |
6495747 | <filename>social_team/accounts/models.py
from django.conf import settings
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \
PermissionsMixin
from cropperjs.models import CropperImageField
from markdownx.models import MarkdownxField
class UserManager(BaseUser... | StarcoderdataPython |
196701 | <filename>tests/python_to_cpp/Shed Skin Examples/compile_all.py
import sys, platform, os
enopt = False
total = 0
ok = 0
for fname in os.listdir('.'):
if fname.endswith('.cpp'):
print(fname, end = '', flush = True)
if sys.platform == 'win32':
was_break = False
for version i... | StarcoderdataPython |
4953236 | from django.apps import AppConfig
class TheblogConfig(AppConfig):
name = 'theblog'
| StarcoderdataPython |
9608238 | #!/usr/bin/env python
import os
import sys
from glob import glob
input = sys.argv[1]
if not os.path.isdir(input):
print 'Error - Not a directory - Please provide a directory as input. Exiting...'
sys.exit()
else:
os.chdir(input)
tiff_check = glob('*.tiff')
dpx_check = glob('*.dpx')
if len(dpx... | StarcoderdataPython |
9607915 | from typing import *
from ..base import HPOBase
from ...utils import Metrics
from ....optim import BayesianOptimization
@HPOBase.register("bo")
class BayesianHPO(HPOBase):
@property
def is_sequential(self) -> bool:
return True
def _init_config(self, **kwargs):
self._bo_config = kwargs.ge... | StarcoderdataPython |
11380014 | from graph import canvas
from search import tools
def isValidCell(cell, visited, obstacles):
x, y = cell
if x < 0 or x >= canvas.WIDTH:
return False
if y < 0 or y >= canvas.HEIGHT:
return False
if cell in visited:
return False
for x, y in obstacles:
if cell[0] == x... | StarcoderdataPython |
5171577 | <reponame>deboradyankova/python_education
n = int(input())
lst_positive = []
lst_negative = []
for _ in range(n):
number = int(input())
if number >= 0:
lst_positive.append(number)
else:
lst_negative.append(number)
print(lst_positive)
print(lst_negative)
print(f'Count of positi... | StarcoderdataPython |
3544664 | # Copyright 2014-2015 MongoDB, Inc.
#
# 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 writin... | StarcoderdataPython |
3543648 | # Copyright (c) 2019 PaddlePaddle Authors. 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 appli... | StarcoderdataPython |
4969055 | from wtforms import Form, TextField, SelectField
from wtforms.validators import DataRequired
class QueryForm(Form):
search_query = TextField('', validators=[DataRequired()], render_kw={"placeholder": "Your query here"})
search_category = SelectField('Search for', choices=[('pa', 'Paper / Author'), ('p', 'Pape... | StarcoderdataPython |
9780204 | # -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
import cohesity_management_sdk.models.ad_object_meta_data
import cohesity_management_sdk.models.email_meta_data
import cohesity_management_sdk.models.file_version
import cohesity_management_sdk.models.universal_id
import cohesity_management_sdk.models.protection_s... | StarcoderdataPython |
1840842 | #!/usr/bin/env python3
import os, os.path
import shutil
import subprocess
SROOT = 'src'
DROOT = 'dist'
def main():
# setup
if not os.path.exists(DROOT):
os.mkdir(DROOT)
if os.path.exists(os.path.join(SROOT, '__javascript__')):
shutil.rmtree(os.path.join(SROOT, '__javascript__'))
# tr... | StarcoderdataPython |
1612682 | from django import forms
from django.utils.safestring import mark_safe
from markupfield.widgets import MarkupTextarea
from .models import Nomination
class NominationForm(forms.ModelForm):
class Meta:
model = Nomination
fields = (
"name",
"email",
"previous_boa... | StarcoderdataPython |
11215883 | <reponame>ghrecommender/ghrecommender-backend
from rest_framework import views
from rest_framework.response import Response
from rest_framework_extensions.cache.decorators import cache_response
from recommendations.serializers import RecommendationSerializer
from core.utils import UserKeyConstructor
from .utils impor... | StarcoderdataPython |
1918911 | <gh_stars>10-100
def no_more_commits_than_origin(project_folder, original_project_folder=None, *args, **kwargs):
if not original_project_folder:
return
if not project_folder.repo or not original_project_folder.repo:
return
# FIXME this check works incorrectly in case of
# new commit in... | StarcoderdataPython |
11397102 | import inspect
import os
import argparse
import black
from pathlib import Path
INDENT = " " * 4
GENERATED_COMMENT = "# Generated content DO NOT EDIT\n"
def do_indent(text: str, indent: str):
return text.replace("\n", f"\n{indent}")
def function(obj, indent, text_signature=None):
if text_signature is None:
... | StarcoderdataPython |
4907700 | import copy
import logging
from typing import TYPE_CHECKING
import naff.api.events as events
from naff.client.const import logger_name, MISSING
from ._template import EventMixinTemplate, Processor
from naff.models import GuildIntegration, Sticker, to_snowflake
from naff.api.events.discord import (
GuildEmojisUpda... | StarcoderdataPython |
3236996 | <filename>app/api/event_sub_topics.py
from flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship
from app.api.bootstrap import api
from app.api.custom_placeholders import CustomPlaceholder
from app.api.helpers.db import safe_query
from app.api.helpers.exceptions import ForbiddenException
from ap... | StarcoderdataPython |
4941204 | <reponame>LumaKernel/dotfiles
import os
from powerline_shell.utils import ThreadedSegment
definitions = {
'fish': {
'abbr': 'fi',
'color': 157,
},
'bash': {
'abbr': 'ba',
'color': 221,
},
}
class Segment(ThreadedSegment):
def add_to_powerline(self):
self.joi... | StarcoderdataPython |
1933814 | from flask import request
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import joinedload, subqueryload_all
from zeus import auth
from zeus.config import db
from zeus.models import Author, Build, Email, Repository, Source
from zeus.pubsub.utils import publish
from .base_repository import BaseRepositor... | StarcoderdataPython |
1912060 | <filename>RandomApps/python/pytohtml.py
def inputMatrix(m,n, vektori = False):
if vektori:
border = "border-right: 2px solid black; border-left: 2px solid black; border-top: none; border-bottom: none;"
else:
border = "border: none;"
tmp = ""
tmp+= """
<div class="conta... | StarcoderdataPython |
9640110 | <filename>Udacity/utils/utils.py
"Utils for python develoment"
# Author: <NAME>
# Start Date : 20th December 2014
import time
import numpy
def timed_call(func, *args):
"Call function with args, return time and result"
t0 = time.clock()
result = func(*args)
t1 = time.clock()
return t1 - t0, result
... | StarcoderdataPython |
8005767 | <reponame>flying-sausages/iommi
from django.urls import path
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from django.utils.translation import gettext
from django.views.decorators.csrf import csrf_exempt
from examples import (
example_adding_decorator,
example_links,
... | StarcoderdataPython |
6446718 | <gh_stars>0
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
class Device:
def __init__(self, pin, device_type):
self.pin = pin
self.type = device_type
def on(self):
GPIO.setup(self.pin, GPIO.OUT)
if self.type == "led":
GPIO.output(self.pin, G... | StarcoderdataPython |
3346248 | # encoding: utf-8
# Copyright 1999-2017 Alibaba Group Holding 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
#
# Unless required b... | StarcoderdataPython |
5002436 | <filename>setup.py
#!/usr/bin/env python
import os
from distutils.core import setup
import pubchempy
if os.path.exists('README.txt'):
long_description = open('README.txt').read()
else:
long_description = open('README.md').read()
setup(
name='PubChemPy',
version=pubchempy.__version__,
author=pub... | StarcoderdataPython |
1912181 | # This file was automatically generated by SWIG (http://www.swig.org).
# Version 1.3.40
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
# This file is compatible with both classic and new-style classes.
from sys import version_info
if version_info >= (... | StarcoderdataPython |
3442409 | import torch
import torch.nn as nn
# model
class net_PixelShuffle(nn.Module):
def __init__(self, upscale_factor):
super().__init__()
self.op = torch.nn.PixelShuffle(upscale_factor)
def forward(self, input):
return self.op(input)
_model_ = net_PixelShuffle(2)
# dummy input for onnx ... | StarcoderdataPython |
9634994 | import cv2
import numpy as np
from domestik import px
skala = px.jendela.skala
h, w = 90, 160
judul = 'sembarang'
skala(judul, [900,1600])
warna = np.random.randint(256, size=3)
dasar = np.zeros([h,w, 3]) + warna
dasar = dasar.astype(np.uint8)
cv2.imshow(judul, dasar)
cv2.displayStatusBar(judul, str(warna))
cv2.waitK... | StarcoderdataPython |
12807948 | <reponame>LightArrowsEXE/Encoding-Projects
from typing import Tuple, Union
import vapoursynth as vs
from lvsfunc.misc import source
from vardautomation import FileInfo, PresetBD, PresetFLAC, VPath
from project_module import encoder as enc
from project_module import flt
core = vs.core
# Sources
JP_BD = FileInfo(r'BD... | StarcoderdataPython |
11321251 | <gh_stars>100-1000
import wave
import pyaudio
class RecordAudio:
def __init__(self):
# 录音参数
self.chunk = 1024
self.format = pyaudio.paInt16
self.channels = 1
self.rate = 16000
# 打开录音
self.p = pyaudio.PyAudio()
self.stream = self.p.open(format=self.... | StarcoderdataPython |
5013878 | from datetime import datetime, timedelta
class ProgressLogger:
prev_print_at = datetime.now()
def log(self, prefix, count, total=None):
if self.prev_print_at > datetime.now() - timedelta(seconds=1):
return
print(
"{}... {:03.2f}{}".format(
prefix,
... | StarcoderdataPython |
5087920 | # coding=utf-8
# Copyright 2019 Deepmind Technologies Limited.
#
# 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 applic... | StarcoderdataPython |
1958602 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
main
~~~~~
the purpose of this code is to solve the knapsack problem.
the code will read the input (the items in the knapsack) and will hopefully
solve the problem (find the best fit to the restrictions) by using genetic algorithm
"""
import logging
import click
impo... | StarcoderdataPython |
3554085 | <reponame>Andrei-Dolgolev/mirror<filename>tests/test_populate.py
"""
Tests for mirror CLI
"""
import argparse
import unittest
import mirror.cli
class TestGenerateMirrorCLI(unittest.TestCase):
def setUp(self):
self.subcommand = 'test-subcommand'
def subcommand_populator(parser: argparse.ArgumentP... | StarcoderdataPython |
1886465 | <reponame>forensic-security/cybereason<gh_stars>1-10
# patch to cope with a bug in /rest/file-search/fetch-direct that
# returns two {'file-encoding': 'chunked'} headers
import re
from h11._abnf import field_name, field_value
from h11._util import bytesify, LocalProtocolError, validate
from h11._headers import Heade... | StarcoderdataPython |
3468930 | import finder_in_files
from colorama import Fore # pip install colorama
class Test:
def __init__(self):
self.settings_files = {
'txt': True,
'log': True,
'html': True,
'css': True,
'cpp': True,
'h': True,
'py': True,
... | StarcoderdataPython |
4838857 | from argparse import ArgumentParser
import shutil
from tensorboard.backend.event_processing.event_file_inspector import get_inspection_units, print_dict, get_dict_to_print
"""
Deletes all folders with small tensorboard run files
"""
parser = ArgumentParser('delete small runs')
parser.add_argument('--logdir', type=str... | StarcoderdataPython |
7955 | <filename>openfermioncirq/variational/ansatzes/swap_network_trotter_hubbard_test.py
# 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 |
3566916 | <gh_stars>0
#!/usr/bin/env python
import warnings
import os
import pickle
import datetime
import logging
from functools import partial
from multiprocessing import Pool
import jinja2
from tqdm import tqdm
import tables
import numpy as np
from astropy import table
from astropy import time, units as u
from mica.starchec... | StarcoderdataPython |
52171 | from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.pipeline import make_pipeline
import matplotlib.pyplot as plt
import numpy as np
import random
#=================================================... | StarcoderdataPython |
1951006 | <filename>PET_Library.py
__author__ = 'lpeng'
"""Penpan library
refering Mcmahon, 2013; Rotstayn, 2006; Li, 2013; Yang, 2012; Roderick, 2007"""
from pylab import *
class Data:
# Initialization
def __init__(self, INPUT, solar): #, npt):
# Define the incoming grid data variables
self.Tair = INPUT['tavg']
self... | StarcoderdataPython |
254058 | <gh_stars>0
import shutil
from pathlib import Path
def copy(src: Path, dest: Path):
"""Copy backup from `src` to `dest`.
Args:
src (Path): the source to copy from
dest (Path): the destination to copy to
Returns:
bool: True if successful
"""
shutil.copy(str(src), str(dest... | StarcoderdataPython |
6692634 | <filename>util.py<gh_stars>100-1000
import csv
try:
from urllib.request import urlretrieve
except ImportError:
from urllib import urlretrieve
class Util:
@staticmethod
def read_games(file):
""" Initializes game objects from csv """
games = [item for item in csv.DictReader(open(file))]
... | StarcoderdataPython |
3408969 | <reponame>shayweitzman/MyAutoBook<gh_stars>1-10
# Generated by Django 3.1.3 on 2021-01-08 00:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('book_catalog', '0028_auto_20210107_2204'),
('review', '0007_auto_20210107_1804'),
('authentic... | StarcoderdataPython |
3550109 | import logging
import pytest
import zenko_e2e.util as util
from ..fixtures import *
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(name)s %(levelname)s: %(message)s',
datefmt='%S')
@pytest.mark.conformance
def test_aws_storage(aws_loc_bucket, aws_target_bucket... | StarcoderdataPython |
4978792 |
from bottle import *
import db
import os
port = os.environ.get("PORT", 17995)
@route('<filename>')
def server_static(filename):
return static_file(filename, root="/files")
@get('/')
def index():
return template("index")
@get('/sign_up')
def s_u():
return template("sign-up")
@post('/... | StarcoderdataPython |
4863823 | <reponame>chenjiancan/pantyhose<gh_stars>1-10
# coding=utf-8
"""
remote server
Run a TCP server to proxy tcp traffic from LOCAL SERVER.
Assume that the first few bytes are `header` that carrying target address info and parse the target from it.
Once the target server was known and connection established... | StarcoderdataPython |
9548 | description = 'Mezei spin flipper using TTI power supply'
group = 'optional'
tango_base = 'tango://miractrl.mira.frm2:10000/mira/'
devices = dict(
dct1 = device('nicos.devices.entangle.PowerSupply',
description = 'current in first channel of supply (flipper current)',
tangodevice = tango_base + 't... | StarcoderdataPython |
8175967 | import os, json
from cloudant.client import Cloudant
from cloudant.error import CloudantException
from cloudant.result import Result, ResultByKey
class DatabaseAccess():
def __init__(self):
vcap_cloudant = json.loads(os.environ['VCAP_SERVICES'])['cloudantNoSQLDB'][0]['credentials']
self.cloudant = Cloudan... | StarcoderdataPython |
316474 | <gh_stars>10-100
import os
import sys
import unittest
import numpy as np
ROOT_DIR = os.path.dirname(os.getcwd())
if ROOT_DIR not in sys.path: sys.path.append(ROOT_DIR)
import DeepSparseCoding.utils.loaders as loaders
import DeepSparseCoding.utils.dataset_utils as datasets
import DeepSparseCoding.utils.run_utils as r... | StarcoderdataPython |
6679427 | <reponame>ZhuoZhuoCrayon/bk-sops
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2020 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you m... | StarcoderdataPython |
6458328 | <filename>nsdperfTool.py
#!/usr/bin/python
import os
import sys
import time
import getopt
import json
import math
import re
import threading
import subprocess
try:
raw_input # Python 2
PYTHON3 = False
except NameError: # Python 3
raw_input = input
PYTHON3 = True
# Global variables with default v... | StarcoderdataPython |
394051 | <reponame>Gornak40/sicily<gh_stars>0
from engine import *
from random import choice, randrange
from results import *
take = lambda arr: arr.pop(randrange(len(arr)))
redCards = CARDS.copy()
blackCards = CARDS.copy()
# traitors turn
redTraitor = take(redCards)
blackTraitor = take(blackCards)
redCards.append(... | StarcoderdataPython |
9717752 | print('-=' * 10, '<NAME>', '-=' * 10)
preco = float(input('Preço das Compras: R$ '))
print('''[1] á vista Dinheiro/cheque
[2] á vista cartão \n[3] 2x no cartão \n[4] 3x no cartão.''')
escolha = int(input('Qual é a opção: '))
if escolha == 1:
valor = preco - (preco * 0.1)
print(f'O valor da sua compra é {preco... | StarcoderdataPython |
5141909 | '''
An example of solving global optimization problem
with guaranteed precision |f-f*| < fTol
'''
from numpy import zeros
from FuncDesigner import *
from openopt import *
a, b, c = oovars(3) # create 3 variables
d = oovars(4) # create 4 variables in a single vector
# some oofuns
f1 = cos(5*a) + 0.2*(b-0.2)**2 + exp(... | StarcoderdataPython |
8051927 | <reponame>HKBU-HPML/gtopkssgd
# -*- coding: utf-8 -*-
from __future__ import print_function
def update_fontsize(ax, fontsize=12.):
for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
ax.get_xticklabels() + ax.get_yticklabels()):
item.set_fontsize(fontsize)
def au... | StarcoderdataPython |
5092075 | # Copyright 2017-present Open Networking Foundation
#
# 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 agr... | StarcoderdataPython |
12810803 | """Tests for the once bitten strategy."""
import random
import axelrod
from .test_player import TestPlayer
C, D = axelrod.Action.C, axelrod.Action.D
class TestOnceBitten(TestPlayer):
name = "<NAME>"
player = axelrod.OnceBitten
expected_classifier = {
"memory_depth": 12,
"stochastic": ... | StarcoderdataPython |
4278 | <filename>Evaluation/batch_detection.py
'''
Autor: <NAME>
Start data: 15th May 2016
purpose: of this file is read frame level predictions and process them to produce a label per video
'''
from sklearn.svm import LinearSVC
from sklearn.ensemble import RandomForestClassifier
import numpy as np
import pickle
import os
im... | StarcoderdataPython |
6509040 | <reponame>tencentcloudapi-test/tencentcloud-cli
# -*- coding: utf-8 -*-
import os
import sys
import six
import json
import tccli.options_define as OptionsDefine
import tccli.format_output as FormatOutput
from tccli import __version__
from tccli.utils import Utils
from tccli.exceptions import ConfigurationError, ClientE... | StarcoderdataPython |
4864285 | <gh_stars>1-10
"""This file contains functionality for sending Halo data into SQS."""
from haloevents import HaloEvents
from haloscans import HaloScans
from utility import Utility
import boto3
import json
class Sender(object):
"""Initialize with an instance of ``halosqs.ConfigHelper``."""
def __init__(self, c... | StarcoderdataPython |
3573492 | <filename>MaoCuHuiSpider/bsdemo.py
# coding=utf-8
"""
bs4 测试:看bs能否同时解析多个HTML
测试结果:只能解析一个HTML DOM树
"""
from bs4 import BeautifulSoup
html = """
<html>
<body>
<div class="title">标题1</div>
<div class="title">标题2</div>
</body>
</html>
<html>
<body>
<div class="title">标题3</div>
... | StarcoderdataPython |
1682556 | print("Hello, Python!!")
A = 23
B = "Python Bangladesh!!"
print(A)
print(B)
print(A,B)
# this is python singel line Comment
"""
This is a comment
written in
more than just one line
"""
#if you run this file with command Prompt type "python Syntax.py"
| StarcoderdataPython |
4884900 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'MiracleWong'
try:
f = open('/Users/miraclewong/test.txt', 'r')
print(f.read())
finally:
if f:
f.close()
with open('/Users/miraclewong/test.txt', 'r') as f:
for line in f.readlines():
print(line.strip())
# 读取非UTF-8编码
# f = ope... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.