id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
42765 | <reponame>ravi-ojha/py-unique-names-generator<filename>unique_names_generator/data/animals.py
ANIMALS = [
"aardvark",
"aardwolf",
"albatross",
"alligator",
"alpaca",
"amphibian",
"anaconda",
"angelfish",
"anglerfish",
"ant",
"anteater",
"antelope",
"antlion",
"ape... | StarcoderdataPython |
2515 | import socketserver
import socket
import sys
import threading
import json
import queue
import time
import datetime
import traceback
class TCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
def server_bind(self):
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.soc... | StarcoderdataPython |
3343381 | '''
Embedded traffic light Flask server.
This module contains a Flask server containing handlers for the following paths:
- GET /store/live
Returns a stream from a .jpg generator using the Raspberry camera.
- GET /store/status
Returns the current status of the traffic light.
- POST /traff... | StarcoderdataPython |
197569 | <gh_stars>0
from __future__ import unicode_literals
import re
import json
from .common import InfoExtractor
from ..compat import (
compat_urllib_parse_unquote,
compat_urlparse,
)
from ..utils import (
ExtractorError,
clean_html,
get_element_by_id,
)
class VeeHDIE(InfoExtractor):... | StarcoderdataPython |
3245297 | import requests
import base64
class API_REST:
def inputGate(self,card_id,gate):
url = f'http://18.213.76.34/output/{card_id}'
print("RESPONSE API INPUT")
print(f'INPUT[] URL {url} gate={gate} card_id={card_id}')
response = requests.put(url,json={"gate":gate},verify=False).json()
... | StarcoderdataPython |
66053 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""
gyroid.util
===========
"""
import numpy as np
import scipy.io
import matplotlib.pyplot as plt
from matplotlib import colors
from mayavi import mlab
from .unitcell import UnitCell
from .group import Group
from .grid import Grid
from .basis import Basis
__all__ = [
"ren... | StarcoderdataPython |
77744 | <reponame>yusharon/sagemaker-xgboost-container<filename>test/unit/test_encoder.py
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is lo... | StarcoderdataPython |
123604 | from output.models.nist_data.atomic.id.schema_instance.nistschema_sv_iv_atomic_id_enumeration_1_xsd.nistschema_sv_iv_atomic_id_enumeration_1 import (
NistschemaSvIvAtomicIdEnumeration1,
NistschemaSvIvAtomicIdEnumeration1Type,
Out,
)
__all__ = [
"NistschemaSvIvAtomicIdEnumeration1",
"NistschemaSvIvA... | StarcoderdataPython |
1653665 | <reponame>xMestas/pyMARS<filename>pymars/tests/test_readInConditions.py
""" Tests the reduction methods implemented by pyMARS """
import sys
import os
import pytest
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/..")
import cantera as ct
import readin_initial_conditions
ROOT_DIR = os.path.dirname(os... | StarcoderdataPython |
25618 | <gh_stars>1-10
import numpy as np
import heapq
def cosine(x, y):
eps = 1e-10
return np.dot(x, y) / np.sqrt((np.dot(x, x) * np.dot(y, y)) + eps)
def get_nearest_k(word, vocab, vocab_matrix, k=4, return_score=False):
k_nearest_neighbors = []
vector_word = vocab_matrix[vocab[word]]
for w in vocab:
... | StarcoderdataPython |
3241753 | <filename>src/practice_4.py
#!/usr/bin/env python3.5
# -*- coding: utf-8 -*-
import tensorflow as tf
'''run() 的输入参数'''
a = tf.constant([5, 3], name='input_a')
b = tf.reduce_sum(a, name='add_b')
c = tf.reduce_prod(a, name='mul_c')
d = tf.add(b, c, name='add_d')
sess = tf.Session()
# fetches参数可接收 Op或Tensor对象,后者则输出一个... | StarcoderdataPython |
10002 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @author: x.huang
# @date:17-8-4
import logging
from pony.orm import db_session
from handlers.base.base import BaseRequestHandler
class LoginRequireError(Exception):
pass
class AuthBaseHandler(BaseRequestHandler):
""" 登录验证的基类 """
def prepare(self):
... | StarcoderdataPython |
3391294 | # -*- coding: utf-8 -*-
from .app import TenDaysWeb
from .response import Response
from .exceptions import HttpException | StarcoderdataPython |
51878 | def link_exists(url, links):
data = [x['link'] for x in links['links']]
return (lambda item, elements: item in elements)(url, data)
| StarcoderdataPython |
1679172 | #
# Copyright (c) 2019 MagicStack Inc.
# All rights reserved.
#
# See LICENSE for details.
##
import edgedb
import random
from . import queries
INSERT_PREFIX = 'insert_test__'
def connect(ctx):
return edgedb.create_client().with_retry_options(
edgedb.RetryOptions(attempts=10),
)
def close(ctx, ... | StarcoderdataPython |
108913 | #! /usr/bin/env python3
import os
from datetime import timedelta
import flask
from module.Interface import *
app = flask.Flask(__name__, template_folder="./static/html")
app.config['SECRET_KEY'] = os.urandom(24)
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=30)
@app.route('/', methods=["GET", "POST"])... | StarcoderdataPython |
4811170 | <reponame>suryanarayana007/python-iot-raspberry-pi-1486806556316
from flask import Flask,redirect
from flask import render_template
from flask import request
import os, json
import time
import ibmiotf.application
from twilio.rest import TwilioRestClient
vcap = json.loads(os.getenv("VCAP_SERVICES"))
twilioAccount = vca... | StarcoderdataPython |
3243901 | <reponame>Franky1/speech-emotion-webapp
from datetime import datetime
import cv2
import librosa
import librosa.display
import matplotlib.pyplot as plt
import numpy as np
from tensorflow.keras.models import load_model
# constants
starttime = datetime.now()
CAT6 = ['fear', 'angry', 'neutral', 'happy', 'sad', 'surprise... | StarcoderdataPython |
1651772 | # coding=utf8
OS = 1
SIZE_SZ = 8
MALLOC_ALIGNMENT = 2 * SIZE_SZ
MALLOC_ALIGN_MASK = 2 * SIZE_SZ - 1
MINSIZE = 32
FASTBIN_MAX_SIZE = 0x80
SMALLBIN_MAX_SIZE = 0x3f0
FASTBIN_CHUNK = 1
SMALLBIN_CHUNK = 2
UNSORTEDBIN_CHUNK = 3
LARGEBIN_CHUNK = 4
UNDEFINED = 0 | StarcoderdataPython |
1752657 | <filename>footballdatawrapper/Fixture.py
class Fixture:
"""
"id": 149461,
"soccerseasonId": 406,
"date": "2014-07-08T20:00:00Z",
"matchday": 6,
"homeTeamName": "Brazil",
"homeTeamId": 764,
"awayTeamName": "Germany",
"awa... | StarcoderdataPython |
3352715 | <filename>src/model/training/train.py
# https://colab.research.google.com/github/pytorch/vision/blob/temp-tutorial/tutorials/torchvision_finetuning_instance_segmentation.ipynb
from azureml.core import Run
import os
import sys
sys.path += ['.']
import logging
from shutil import copy
import numpy as np
import torch
impor... | StarcoderdataPython |
3385265 | import compas_ags
from compas_ags.diagrams import FormDiagram
from compas_ags.diagrams import ForceDiagram
from compas_ags.ags import form_update_q_from_qind
from compas_ags.ags import force_update_from_form
from compas_ags.ags import form_update_from_force
from compas_ags.viewers import Viewer
def view_form_force(fo... | StarcoderdataPython |
1655148 | <reponame>fochoao/cpython
from .log_widget import LogMonitorWidget, LogMonitorDockWidget, LogMonitorDropdown
from .log_database_handler import DatabaseHandler
import logging
from qtstrap import OPTIONS
from pathlib import Path
# Make sure the log database directory exists
Path(OPTIONS.config_dir).mkdir(parents=True, ... | StarcoderdataPython |
3211237 | #!/usr/bin/env python
import os
import sys
from setuptools import setup
import chesslib
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit(0)
classifiers = '''\
Development Status :: 5 - Production/Stable
Intended Audience :: Developers
License :: OSI Approved :: MIT License
Pro... | StarcoderdataPython |
21972 | <reponame>WWWCourses/PythonCourseNetIT-Slides
"""ЗАДАЧА:
Разгледайте дадения по-долу код и направете необходимите промени,
така че след приключването на двата процеса променливата x да има стойност 20.
Използвайте multiprocessing.Queue() за да обмените текущата стойност на x между процесите.
"""
import multiproces... | StarcoderdataPython |
1618661 | <reponame>ToddG/hypermodern-python-seed
"""{{cookiecutter.project_name}} tests."""
| StarcoderdataPython |
1629244 | #!/usr/bin/env python
# encoding: utf-8
from .converter import Csv2Weka # noqa
from .version import __version__ # noqa
__all__ = ['Csv2Weka', '__version__']
| StarcoderdataPython |
165301 | '''set_degrees_counted(degrees_counted)
Sets the "number of degrees counted" to the desired value.
Parameters
degrees_counted
The value to which the number of degrees counted should be set.
Type:integer (a positive or negative whole number, including 0)
Values:any number
Default:no default value
Errors
TypeError
degree... | StarcoderdataPython |
3276368 | # V0
# V1
# http://bookshadow.com/weblog/2018/06/17/leetcode-exam-room/
# https://blog.csdn.net/fuxuemingzhu/article/details/83141523
# IDEA : bisect.insort : https://www.cnblogs.com/skydesign/archive/2011/09/02/2163592.html
class ExamRoom(object):
def __init__(self, N):
"""
:type N: int
... | StarcoderdataPython |
1651015 | import os
import re
import magic
import fnmatch
import ctypes
import ctypes.util
import binwalk.smartstrings
from binwalk.compat import *
from binwalk.common import strings
from binwalk.prettyprint import PrettyPrint
class HashResult(object):
'''
Class for storing libfuzzy hash results.
For internal use only.
'''
... | StarcoderdataPython |
2982 | <filename>reservation_management/migrations/0021_delete_greenpass.py
# Generated by Django 3.2.7 on 2021-10-22 14:23
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('reservation_management', '0020_greenpass'),
]
operations = [
migrations.DeleteM... | StarcoderdataPython |
3392250 | from carla.data import DataCatalog
from carla.models import load_model, predict_negative_instances
if __name__ == "__main__":
data_name = "adult"
data_catalog = "adult_catalog.yaml"
data = DataCatalog(data_name, data_catalog)
model = load_model("ann", data_name)
print(f"Using model: {model.__clas... | StarcoderdataPython |
1770628 | """
atmospheric.py, <NAME> (2016-10-26)
Atmospheric water vapour, ozone and AOT from GEE
Usage
H2O = Atmospheric.water(geom,date)
O3 = Atmospheric.ozone(geom,date)
AOT = Atmospheric.aerosol(geom,date)
"""
import ee
import geemap
from Py6S import *
import os, sys, time, math, datetime
class Atmospheric():
def r... | StarcoderdataPython |
1777924 | from Symtab import ModuleScope
from PyrexTypes import *
from UtilityCode import CythonUtilityCode
from Errors import error
from Scanning import StringSourceDescriptor
class CythonScope(ModuleScope):
is_cython_builtin = 1
def __init__(self):
ModuleScope.__init__(self, u'cython', None, None)
sel... | StarcoderdataPython |
3243638 | <reponame>paulaksm/rrt-plan
class Domain(object):
''' STRIPS domain representation '''
def __init__(self, name, requirements, types, predicates, operators):
self._name = name
self._requirements = requirements
self._types = types
self._predicates = predicates
self._opera... | StarcoderdataPython |
3257296 | <filename>ldap2sql.py
#!/usr/bin/python
import inspect
import os
import sys
import urllib
import urllib2
import hashlib
import logging
from sqlalchemy import create_engine
reload(sys)
sys.setdefaultencoding('UTF8')
cmd_folder = os.path.abspath(os.path.join(os.path.split(inspect.getfile(inspect.currentframe()))[0], "c... | StarcoderdataPython |
1773893 | <reponame>UST-QuAntiL/Quokka<filename>api/controller/algorithms/algorithm_controller.py<gh_stars>0
from flask_smorest import Blueprint
from ...model.circuit_response import CircuitResponseSchema
from ...model.algorithm_request import (
HHLAlgorithmRequestSchema,
HHLAlgorithmRequest,
QAOAAlgorithmRequestSche... | StarcoderdataPython |
4811021 | """
Author: <NAME>
Date: September 7th 2020
Class for the defining a molecule object, and
being able to grab molecule features.
Molecule objects contain:
- XYZ geometry
- Atom list
- Charge
- Multiplicity
"""
import sys
import os
import logging
import numpy as np
class Molecule():
"""
Class contains proper... | StarcoderdataPython |
1703010 | <reponame>derpyninja/nlp4cciwr
# -*- coding: utf-8 -*-
import os
import logging
import textacy
import textacy.tm
from tqdm import tqdm
class TopicModelPermutation:
def __init__(self, grp_term_matrix, vectorizer, version=None):
# matrix & model
self.grp_term_matrix = grp_term_matrix
self.ve... | StarcoderdataPython |
43342 | #
# Copyright SAS Institute
#
# Licensed under the Apache License, Version 2.0 (the License);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | StarcoderdataPython |
1639175 | <gh_stars>1-10
def digitToword(num):
switcher = {
0: 'zero',
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine'
}
return switcher.get(num)
def numberToword(num):
if(num == ... | StarcoderdataPython |
190632 | #!/usr/bin/env python
from flask import Flask, jsonify
from alexa_agent import AlexaAgent
app = Flask(__name__)
@app.route('/tell-me-a-joke', methods=['GET'])
def tell_me_a_joke():
agent = AlexaAgent()
agent.wakeup()
agent.ask('tell me a joke')
return jsonify({'code': 200, 'message': 'Was that joke... | StarcoderdataPython |
3202664 | from setuptools import setup
setup(
name='mi',
packages=['mi'],
install_requires=[
'docopt', 'cached-property', 'sqlalchemy',
],
entry_points="""
[console_scripts]
mi=mi.main:entry_point
""",
)
| StarcoderdataPython |
3308575 | """
Entradas
Lectura de la factura-->float-->L
Costo kilovatio-->float-->CK
Salidas
Monto total de la factura-->float-->MT
"""
L=float(input("Ingrese la lectura de su factura: "))
CK=float(input("ingrese el costo del kilovatio: "))
MT=(L*CK)
print("Monto total de su factura: "+str(MT)) | StarcoderdataPython |
115974 | from interpolator import interpolate, interpolation_printer
def f(x, y, z):
return x*x*y*3 + x*x*2 + x*y*6 - x*13 - y*235 - 3351
xs = [2,3,5]
ys = [0,1]
zs = [3]
ps = (xs, ys, zs)
res = interpolate(f, ps)
interpolation_printer(res, tuple(map(len, ps)), 'xyz')
def g(x):
return sum(range(x + 1)) # equals to... | StarcoderdataPython |
1727595 | import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job
import pyspark.sql.functions as F
from pyspark import SparkContext
# from operator import add
from pyspark.sql.types impor... | StarcoderdataPython |
3357917 | """
Some key layers used for constructing a Capsule Network. These layers can used to construct CapsNet on other dataset,
not just on MNIST.
Author: <NAME>, E-mail: `<EMAIL>`, Github: `https://github.com/XifengGuo/CapsNet-Pytorch`
"""
import torch.nn.functional as F
import torch
from torch import nn
from torch.autogr... | StarcoderdataPython |
66646 | import itertools
from abc import abstractmethod, ABC
from typing import (
Sequence,
Any,
Iterable,
Dict,
)
from .helper import Offset2ID
from .... import Document
class BaseGetSetDelMixin(ABC):
"""Provide abstract methods and derived methods for ``__getitem__``, ``__setitem__`` and ``__delitem__`... | StarcoderdataPython |
3346434 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
All necessary for feature
"""
import tensorflow as tf
# model preprocess
model_preprocess = {
"DenseNet": tf.keras.applications.densenet.preprocess_input,
"EfficientNet": tf.keras.applications.efficientnet.preprocess_input,
"NasNet": tf.keras.applications.nasnet.... | StarcoderdataPython |
1792794 | <reponame>gsi-upm/senpy<filename>senpy/blueprints.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2014 Grupo de Sistemas Inteligentes (GSI) DIT, UPM
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obt... | StarcoderdataPython |
1719050 | #!/usr/bin/env python
# vim: set fileencoding=utf-8 ts=4 sts=4 sw=4 et tw=80 :
#
# Help determine actual units of downloaded Spitzer images.
#
# <NAME>
# Created: 2019-09-11
# Last modified: 2019-09-11
#--------------------------------------------------------------------------
#***********************************... | StarcoderdataPython |
1648316 | # Copyright 2021 Sony Group Corporation.
#
# 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 ... | StarcoderdataPython |
11129 | #! /usr/bin/env python
# -*- coding:utf8 -*-
#
# pw_classes.py
#
# This file is part of pyplanes, a software distributed under the MIT license.
# For any question, please contact one of the authors cited below.
#
# Copyright (c) 2020
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# Permission is hereby g... | StarcoderdataPython |
1740480 | <filename>django_town/rest/resources/mongo_resource.py<gh_stars>0
from django_town.utils import json
import datetime
from django.utils.functional import cached_property
from mongoengine import ListField, SortedListField, EmbeddedDocumentField, PointField, EmbeddedDocument, \
NotUniqueError, ValidationError, DateTim... | StarcoderdataPython |
3217944 | <filename>python3/easy/temperatures.py
import sys
import math
n = int(input())
numbers = input().split() or [0]
pos = min([int(i) if int(i) >= 0 else math.inf for i in numbers])
neg = max([int(i) if int(i) < 0 else (math.inf * -1) for i in numbers])
print(pos if pos <= abs(neg) else neg)
| StarcoderdataPython |
192220 | import sys
from typing import Dict
from ttt import *
from ttt.helper_util import PositionOccupiedException, InvalidCellPosition, \
BgColors
from utils.contracts import require, ensure
players: Dict[int, Player] = {}
symbols = {
1: "X",
2: "O"
}
@require("Player to be an Instance of Player",
la... | StarcoderdataPython |
3331552 | """
Sequence preprocessing functionality. Extends sklearn
transformers to sequences.
"""
import numpy as np
from sklearn.base import ClassifierMixin, BaseEstimator, TransformerMixin, clone
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.prepro... | StarcoderdataPython |
160701 | <reponame>Mopolino8/pylbm
# Authors:
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# License: BSD 3 clause
"""
Example of a two velocities scheme for the shallow water system
d_t(h) + d_x(q) = 0, t > 0, 0 < x < 1,
d_t(q) + d_x(q^2/h+gh^2/2) = 0, t > 0, 0 < x < 1,
"""
import sympy as sp
import pylbm
# pylin... | StarcoderdataPython |
17528 | #
# This script allows the user to control an Anki car using Python
# To control multiple cars at once, open a seperate Command Line Window for each car
# and call this script with the approriate car mac address.
# This script attempts to save lap times into local mysql db running on the pi
# Author: jstucken
#... | StarcoderdataPython |
3355321 | name = str(input('Digite um nome: ').strip().upper())
nameS = 'SILVA' in name
print('Have "Silva" in this name:')
print(nameS)
| StarcoderdataPython |
1776402 | file_name = "show_ver.out"
with open(file_name, "r") as f:
output = f.read()
if 'Cisco' in output:
print "Found Cisco string"
| StarcoderdataPython |
1768753 | <reponame>Anancha/Programming-Techniques-using-Python
myl1 = []
num = int(input("Enter the number: "))
for loop in range(num):
mydata = input("Enter the data: ")
myl1.append(mydata)
print(myl1)
| StarcoderdataPython |
128394 | <gh_stars>1-10
import datetime
import itertools
import logging
from numbers import Real
from typing import List, Tuple, Union, Optional, Any
import dateutil.parser
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class HeaderParameter:
paths: List[Tuple[str, ...]]
defaultvalue: Optional[Tu... | StarcoderdataPython |
3283456 | """
Decorator is a structural design pattern wich allows add
new behaviors in objects by put them inside of a "wrapper"
(decorator) of objects
Decorators provide an flexible alternative by the use of
subclasses for the functionality extension
Decorator (design pattern) != Python decorator
Python decorator -> A decor... | StarcoderdataPython |
1741317 | import configparser
import datetime
def parse_dates_from_config(dates_str):
return [datetime.datetime.strptime(day_string, "%Y.%m.%d").date()
for day_string in dates_str.split(',')]
class Config(object):
def __init__(self, api_key=None, work_hours_per_day=8.4, public_holidays=None,
... | StarcoderdataPython |
3381164 | <reponame>bzg/acceslibre
import dj_database_url
import os
from django.contrib.messages import constants as message_constants
from django.core.exceptions import ImproperlyConfigured
def get_env_variable(var_name, required=True, type=str):
if required:
try:
return type(os.environ[var_name])
... | StarcoderdataPython |
2698 | from django.conf.urls import include, url
from django.views.generic.base import TemplateView
from . import views as core_views
from .category.urls import urlpatterns as category_urls
from .collection.urls import urlpatterns as collection_urls
from .customer.urls import urlpatterns as customer_urls
from .discount.urls ... | StarcoderdataPython |
3220451 | from setuptools import setup
setup(name='lipnet',
version='0.1.6',
description='End-to-end sentence-level lipreading',
url='http://github.com/rizkiarm/LipNet',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
packages=['lipnet'],
zip_safe=False,
install_requires=[
# 'Ker... | StarcoderdataPython |
3235005 | from typing import Optional
import requests
import asyncio
from fastapi import FastAPI
from pydantic import BaseModel
import urllib
import urllib.parse
import json
import sys
import os
import platform
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] =... | StarcoderdataPython |
1789775 | __author__ = 'mikeconlon'
| StarcoderdataPython |
4818878 | <gh_stars>1-10
#!/usr/bin/env python
# Copyright 2015-2017, Institute for Systems Biology.
# 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 |
1745958 | <gh_stars>1-10
__version__ = "0.3.3"
from mongogrant.client import Client | StarcoderdataPython |
52936 | #coding=utf-8
#抓取精品课网站中的课程,把有优惠券的课程筛选出来
#第一步:访问ke.youdao.com 获取精品课网页的所有的标签内容,例如:四六级,考研,实用英语...:
#第二步:访问标签页,获取课程详情页的url
#第三步:获取课程详情页需要的信息
#第四步:保存到Excel表中
import requests
import urllib3
import re
import sys
from bs4 import BeautifulSoup
from openpyxl import Workbook
from openpyxl import load_workbook
#抓取标签,"http://ke.... | StarcoderdataPython |
3211736 | <gh_stars>1-10
import warnings
warnings.filterwarnings(action="ignore", module="scipy", message="^internal gelsd")
import pandas as pd
import numpy as np
import sklearn.linear_model as skl
import matplotlib.pyplot as plt
reg = skl.LinearRegression()
data = pd.read_csv('sleep_quality_data.csv', index_col=0)
x_train = ... | StarcoderdataPython |
1788704 | <gh_stars>1-10
import pandas as pd
from pyfibre.core.base_multi_image_analyser import BaseMultiImageAnalyser
from .multi_images import ProbeMultiImage
class ProbeAnalyser(BaseMultiImageAnalyser):
database_names = ['probe']
def __init__(self, *args, **kwargs):
kwargs['multi_image'] = ProbeMultiImag... | StarcoderdataPython |
65618 | <gh_stars>0
#!/usr/bin/env python3 -u
# -*- coding: utf-8 -*-
# copyright: sktime developers, BSD-3-Clause License (see LICENSE file)
"""Implements feature selection algorithms."""
__author__ = ["aiwalter"]
__all__ = ["FeatureSelection"]
import math
import pandas as pd
from sktime.transformations.base import BaseTr... | StarcoderdataPython |
3284448 | <gh_stars>0
"""
Script for running simulations to compare the payments of strategic and truthful agents in the continuous effort, biased agents setting.
@author: <NAME> <<EMAIL>>
"""
from numpy import ones
from statistics import mean, median, variance
import json
from setup import initialize_strategic_student_list, ... | StarcoderdataPython |
3387580 | <gh_stars>0
from django.shortcuts import render
from django.views.generic import View
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, JsonResponse
from django.utils import timezone
from .forms import PhotoForm, DeleteFo... | StarcoderdataPython |
3362559 | class IActionChooser:
def action(self, state, considerExploring):
pass
def get_brain(self):
pass
| StarcoderdataPython |
161422 | <reponame>RobertTownley/stonehenge<filename>stonehenge/components/ui/base.py
from stonehenge.components.component import Component
class UIComponent(Component):
pass
| StarcoderdataPython |
1714879 | <reponame>SalahAdDin/django-oscar-support
from django.db import models
from django.utils.timezone import now as utc_now
from django.utils.translation import ugettext_lazy as _
class ModificationTrackingMixin(models.Model):
date_created = models.DateTimeField(_("Created"), blank=True)
date_updated = models.Dat... | StarcoderdataPython |
152574 | <gh_stars>0
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import pulumi
import pulumi.runtime
class GroupPolicyAttachment(pulumi.CustomResource):
"""
Attaches a Managed IAM... | StarcoderdataPython |
1794398 | <filename>niimpy/preprocessing/test_sampledata.py
"""Test that sample data can be opened.
"""
import pandas as pd
import pytest
import niimpy
from niimpy.reading import read
from niimpy.config import config
from niimpy.preprocessing import sampledata
TZ = 'Europe/Helsinki'
@pytest.mark.parametrize("datafile",
... | StarcoderdataPython |
51881 | <reponame>gtnx/chrony<filename>chrony/core.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
import pandas as pd
def compute_category_index(categories):
return {category: index + 1 for index, category in enumerate(sorted(set(categori... | StarcoderdataPython |
1706259 | <filename>network_aware_heat/network_aware_resources.py<gh_stars>1-10
from heat.engine.properties import Properties
from heat.engine.resources.openstack.nova.server import Server as NovaServer
from oslo_log import log as logging
from heat.engine import properties
LOG = logging.getLogger("heat.engine.resource")
def... | StarcoderdataPython |
27200 | from cheater import *
from main import *
# new Chain instance with
# mining difficulty = 4
c = Chain(4)
c.createGenesis()
# simulate transactions
c.addBlock(Block("3$ to Arthur"))
c.addBlock(Block("5$ to Bob"))
c.addBlock(Block("12$ to Jean"))
c.addBlock(Block("7$ to Jake"))
c.addBlock(Block("2$ to Camille"))
c.addBl... | StarcoderdataPython |
3323834 | <filename>src/app/clients.py<gh_stars>0
from datetime import timedelta
from .constants import KIND_MAP
from .db import session
from .models import Message, User
def check_if_message_exists(data):
gap_30_minutes_up = data["scheduled"] + timedelta(minutes=30)
gap_30_minutes_down = data["scheduled"] - timedelta... | StarcoderdataPython |
1635891 | <gh_stars>0
import os
from dotenv import load_dotenv
dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
if os.path.exists(dotenv_path):
load_dotenv(dotenv_path)
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from beedare import create_app, create_admin
from beedare ... | StarcoderdataPython |
120904 | <gh_stars>1-10
def B():
n = int(input())
a = [int(x) for x in input().split()]
d = {i:[] for i in range(1,n+1)}
d[0]= [0,0]
for i in range(2*n):
d[a[i]].append(i)
ans = 0
for i in range(n):
a , b = d[i] , d[i+1]
ans+= min(abs(b[0]-a[0])+abs(b[1]-a[1]) , abs(b[0]-a[1])... | StarcoderdataPython |
3386836 | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Tests for ``flocker.provision._ssh._monkeypatch``.
"""
from twisted.trial.unittest import SynchronousTestCase as TestCase
from .._ssh._monkeypatch import _patch_7672_needed, patch_7672_applied
class Twisted7672Tests(TestCase):
""""
Tests for `... | StarcoderdataPython |
3324873 | <filename>tests/pint_units.py<gh_stars>1-10
import importlib.resources as pkg_resources
import random
_RAW_UNIT_DATA = None
def get_units():
global _RAW_UNIT_DATA # pylint: disable=global-statement
if _RAW_UNIT_DATA is None:
unit_data = {}
for raw_row in pkg_resources.open_text(__package__,... | StarcoderdataPython |
1713406 | <gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 26 13:13:09 2020
@author: praveshj
"""
#Calculating the NMI Score for all four clusterings
import math
import pandas as pd
import numpy as np
#X is a list of lists, where each list correponds to a class
#So to calculate entropy we ju... | StarcoderdataPython |
3314937 | '''
Visualize sequences prepared by tools.prepare
Run after running main.py
'''
from tools import dataset
from tools.dataset import Dataset
from tools import prepare
import random
import os
import argparse
from glob import glob
import numpy as np
import cv2
import imageio
from tools import augmentation as augment... | StarcoderdataPython |
133679 | from verifiers import *
from cipher import *
from rwaFiles import *
from colors import *
import getpass
passCounter = 0
idCounter = 0
userID = ''
############################################ Start of Register User ############################################
# Register User Function - userid_pswd.csv
def re... | StarcoderdataPython |
1783795 | #!/usr/bin/python3
import subprocess, os, sys, time, atexit, signal, psutil, datetime
if len(sys.argv) < 3:
print("Usage: watcher.py <directories and/or files to watch, comma separated> <command to terminate and repeat> <optional \"forever\">")
sys.exit(1)
forever = False
if len(sys.argv) > 3 and sys.argv[3] == "f... | StarcoderdataPython |
136686 | <reponame>Robin5605/site<filename>pydis_site/apps/content/tests/test_utils.py<gh_stars>100-1000
from pathlib import Path
from django.http import Http404
from pydis_site.apps.content import utils
from pydis_site.apps.content.tests.helpers import (
BASE_PATH, MockPagesTestCase, PARSED_CATEGORY_INFO, PARSED_HTML, PA... | StarcoderdataPython |
57677 | <reponame>iamgroot42/opacus
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# 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/... | StarcoderdataPython |
1639861 | #!/usr/bin/env python3.6
from user import User
from credential import Credential
def create_user(fname, lname, email, Password):
'''
function to create a new user
'''
new_user = User(fname, lname, email, Password)
return new_user
def save_users(user):
'''
function to save user
'''
... | StarcoderdataPython |
3395077 | import shutil
from os import path
from pathlib import Path
from embers.rf_tools.align_data import (plot_savgol_interp, save_aligned,
savgol_interp)
# Save the path to this directory
dirpath = path.dirname(__file__)
# Obtain path to directory with test_data
test_data = path.abs... | StarcoderdataPython |
4842233 | <reponame>Philipuss1/cloob<gh_stars>1-10
import argparse
def get_default_params(model_name):
# Params from paper (https://arxiv.org/pdf/2103.00020.pdf)
if model_name in ["RN50", "RN101", "RN50x4"]:
return {"lr": 5.0e-4, "beta1": 0.9, "beta2": 0.999, "eps": 1.0e-8}
elif model_name == "ViT-B/32":
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.