id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1713271 | # Copyright (c) 2020, Oracle and/or its affiliates.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2.0,
# as published by the Free Software Foundation.
#
# This program is also distributed with certain software (including
# but no... | StarcoderdataPython |
3266709 | from .llcp import LLCP
from .sample import NextReaction, NextReactionRecord, FirstReaction
from .runner import RunnerFSM
from .distributions import ExponentialDistribution, WeibullDistribution
from .distributions import GammaDistribution, UniformDistribution
from .distributions import PiecewiseLinearDistribution, Piece... | StarcoderdataPython |
1659634 | ###################################
# DRH Health - Password generator #
# Created by <NAME> - IT #
###################################
# Imports
import random, array, webbrowser
import PySimpleGUI as sg
# PySimpleGUI theme
#sg.theme('DarkGrey12')
# Create password pattern
def create_password(pass_len... | StarcoderdataPython |
1695598 | from .exchangeability import exch_test
from .goodness_of_fit import gof_copula
from .radial_symmetry import rad_sym_test
| StarcoderdataPython |
1726407 | <reponame>Pysics/Algorithm
from __future__ import annotations
import copy
import networkx
def kahn_algorithm(graph: networkx.DiGraph) -> list:
_graph = copy.deepcopy(graph)
sequence = []
vertices = [vertex for vertex in _graph.nodes if _graph.in_degree(vertex) == 0]
while len(vertices) > 0:
ve... | StarcoderdataPython |
1784592 | from setuptools import setup, find_packages
setup(
name='simple_pytimer',
version='0.0.6',
license='',
packages=find_packages()
)
| StarcoderdataPython |
90774 | <gh_stars>0
from datetime import datetime, timedelta
import os
import uuid
from django.test import TestCase
from mock import MagicMock
from couchdbkit import RequestFailed
from casexml.apps.case.mock import CaseBlock
from casexml.apps.case.xml import V2
from corehq.apps.hqcase.utils import submit_case_blocks
from coreh... | StarcoderdataPython |
3220744 | <reponame>zhebrak/beatle
import aiohttp
import argparse
import asyncio
import functools
import json
import hmac
import logging
import pytz
import raftos
import time
from configparser import ConfigParser, NoSectionError, NoOptionError
from datetime import datetime, timedelta
from logging.handlers import SysLogHandler
... | StarcoderdataPython |
23058 | # Generated by Django 3.0.2 on 2020-01-31 20:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('collections', '0002_auto_20200109_1348'),
]
operations = [
migrations.AlterField(
model_name='collection',
name='com... | StarcoderdataPython |
38796 | <filename>ecosante/newsletter/tasks/import_in_sb.py
from flask import current_app
from datetime import datetime
from uuid import uuid4
import os
from flask.helpers import url_for
import sib_api_v3_sdk
from sib_api_v3_sdk.rest import ApiException
from ecosante.newsletter.models import Newsletter, NewsletterDB, Inscripti... | StarcoderdataPython |
3328005 | <filename>tests/captcha/test_widgets.py<gh_stars>10-100
from unittest import TestCase
from django.utils.safestring import SafeData
from antispam.captcha.widgets import ReCAPTCHA, InvisibleReCAPTCHA
class ReCAPTCHATests(TestCase):
def setUp(self):
self.widget = ReCAPTCHA(sitekey='mysitekey')
def tes... | StarcoderdataPython |
113940 | from __future__ import absolute_import, division, print_function
from dxtbx_format_image_ext import * # noqa: F403
__all__ = ( # noqa: F405
"CBFFastImageListReader",
"CBFFastReader",
"CBFImageListReader",
"CBFReader",
"HDF5Reader",
"ImageBool",
"ImageBuffer",
"ImageDouble",
"Imag... | StarcoderdataPython |
193737 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import hr
from . import res_config_settings
from . import mail_alias
from . import mail_channel
from . import res_partner
from . import res_users
| StarcoderdataPython |
71523 | #Module Import
from config import *
try:
conn = psycopg2.connect(
host="postgres",
database="production",
user="postgres1",
password="<PASSWORD>")
cur = conn.cursor()
except Exception as e:
print('Not Connected... | StarcoderdataPython |
3317113 | from __future__ import print_function
from __future__ import division
import findcaffe
import caffe
import os, argparse
import os.path as osp
import numpy as np
import scipy.ndimage as nd
import pylab, png, pickle
from shutil import copyfile
from ipdb import set_trace
import matplotlib.pyplot as plt
plt.switch_backe... | StarcoderdataPython |
1782620 | from ipyannotations import base
from unittest.mock import MagicMock
import ipywidgets
import pytest
ENTER_KEYUP = {"type": "keyup", "key": "Enter"}
ENTER_KEYDOWN = {"type": "keydown", "key": "Enter"}
BACKSPACE_KEYDOWN = {"type": "keyup", "key": "Backspace"}
class TestWidget(base.LabellingWidgetMixin, ipywidgets.VBo... | StarcoderdataPython |
1757110 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2017-2019 Met Office.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions a... | StarcoderdataPython |
3261501 | from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
class Pagination:
def __init__(self, objects, amount):
self.paginator = Paginator(objects, amount)
def items_for_page(self, page):
try:
items = self.paginator.page(page)
except PageNotAnInteger:
... | StarcoderdataPython |
1621407 | <reponame>DQiaole/ZITS
import math
import os
import time
import cv2
import numpy as np
import torch
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data.dataloader import DataLoader
from torch.utils.data.distributed import DistributedSampler
from tqdm import tqdm
try:
from apex impor... | StarcoderdataPython |
3309033 | from stockpricer.model import Pricer | StarcoderdataPython |
20451 | <reponame>major-hub/soil_app
from rest_framework import serializers
from user.models import User
from main.exceptions.user_exceptions import UserException
user_exception = UserException
class UserRegisterSerializer(serializers.ModelSerializer):
password_confirmation = serializers.CharField(max_length=128)
... | StarcoderdataPython |
4835941 | <reponame>byanofsky/simple-blog
from google.appengine.datastore.datastore_query import Cursor
from handlers.basehandler import BaseHandler
from models.post import Post
class FrontPageHandler(BaseHandler):
def get(self):
# Constant for how many posts to display per page
POSTS_PER_PAGE = 10
... | StarcoderdataPython |
4840542 | import numpy as np
#简单数据集上应用adaBoosting
def loadSimpData():
'''
创建简单数据集
'''
dataMat = np.matrix([[1., 2.1],
[2., 1.1],
[1.3, 1 ],
[1. , 1.],
[2. , 1.]])
classLabels = [1.0, 1.0, -1.0, -1.0, 1.0]
return dataMat, classLabels
def stumpClassify(dataMatrix, dimen, threshVal... | StarcoderdataPython |
1634697 | <reponame>Melca-G/Aeolus
from pyrevit.framework import List
from pyrevit import revit, DB
import clr
clr.AddReference('RevitAPI')
clr.AddReference('RevitAPIUI')
# clr.AddReference("System.Windows.Form")
from Autodesk.Revit.DB import FilteredElementCollector, FilteredWorksetCollector, RevitLinkType,BuiltInParameter,\
... | StarcoderdataPython |
1642601 | <reponame>smoosavioon/saeedconnect4<filename>agents/agent_minimax/minimax.py
import numpy as np
from agents.common import PlayerAction, BoardPiece, SavedState, GenMove, GameState, connected_four, PLAYER1, PLAYER2, apply_player_action, check_end_state
import math
from typing import Optional, Callable, Tuple
def evalua... | StarcoderdataPython |
1699634 | <reponame>hanaecarrie/pisap
##########################################################################
# XXX - Copyright (C) XXX, 2017
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.htm... | StarcoderdataPython |
76365 | EXPECTED_SECRETS = [
"EQ_SERVER_SIDE_STORAGE_USER_ID_SALT",
"EQ_SERVER_SIDE_STORAGE_USER_IK_SALT",
"EQ_SERVER_SIDE_STORAGE_ENCRYPTION_USER_PEPPER",
"EQ_SECRET_KEY",
"EQ_RABBITMQ_USERNAME",
"EQ_RABBITMQ_PASSWORD",
]
def validate_required_secrets(secrets):
for required_secret in EXPECTED_SEC... | StarcoderdataPython |
190193 | <gh_stars>10-100
from numba import jit
import cv2
import numpy as np
import random
__all__ = ['coco2yolo', 'yolo2coco', 'voc2coco', 'coco2voc', 'yolo2voc', 'voc2yolo',
'bbox_iou', 'draw_bboxes', 'load_image']
@jit(nopython=True)
def voc2yolo(bboxes, height=720, width=1280):
"""
voc => [x1, y1, x2,... | StarcoderdataPython |
1706066 | #Built-in imports
import sys
# External imports
import pandas as pd
def calculate_demographic_data(print_data=True):
def round_one(x):
return float(round(x,1))
# Read data from file
df = pd.read_csv("adult.data.csv")
# How many of each race are represented in this dataset? This should be a P... | StarcoderdataPython |
133304 | #!/usr/bin/env python3
# ****************************************************************************
# Copyright 2019 The Apollo 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... | StarcoderdataPython |
1696499 | # -*- coding: utf-8 -*-
"""User models."""
import datetime as dt
from palette.database import Column, Model, SurrogatePK, db, reference_col, relationship
class Item(SurrogatePK, Model):
"""An item to be created by a user."""
__tablename__ = 'items'
name = Column(db.String(80), nullable=False)
descri... | StarcoderdataPython |
121184 | <gh_stars>0
import pickle
import os
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import balanced_accuracy_score
from s... | StarcoderdataPython |
1667810 | <gh_stars>0
import setuptools
setuptools.setup(
version="0.0.1",
install_requires=[
'wallstreet==0.3',
'forex-python==1.5'
],
description="Wall street cli",
packages=setuptools.find_packages(),
classifiers=[
"Programming Language :: Python :: 3",
"License ... | StarcoderdataPython |
3378494 | <reponame>PySilentSubstitution/silent-sub
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 3 11:00:15 2021
@author: jtm
"""
| StarcoderdataPython |
49696 | <reponame>halilkocaerkek/GitHub-amazon-sagemaker-stock-prediction-alphavantage
import pandas as pd
import matplotlib.pyplot as plt
from enum import Enum
Adjusted = Enum('Adjusted', 'true false')
Interval = Enum('Interval', '_1min _5min _15min _30min _60min')
OutputSize = Enum('outputsize', 'compact full')
DataType ... | StarcoderdataPython |
139357 | import simalign
from tqdm import tqdm
from simalign import SentenceAligner
def parse_file2lines(filename):
lines=[]
with open(filename) as f:
lines = f.readlines()
lines = [x.strip() for x in lines]
return lines
def align_simaligner(infile_src, infile_tgt, outfile, langs):
moden = 'iter... | StarcoderdataPython |
1762995 | """Entry point"""
from src.view import viewfactory as vf
def main():
"""simple game loop to link a view with our model logic"""
view = vf.factory_create()
view.init()
while 1:
view.handle_events()
view.update()
view.display()
view.quit()
if __name__ == '__main__':
main(... | StarcoderdataPython |
3277028 | import os
import sys
import praw
import spacy
nlp = spacy.load('en_core_web_sm',disable=['ner','textcat'])
import nltk
from nltk.tokenize import word_tokenize
import glob
import pandas as pd
import re
from datetime import datetime
import threading
dev_mode = False
def fix_path(name):
if dev_mode == True:
retur... | StarcoderdataPython |
62533 | <gh_stars>10-100
#!/usr/bin/env python3
# Copyright 2004-present Facebook. All Rights Reserved.
import collections
import copy
from typing import Dict
def deep_update(dst: Dict, src: Dict, join_lists: bool = False) -> None:
"""Perform an in-place deep merge of ``src`` into ``dst``.
Args:
dst: The de... | StarcoderdataPython |
1791141 | import autogp
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
# Generate synthetic data.
N_all = 200
N = 50
inputs = 5 * np.linspace(0, 1, num=N_all)[:, np.newaxis]
outputs = np.sin(inputs)
# selects training and test
idx = np.arange(N_all)
np.random.shuffle(idx)
xtrain = inputs[idx[:N]]
yt... | StarcoderdataPython |
3309721 | <filename>Main.py
from ursina import *
dissolve=Shader(language=Shader.GLSL,fragment="""
#version 400
uniform sampler2D p3d_Texture0;
uniform sampler2D noiseTex;
uniform float threshold;
in vec2 uv;
out vec4 color;
void main(){
float noiseVal=texture(noiseTex,uv).x;
if(noiseVal>=threshold){
color=... | StarcoderdataPython |
3394502 | <filename>src/GIS/mammals_distribution.py
import csv
import tqdm
import os
import subprocess
import tqdm
def readFile_index():
filename_list = []
with open('mammal/akernel_density.csv', newline='') as csvfile:
csvfile = csv.reader(csvfile, delimiter=',', quotechar='"')
for row in csvfile:
if (len(row ) > ... | StarcoderdataPython |
3201148 | <gh_stars>1-10
GIT_SUBDIR = "privacy" # subdir in .git used for storing state
| StarcoderdataPython |
3347821 | <gh_stars>0
from factory import Faker, LazyAttribute, Maybe, SubFactory, lazy_attribute
from ..core.factories import DjangoModelFactory
from . import models
AUTO_QUESTION_TYPES = [
t
for t in models.Question.TYPE_CHOICES
if t
not in [
models.Question.TYPE_STATIC,
models.Question.TYPE_F... | StarcoderdataPython |
3210412 | <filename>Boot2Root/vulnhub/Trollcave-v1-2/scripts/user-hint-enum.py
import requests
import re
def GetUserByID(id):
response = (requests.get('http://192.168.1.30/users/' + str(id)).text).strip()
# Match <a href="/send_pm?recipient_name=King">PM</a>
username = re.search('recipient_name=(.*?)"', response).group(1)
r... | StarcoderdataPython |
1756896 | from django.urls import path
from . import views
urlpatterns = [
path('', views.Index.as_view(), name="index"),
# <pk>にPostのIDを渡すと表示される。
path('detail/<pk>/', views.Detail.as_view(), name="detail"), #ここのnameはURLを変数として用いるときの変数名になる <pk>というのはidに対応
path('create/', views.Create.as_view(), name='create'),
... | StarcoderdataPython |
3320963 | import os
import yaml
from .alerts import Alert
def contents_of_file(filename):
open_file = open(filename)
contents = open_file.read()
open_file.close()
return contents
def get_config(path):
return Config(path)
class Config(object):
def __init__(self, path):
alert_yml = contents_... | StarcoderdataPython |
194332 | # Image augmentation with ImageDataGenerator
# Steps
# 1. Prepare images dataset
# 2. create ImageDataGenerator
# 3. Create iterators flow() or flow_from_directory(...)
# 4. Fit
# Horizontal shift image augmentation
from PIL import Image
from numpy import expand_dims
from keras.preprocessing.image import load_img, ... | StarcoderdataPython |
84462 | print(3 // 7)
| StarcoderdataPython |
1787093 | <gh_stars>1-10
import collections
import time
import ocs
from ocs import site_config
def _get_op(op_type, name, encoded, client):
"""Factory for generating matched operations. This will make sure
op.start's docstring is the docstring of the operation.
Parameters:
op_type (str): Operation type, e... | StarcoderdataPython |
145748 | <reponame>Mitul-Joby/Semester-1-Python-Lab
def Length(L):
C = 0
for _ in L:
C+=1
return C
N = int(input('\nEnter number of elements in list to be entered: '))
L = []
for i in range(0,N):
L.append(input('Enter an element: '))
print('\nLength of list:',Length(L)) | StarcoderdataPython |
1774917 | # Semana 7
# Exercício 1
# <NAME>
# Escreva um programa que recebe como entradas dois números inteiros correspondentes à largura e à altura de um retângulo;
# O programa deve imprimir uma cadeira de caracteres que represente o retângulo informado com caracteres "#" na saída.
# Dica: a função print pode receber um parâ... | StarcoderdataPython |
33754 | <filename>src/models/predict_text_model.py
from ast import literal_eval
from performance_metrics import get_performance_metrics
from tensorflow.keras.models import load_model
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1' # Ignore tf info messages
import pandas as pd
if __name__ == "__main__":
TASK = "hum... | StarcoderdataPython |
66333 | import random
from typing import Any, Dict, List, Optional, Type
from mathy_core.expressions import MathExpression
from mathy_core.problems import get_rand_term_templates, mathy_term_string
from mathy_core.rule import BaseRule
from mathy_core.rules import (
AssociativeSwapRule,
CommutativeSwapRule,
Constan... | StarcoderdataPython |
3232297 | from FileSystemItem import FileSystemItem
class File(FileSystemItem):
def __init__(self, size):
self.size = size
def get_size(self):
return self.size
| StarcoderdataPython |
82628 | <filename>scripts/check_enumerative_guesses.py<gh_stars>0
#!/usr/bin/python
import os
import subprocess
import sys
import time
import re
import itertools
import json
num_instrs = [1, 2, 3]
files = ['enum0.opt', 'enum1.opt']
dataflows = ['false']
configs = itertools.product(num_instrs, files, dataflows)
# 0 - num-ins... | StarcoderdataPython |
3211951 | from model.Bacteria import Bacteria
class Anaerobs(Bacteria):
def __init__(self):
self.metabolismType = "Anaerob"
| StarcoderdataPython |
1708782 | <filename>majora2/migrations/0075_auto_20200505_1806.py
# Generated by Django 2.2.10 on 2020-05-05 18:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('majora2', '0074_temporarymajoraartifactmetric_thresholdcycle_temporarymajoraartifactmetricrecord_tem... | StarcoderdataPython |
1794213 | #!/usr/bin/env python
# Update the total number of annotations and experiments each term appears in
'''Update the total number of annotations and experiments each term appears in
'''
import sys
import argparse
import psycopg2
import psycopg2.extras
import setproctitle
from collections import defaultdict
from dbbac... | StarcoderdataPython |
3201456 | <filename>single-led.py
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(18,GPIO.OUT)
print "LED On"
GPIO.output(18,GPIO.HIGH)
time.sleep(1)
print "LED Off"
GPIO.output(18,GPIO.LOW)
| StarcoderdataPython |
1751654 | import keras.losses as kloss
import concise.losses as closs
from concise.losses import MASK_VALUE
import numpy as np
import keras.backend as K
import keras.layers as kl
from keras.models import Model, load_model
from keras.utils.generic_utils import deserialize_keras_object, serialize_keras_object, get_custom_objects
... | StarcoderdataPython |
46444 | <reponame>gnubyte/publicServerAutomator<gh_stars>0
# @Author: <NAME>
# @Date 4-13-2018
# ----------------
import server
dockerInstructions = [
"apt-get update -y",
"apt-get install apt-transport-https -y",
"apt-get install software-properties-common -y",
"apt-get install curl -y",
"apt-get insta... | StarcoderdataPython |
1705329 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import sys
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
FLAGS = None
def main(_):
mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)
... | StarcoderdataPython |
143935 | <reponame>bopopescu/classic_diff_geom<filename>src/sage/schemes/elliptic_curves/weierstrass_morphism.py
r"""
Isomorphisms between Weierstrass models of elliptic curves
AUTHORS:
- <NAME> (2007): initial version
- <NAME> (Jan 2008): isomorphisms, automorphisms and twists
in all characteristics
"""
#*****************... | StarcoderdataPython |
3391101 | # Generated by Django 3.1.2 on 2020-11-04 01:45
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('matchus', '0011_auto_20201104_0133'),
]
operations = [
migrations.RenameField(
model_name='chat',
old_name='sent',
... | StarcoderdataPython |
3317086 | <reponame>yujmo/python<gh_stars>0
def gen():
yield from subgen()
def subgen():
while True:
x = yield
yield x + 1
def main():
g = gen()
next(g)
retval = g.send(1)
print(retval)
g.throw(StopIteration)
main()
| StarcoderdataPython |
4828578 | #generate an expander graph (into a CSV file for omnetpp template)
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import os
path = r".\topologies\exp_CSV"
os.chdir(path)
n = 10 #Number of nodes
rep = 1 #number of files (always > 0)
save = False #to save the output as a SVG file
... | StarcoderdataPython |
102036 | """implements required text elements for the app"""
APP_NAME = "OSCAR"
WELCOME = "Welcome to " + APP_NAME
CREATE_PROJECT = {
'main': "Create ...",
'sub': "New " + APP_NAME + " project"
}
OPEN_PROJECT = {
'main': "Open ...",
'sub': "Existing " + APP_NAME + " project"
}
SECTIONS = {
'over': "Overvi... | StarcoderdataPython |
3283595 | <reponame>rebryk/kaggle
from pathlib import Path
from typing import Union
import cv2
import numpy as np
def load_mask(path: Union[str, Path]) -> np.array:
"""
Read grayscale mask from the disk.
:param path: path to a local file on disk
:return: image as a NumPy array
"""
mask = cv2.imread(s... | StarcoderdataPython |
1711077 | import math
input_numbers = []
years = 0
init_deposit, percent, target = map(str, input().split())
init_deposit, percent, target = int(init_deposit), int(percent), int(target)
# for i in range(3):
# input_numbers.append(int(input()))
deposit = init_deposit
while deposit < target:
# deposit += init_deposit... | StarcoderdataPython |
1618041 | <reponame>willthefrog/Paddle<filename>python/paddle/fluid/contrib/utils/hdfs_utils.py
# Copyright (c) 2018 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 Li... | StarcoderdataPython |
4801516 | #does not work
import numpy as np
import math
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Layer,Dense, Activation
import tensorflow.keras as keras# as k
import tensorflow as t
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import Adam,SGD
from tensorf... | StarcoderdataPython |
3333979 | from pmaf.pipe.specs._metakit import SpecificationCompositeMetabase,SpecificationBackboneMetabase
from pmaf.pipe.specs._base import SpecificationBase
class SpecificationCompositeBase(SpecificationBase,SpecificationCompositeMetabase):
""""""
def __init__(self, _specs,_steps):
if not all([isinstance(spec... | StarcoderdataPython |
3328326 | <filename>aws/production_experiment/preprocess/run_processing_job.py
"""
runs script train_val_test_split on an ec2 instance as a sagemaker processing job
"""
from sagemaker.processing import ScriptProcessor, ProcessingInput, ProcessingOutput
import sagemaker
import boto3
## locations and vars
BUCKET = sagemaker.Sessio... | StarcoderdataPython |
3292846 | """
重点代码 !!
练习4: 假设在当前文件夹下有一个图片timg.jfif
请编写一个函数,将该文件名传入,通过执行函数将其
复制一份到 主目录下
注意: 考虑可能文件比较大,不允许一次性读取
逻辑提示: 边从原来的文件读取内容,再将内容写入新文件
"""
def copy(filename):
"""
:param filename: 要拷贝的文件
"""
fr = open(filename, 'rb') # 原文件
fw = open("/home/tarena/" + filename, 'wb')
# 边读边写
while True:
... | StarcoderdataPython |
3333272 | # Setting up Chatterbot
import os
import json
import random
import dateutil.parser
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
# Train the bot
english_bot = ChatBot("English Bot",
storage_adapter="chatterbot.storage.SQLStorageAdapter",
databas... | StarcoderdataPython |
49347 | <gh_stars>1-10
#!/usr/bin/python
#
# Copyright 2010 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
#
# Un... | StarcoderdataPython |
1788788 | <gh_stars>0
"""
This script adds a missing "duration" field for every anime in the list retrieved via official myanimelist export api(https://myanimelist.net/panel.php?go=export)
"""
import sys
from typing import Optional
import xml.etree.ElementTree as ET
from mal import Anime
def get_duration(amime_id: int) -> Opt... | StarcoderdataPython |
162431 | #!/usr/bin/env bash
# This script trims wiki dumps into only relevant information.
# The output is:
# - results/pages_trimmed containing page id, namespace, title
# - results/links_trimmed containing pade id (from), namespace, title (to)
# This should be further parsed by parse_and_save to construct edges as
# (sr... | StarcoderdataPython |
4841734 | from model import *
import matplotlib.pyplot as plt
model = VirusModel(num_nodes=10, avg_node_degree=2, initial_outbreak_size=1, alpha=0.05, beta=0.05, gamma=0.03)
# while number_infected(model)>0:
# model.step()
for n in range(10):
model.step()
df = model.datacollector.get_model_vars_dataframe()
df.plot()
pl... | StarcoderdataPython |
3237638 | """Connections to ADODB data sources from Kukur.
This requires an installation of pywin32 (LGPL).
"""
# SPDX-FileCopyrightText: 2021 Timeseer.AI
# SPDX-License-Identifier: Apache-2.0
try:
import adodbapi
HAS_ADODB = True
except ImportError:
HAS_ADODB = False
from kukur.source.metadata import MetadataVa... | StarcoderdataPython |
12482 | #!/usr/bin/env python
from argparse import ArgumentParser
import sys
from comp_pi import compute_pi
def main():
arg_parser = ArgumentParser(description='compute pi using Fortran '
'function')
arg_parser.add_argument('n', default=1000, nargs='?',
hel... | StarcoderdataPython |
1617814 | <reponame>BenWibking/spack
# Copyright 2013-2021 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 import *
class TreeSitter(MakefilePackage):
"""Tree-sitter is a parser genera... | StarcoderdataPython |
4809431 | import os
import textwrap
from dvc.main import main
def test_cache_dir_local(tmp_dir, dvc, capsys, caplog):
(tmp_dir / ".dvc" / "config.local").write_text(
textwrap.dedent(
"""\
[cache]
dir = some/path
"""
)
)
path = os.path.join(dvc.dvc... | StarcoderdataPython |
53982 | <filename>spinner.py
#!/usr/bin/python
import sys, time
while True:
for i in ['\o/', '\o>', '<o>', '<o/']:
sys.stdout.write('\r%s' % i);
sys.stdout.flush();
time.sleep(0.1)
| StarcoderdataPython |
4842895 | # -*- coding: utf-8 -*-
from random import randint, random
import numpy as np
from npstreams import idot, itensordot, iinner, ieinsum, last
import pytest
def test_idot_against_numpy_multidot():
"""Test against numpy.linalg.multi_dot in 2D case"""
stream = [np.random.random((8, 8)) for _ in range(7)]
f... | StarcoderdataPython |
1681856 | <reponame>zzl0/aoc
from utils import *
@dataclass
class Password:
first: int
second: int
char: str
password: str
@classmethod
def of(cls, s):
# '1-3 b: cdefg' -> ('1', '3', 'b', 'cdefg')
l, h, c, password = re.findall(r'[^-:\s]+', s)
return cls(int(l), int(h), c, passw... | StarcoderdataPython |
1736577 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Auther: <NAME>
#
# This file is part of Mini Proxy Pool
#
# This program is free software and it is distributed under
# the terms of the MIT license. Please see LICENSE file for details.
PROXY_DB_FILE = "_proxies.db"
VALIDATOR_TIMEOUT = 1 # seconds
VALIDA... | StarcoderdataPython |
26308 | <reponame>AkshayVKumar/ActivityManager<filename>activity/views.py<gh_stars>0
from rest_framework import viewsets
from .serializers import MemberSerializer, ActivityPeriodSerializer
from activity.models import UserProfile, ActivityPeriod
from django.http import JsonResponse
#class for displaying members
class MemberVie... | StarcoderdataPython |
31741 | <reponame>bdunnette/derbot
from django.db.models.signals import pre_save
from django.dispatch import receiver
import random
import fractions
import humanize
# from derbot.names.tasks import generate_number
from derbot.names.models import DerbyName
@receiver(pre_save, sender=DerbyName)
def generate_number(sender, ins... | StarcoderdataPython |
3361171 | <reponame>drakaru/elastalert
import pytest
from elastalert.alerters.twilio import TwilioAlerter
from elastalert.loaders import FileRulesLoader
from elastalert.util import EAException
def test_twilio_getinfo():
rule = {
'name': '<NAME>',
'type': 'any',
'alert_subject': 'Cool subject',
... | StarcoderdataPython |
1736786 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module contains convenience functions for coordinate-related functionality.
This is generally just wrapping around the object-oriented coordinates
framework, but it is useful for some users who are used to more functional
interfaces.
"""
import... | StarcoderdataPython |
3342944 | <reponame>spikefairway/fsVOIManager
#!/usr/bin/env python
# coding: utf-8
__author__ = 'keisu-ma'
import sys
import pandas as pd
from fsVOIManager import mergeFSVOI
def argumentError():
print("Invalid argument!")
print("Usage: %s input_NIfTI_VOI_file VOI_set_file output_NIfTI_VOI_file" % (sys.argv[0]))
... | StarcoderdataPython |
64217 | <reponame>Layty/dlms-cosem<filename>dlms_cosem/clients/dlms_client.py
import contextlib
import logging
from typing import *
import attr
from typing_extensions import Protocol # type: ignore
from dlms_cosem import cosem, dlms_data, enumerations, exceptions, state, utils
from dlms_cosem.clients.blocking_tcp_transport ... | StarcoderdataPython |
1748632 | # Import the needed libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import datetime
# For linear regression function
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.linear_model import LogisticRegression, LinearRegression
from skl... | StarcoderdataPython |
1705860 | #!/usr/bin/env python3
# Copyright 2021 BHG [bw.org]
# as of 2021-04-07 bw
import sqlite3
def main():
db = sqlite3.connect(":memory:")
cur = db.cursor()
cur.execute("SELECT sqlite_version()")
version = cur.fetchone()[0]
print(f"SQLite version {version}")
cur.close()
db.close()
if __na... | StarcoderdataPython |
3308783 | from __future__ import print_function
import Pyro4
@Pyro4.behavior(instance_mode="single")
class SingleInstance(object):
@Pyro4.expose
def msg(self, message):
print("[%s] %s.msg: %s" % (id(self), self.__class__.__name__, message))
return id(self)
@Pyro4.behavior(instance_mode="session", inst... | StarcoderdataPython |
3265381 | <filename>FJSP/routing.py
import simpy
import random
import numpy as np
import torch
'''
routing data
job_idx, routing_data, machine_condition, job_pt, job slack, wc_idx, remaining_pt
routing_data = [cumulative_pt, time till available, que_size, cumulative_run_time]
'''
# Benchmark, as the worst possible cas... | StarcoderdataPython |
3333945 | <filename>swamp/mr/mrarray.py<gh_stars>1-10
import swamp.mr.mrjob
from swamp.mr.mr import Mr
from pyjob import TaskFactory
class MrArray(Mr):
"""An array of molecular replacement tasks to solve a given structure.
This class implements data structures to hold all the MR tasks to be executed on a target. It im... | StarcoderdataPython |
3391077 | <filename>tests/test_category.py
from pytypecho import Category
def test_get_category(te):
r = te.get_categories()
assert r
assert r[0]['categoryName'] == '默认分类'
def test_new_category(te):
category = Category(name='Category Name')
r = te.new_category(category)
assert r
assert isinstance(... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.