text string | size int64 | token_count int64 |
|---|---|---|
import frappe
def set_appointment_as_pending():
frappe.db.sql("""update `tabVisitor Appointment` set `status`='Pending'
where appointment_date is not null
and appointment_date < CURDATE()
and `status` not in ('Closed', 'Cancelled')""") | 243 | 86 |
from django.urls import path , include
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.home,name='home'),
path('profile/', views.profile , name = 'profile'),
path('update_profile/',views.update_profile,name='update'),
... | 986 | 317 |
from typing import List
from .tile import Tile
class TargetTracker(list):
"""
Track the targets that might be good to attack/explore
"""
def __init__(self, *args, **kwargs):
list.__init__(self, *args, **kwargs)
self.turn_last_updated: int = 0
def update_list(self, target_list: Li... | 962 | 279 |
import logging
import time
import blueforge.apis.telegram as tg
import requests
import urllib.parse
import json
from blueforge.apis.facebook import Message, ImageAttachment, QuickReply, QuickReplyTextItem, TemplateAttachment, \
GenericTemplate, Element, PostBackButton, ButtonTemplate, UrlButton
logger = logging.g... | 7,546 | 1,919 |
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
# Create your models here.
class QuestionManager(models.Manager):
def new(self):
return self.order_by('-id')
def popular(self):
return self.order_by('-rating')
class Question(models.Model... | 1,195 | 366 |
class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
pre_sum = sum(nums[0:k])
max_sum = pre_sum
for i in range(len(nums)-k):
next_sum = pre_sum - nums[i] + nums[i + k]
if next_sum > max_sum:
max_sum = next_sum
pre_su... | 368 | 131 |
n = float(input("informe um medida em metros: "));
cm = n * 100
mm = n * 1000
print('A medida {}M é correspondente a {}Cm e {}Mm'.format(n, cm, mm)) | 152 | 69 |
# -*- coding: utf-8 -*-
# (c) 2013 Bright Interactive Limited. All rights reserved.
# http://www.bright-interactive.com | info@bright-interactive.com
from import_descendants import import_descendants
import sys
this_module = sys.modules[__name__]
import_descendants(this_module, globals(), locals())
| 301 | 103 |
import pytest
from tempus_dominus import widgets
def test_datepicker_format_localized(settings):
settings.TEMPUS_DOMINUS_LOCALIZE = True
widget = widgets.DatePicker()
assert widget.get_js_format() == 'L'
def test_datepicker_format_nonlocalized(settings):
settings.TEMPUS_DOMINUS_LOCALIZE = False
... | 1,264 | 445 |
import folium
from folium import plugins
import numpy as np
import sqlite3 as sqlite
import os
import sys
import pandas as pd
#extract data from yelp DB and clean it:
DB_PATH = "/Users/selinerguncu/Desktop/PythonProjects/Fun Projects/Yelp/data/yelpCleanDB.sqlite"
conn = sqlite.connect(DB_PATH)
##################... | 9,568 | 2,977 |
from . import (
UpdateMethods, AuthMethods, DownloadMethods, DialogMethods,
ChatMethods, MessageMethods, UploadMethods, MessageParseMethods,
UserMethods
)
class TelegramClient(
UpdateMethods, AuthMethods, DownloadMethods, DialogMethods,
ChatMethods, MessageMethods, UploadMethods, MessageParseMetho... | 352 | 91 |
import logging
from ruamel.yaml import YAML
from great_expectations.data_context.data_context.data_context import DataContext
logger = logging.getLogger(__name__)
yaml = YAML()
yaml.indent(mapping=2, sequence=4, offset=2)
yaml.default_flow_style = False
class ExplorerDataContext(DataContext):
def __init__(self... | 1,529 | 395 |
"""Rio-Cogeo Errors and Warnings."""
class LossyCompression(UserWarning):
"""Rio-cogeo module Lossy compression warning."""
class IncompatibleBlockRasterSize(UserWarning):
"""Rio-cogeo module incompatible raster block/size warning."""
class RioCogeoError(Exception):
"""Base exception class."""
class... | 406 | 131 |
import click
@click.group()
def update():
pass
@update.command("song")
def _update_song():
pass
@update.command("arrangement")
def _update_arrangement():
pass
@update.command("worship")
def _update_worship():
pass
@update.command("hymn")
def _update_hymn():
pass
| 293 | 107 |
'''
Copyright (c) Alex Li 2003. All rights reserved.
'''
__version__ = '0.1'
__file__ = 'rmcompile.py'
import os, getopt, sys
EXTLIST = ['.ptlc', '.pyc']
def remove(extlist, dirname, files):
for file in files:
(name, ext) = os.path.splitext(file)
if ext in extlist:
os.remove(os.p... | 1,367 | 469 |
import json
import os
from urllib.request import Request, urlopen
OPSGENIE_KEY = os.getenv("OPSGENIE_KEY", None)
def get_on_call_users(schedule):
content = api_get_request(
f"https://api.opsgenie.com/v2/schedules/{schedule}/on-calls",
{"name": "GenieKey", "token": OPSGENIE_KEY},
)
try:
... | 706 | 249 |
# Generated by Django 3.1.1 on 2020-10-07 20:20
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('dados', '0006_auto_20201007_1630'),
]
operations = [
migrations.AlterUniqueTogether(
name='variaveisgrafico',
unique_togethe... | 366 | 143 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 8 15:15:29 2018
@author: tatvam
importing the libraries
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# import the dataset
dataset = pd.read_csv("Data.csv")
X = dataset.iloc[:, :-1].values
Y = dataset.iloc[:, 3].value... | 688 | 262 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
from distutils.dir_util import copy_tree
from kombu.utils.objects import cached_property
import qiniu_ufop
from ..base import BaseCommand
class Command(BaseCommand):
"""创建一个项目"""
def execute(self, args, unknown):
src = os.pa... | 785 | 273 |
import pytest
from jenkinsapi.jenkins import Jenkins
from jenkinsapi.nodes import Nodes
from jenkinsapi.node import Node
DATA0 = {
'assignedLabels': [{}],
'description': None,
'jobs': [],
'mode': 'NORMAL',
'nodeDescription': 'the master Jenkins node',
'nodeName': '',
'numExecutors': 2,
... | 8,991 | 3,058 |
from messages.SessionMessage import SessionMessage
from msg_codes import CLIENT_GET_CLOUD_HOST_RESPONSE as CLIENT_GET_CLOUD_HOST_RESPONSE
__author__ = 'Mike'
class ClientGetCloudHostResponse(SessionMessage):
def __init__(self, session_id=None, cname=None, ip=None, port=None, wsport=None):
super(ClientGetC... | 790 | 260 |
"""
PSEUDOCODE:
Load csv to pandas
csv will be of form: city, event type, event name, year, theme_A, theme_B, theme_C...
City can contain multiple cities, separated by TBD?
Check min and max year
Open figure,
Deal with events in same year, offset a little bit?
For city in cities:tle
for event in events
"""
impor... | 8,072 | 3,008 |
from eth.db.atomic import AtomicDB
from eth.db.backends.level import LevelDB
from eth.db.account import AccountDB
from rlp.sedes import big_endian_int
from bevm.block import Block
from bevm.action import rlp_decode_action
ACTION_COUNT = b'BEVM:ACTION_COUNT'
def block_key(blockno):
return 'BEVM:BLOCK_KEY_{}'.for... | 2,012 | 683 |
import dateutil.parser as dp
from dateutil.relativedelta import relativedelta
import pandas as pd, datetime as dt
def checkLatestAnomaly(df, operationCheckStr):
"""
Looks up latest anomaly in dataframe
"""
anomalies = df[df["anomaly"] == 15]
if anomalies.shape[0] > 0:
lastAnomalyRow = anom... | 2,408 | 868 |
list = []
while True:
number = 0.0
input_num = input('Enter a number: ')
if input_num == 'done':
break
try:
number = float(input_num)
except:
print('Invalid input')
quit()
list.append(input_num)
if list:
print('Maximum: ', max(list) or None)
print('Minimum... | 343 | 115 |
MONO = "FiraMono-Medium"
PORT = 9999
ISSUES = "https://github.com/math2001/nine43/issues"
| 91 | 49 |
import sys
PY2 = sys.version_info[0] == 2
if PY2:
from .zipencrypt2 import ZipFile
from zipfile import BadZipfile, error, ZIP_STORED, ZIP_DEFLATED, \
is_zipfile, ZipInfo, PyZipFile, LargeZipFile
__all__ = ["BadZipfile", "error", "ZIP_STORED", "ZIP_DEFLATED",
"is_zipfile", "ZipInfo",... | 484 | 188 |
from . import tools | 19 | 5 |
from .rawdata import RawData
from .timedata import TimeData
from .voltdata import VoltData
__all__ = ["RawData", "TimeData", "VoltData"]
| 138 | 47 |
"""
Sketch (similar to Coarse-to-Fine)
- keep Python keywords as is
- strip off arguments and variable names
- substitute tokens with types: `NUMBER`, `STRING`
- specialize `NAME` token:
- for functions: `FUNC#<num_args>`
# Examples
x = 1 if True else 0
NAME = NUMBER if True else NUMBER
result = SomeFunc(1,... | 5,654 | 1,893 |
import pytest
from LPBv2.common import (
InventoryItem,
PlayerInfo,
PlayerScore,
PlayerStats,
TeamMember,
MinimapZone,
merge_dicts,
)
from LPBv2.game import Player
update_data = {
"abilities": {
"E": {
"abilityLevel": 0,
"displayName": "\u9b42\u306e\u8a6... | 8,538 | 3,279 |
# cookbook/ingredients/schema.py
import graphene
from graphene_django_extras import DjangoObjectField, DjangoFilterPaginateListField, LimitOffsetGraphqlPagination
from .types import UserType
from .mutations import UserSerializerMutation
from .subscriptions import UserSubscription
class Query(graphene.ObjectType):
... | 785 | 217 |
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask.logging import default_handler
from flask_request_id_header.middleware import RequestID
from app.resources.encoders import CustomJSONEncoder
from app.resources.logger import formatter
from flask_jwt import JWT
db = SQLAlchemy()
def ... | 1,026 | 307 |
import unittest
import tempfile
import os
import yaml
import types
from hier_config import HConfig
from hier_config.host import Host
class TestNegateWithUndo(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.os = 'comware5'
cls.options_file = os.path.join(
os.path.dirname... | 1,199 | 431 |
"""Gauss-Legendre collocation methods for port-Hamiltonian systems"""
import sympy
import numpy
import math
from newton import newton_raphson, DidNotConvergeError
from symbolic import eval_expr
def butcher(s):
"""Compute the Butcher tableau for a Gauss-Legendre collocation method.
Parameters
----------... | 6,984 | 2,464 |
from sql_app.repositories.movie_repository import MovieRepo
from feedgenerator import RssFeed
from sqlalchemy.orm import Session
class LatestRssFeed(RssFeed):
title: str
price: float
description: str
@staticmethod
def items(db: Session):
return MovieRepo.fetch_all(db)
@staticmethod
... | 525 | 156 |
from opentera.db.Base import db, BaseModel
class TeraDeviceParticipant(db.Model, BaseModel):
__tablename__ = 't_devices_participants'
id_device_participant = db.Column(db.Integer, db.Sequence('id_device_participant_sequence'), primary_key=True,
autoincrement=True)
id_... | 3,026 | 958 |
"""
725. Split Linked List in Parts
Medium
0Given the head of a singly linked list and an integer k, split the linked list into k consecutive linked list parts.
The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null.
... | 11,043 | 3,421 |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
"""
def ecdf(sorted_views):
for view, data in sorted_views.iteritems():
yvals = np.arange(len(data))/float(len(data))
plt.plot(data, yvals, label=view)
plt.grid(True)
plt.xlabel('jaccard')
plt.ylabel('CDF')
lgnd ... | 1,645 | 643 |
import pystim
bin_path = None # TODO correct.
vec_path = None # TODO correct.
trials_path = None # TODO correct.
stimulus = pystim.stimuli.flashed_images.load(bin_path, vec_path, trials_path)
print(stimulus.nb_frames)
print(stimulus.nb_diplays)
print(stimulus.nb_trials)
print(stimulus.nb_conditions)
print(stimulu... | 1,740 | 637 |
#### neeed to make sure google still work for sure
# this may have to run on non-python devs' boxes, try/catch an install of the requests lib to be SURE
try:
import requests
except:
import os
os.sys('easy_install pip')
os.sys('pip install requests')
import requests
#r = requests.get('http://www.go... | 427 | 139 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Exercise 10.10 from Kane 1985."""
from __future__ import division
from sympy import expand, solve, symbols, sin, cos, S
from sympy.physics.mechanics import ReferenceFrame, RigidBody, Point
from sympy.physics.mechanics import dot, dynamicsymbols, inertia, msprint
from ut... | 4,760 | 2,443 |
from unittest import TestCase
from src.view import PairwiseView
import numpy as np
class TestPairwiseView(TestCase):
def setUp(self):
self.num_stations = 4
self.n = 200
self.stations = np.random.randn(self.n, self.num_stations)
self.pv = PairwiseView(variable='pr')
def test_mak... | 1,179 | 430 |
# prompt user to enter how much they weigh in pounds
weight = int(input ("How much do you weigh (in pounds)? "))
# prompt user to enter their height in inches
height = int(input ("What is your height (in inches)? "))
# this converts weight to kilograms
weight_in_kg = weight / 2.2
# this converts height to c... | 1,013 | 383 |
# Day9 - 2021 Advent of code
# source: https://adventofcode.com/2021/day/9
import os
import numpy as np
def clear_console():
os.system('clear')
print('< .... AoC 2021 Day 9, part 1 .... >')
print()
return
def find_low_points(the_map, numOfRows, numOfCols):
low_points_list = []
row = 0
las... | 7,031 | 2,213 |
import discord
from discord.ext import commands
from datetime import date, datetime
# Class handles commands related to console players
class ConsoleCommands(commands.Cog, name="Console Commands"):
"""Console Commands"""
def __init__(self, bot):
self.bot = bot
# Returns a list of embeds of conso... | 7,420 | 1,953 |
R"""
try to get the worksheet name from a worksheet
run -pyf C:\Users\swharden\Documents\GitHub\PyOriginTools\documentation\demonstrations\abfFromWks.py
"""
import sys
if False:
# this code block will NEVER actually run
sys.path.append('../') # helps my IDE autocomplete
sys.path.append('../../') # helps my... | 666 | 211 |
# Generated by Django 3.1 on 2021-08-19 15:49
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("corpus", "0017_secondary_lang_allow_unknown"),
]
operations = [
migrations.AlterField(
model_name... | 803 | 273 |
from .features import *
from .conditions import *
| 50 | 14 |
import numpy as np
import h5py
from datetime import datetime
from geopy.distance import distance
import argparse
import pickle
import json
import os
class TestedFeatureExtractor:
driving_time_norm = 1
def __init__(self, selected_feature, norm_param):
self.selected_feature = selected_feature
s... | 5,932 | 1,946 |
from clawpack.petclaw.solution import Solution
import matplotlib
matplotlib.use('Agg')
import matplotlib.pylab as pl
from matplotlib import rc
import numpy as np
import os
def plot_q(frame,
file_prefix='claw',
path='./_output/',
xShift=0.0,
xlimits=None,
ylimits=N... | 2,545 | 946 |
import torch
from typing import List
def get_min_value(tensor):
if tensor.dtype == torch.float16:
min_value = -1e4
elif tensor.dtype == torch.float32:
min_value = -1e9
else:
raise ValueError("{} not recognized. `dtype` "
"should be set to either `torch.floa... | 2,285 | 835 |
import os
import json
import numpy as np
from numpy import log10, pi, sqrt
import scipy.io.wavfile as wav
from scipy.fftpack import *
from src import (
FilterAnalyzePlot,
WaveProcessor,
ParametricEqualizer,
GraphicalEqualizer,
cvt_char2num,
maker_logger,
DEBUG,
)
if DEBUG:
PRINTER = ma... | 13,762 | 5,306 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import re
import json
from datetime import datetime
from alfred import *
TIMESTAMP_SEC_RE = r'^\d{10}$' # 1643372599
TIMESTAMP_MSEC_RE = r'^\d{13}$' # 1643372599000
# 2022-01-28 10:00:00
DATETIME_LONG_STR = r'^[1-9]\d{3}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$'
DATET... | 3,322 | 1,338 |
import ursina
app = ursina.Ursina(init_showbase=True)
| 55 | 23 |
import logging
from functools import wraps
import psutil
from telegram import InlineKeyboardMarkup, InlineKeyboardButton, ForceReply, ParseMode
from telegram.ext import CommandHandler, CallbackQueryHandler, MessageHandler, Filters
from ravager.bot.helpers.constants import *
from ravager.bot.helpers.timeout import Con... | 14,598 | 4,202 |
#############################################################
# 作者:我.doc
# Github地址:https://github.com/idocx/WHULibSeatReservation
#############################################################
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\x03\xac\
\x00\
\x00\x67\xf6\x78\x9c... | 10,004 | 8,826 |
import random
import six.moves.urllib.parse as urlparse
def replace_url(url, host=None, port=None, path=None):
o = urlparse.urlparse(url)
_host = o.hostname
_port = o.port
_path = o.path
if host is not None:
_host = host
if port is not None:
_port = port
netloc = _host
... | 563 | 219 |
# 9.1. Putting a Wrapper Around a Function
#region
# import time
# from functools import wraps
# def timethis(func):
# '''
# Decorator that reports the execution time.
# '''
# @wraps(func)
# def wrapper(*args, **kwargs):
# start = time.time()
# result = func(*args, **kwargs)
# ... | 2,745 | 924 |
import numpy as np
import torch
torch.manual_seed(0)
# PRE-PROCESSING
RAVDESS_DSET_PATH = "C:\\Users\\***\\Downloads\\RAVDESS\\"
TESS_DSET_PATH = "C:\\Users\\***\\Downloads\\TESS\\"
N_WORKERS = 15
# DATASET
emote_id = {
"01" : "neutral", "03" : "happy",
"04" : "sad", "05" : "angry"}
emote_idn = ... | 759 | 352 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: vdp/pipeline/v1alpha/pipeline_service.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import... | 7,752 | 3,707 |
__author__ = "SilentJungle399"
__version__ = "1.0.0"
from .client import *
from .models import *
from .enums import *
| 119 | 48 |
from .abstractanalyzer import AbstractAnalyzer
from textblob import TextBlob
class TextBlobAnalyzer(AbstractAnalyzer):
def __init__(self):
pass
def analyze(self, text_content):
pass
| 211 | 64 |
"""3/1 adventofcode"""
with open("input.txt", "r", encoding="UTF-8") as i_file:
data = i_file.read().splitlines()
columns = [[row[i] for row in data] for i in range(len(data[0]))]
def binlst_to_int(values) -> int:
"""Returns int values of binary in list form"""
values = values[::-1]
total = 0... | 850 | 302 |
class Solution:
def palindromePairs(self, words: List[str]) -> List[List[int]]:
lookup = {}
for index, word in enumerate(words):
lookup[word] = index
ans = set()
for index, word in enumerate(words):
for k in range(len(word) + 1):
current = word... | 848 | 225 |
from braces.views import AnonymousRequiredMixin
from django.views.generic import TemplateView
class LandingView(AnonymousRequiredMixin, TemplateView):
template_name = 'landing/index.html'
| 193 | 55 |
#!/usr/bin/python3
from functools import partial
from datetime import datetime
import pandas as pd
from joblib import parallel_backend
import random
import numpy as np
from sklearn.calibration import CalibratedClassifierCV
import shutil
import pathlib
import os
import math
import random
from matplotlib import pyplot
... | 30,437 | 10,092 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
from scipy import optimize, sparse
from .AbstractDistanceAlg import AbstractDistanceAlg
class HungarianAlg(AbstractDistanceAlg):
def __init__(self, df, size):
super().__init__(df, size)
def compute_matching(self):
distances = ... | 692 | 207 |
from collections.abc import Sequence
from .filter import Filter
class FilterCollection(Sequence):
def __init__(self, host, filters, *args, **kwargs):
super().__init__(*args, **kwargs)
self.host = host
self._filters = [Filter(self.host, filter) for filter in filters]
def __repr__(self... | 757 | 238 |
"""
:copyright: Nick Hale
:license: MIT, see LICENSE for more details.
"""
__version__ = '0.0.1'
| 97 | 43 |
from google.protobuf import text_format
from pomagma.io import protobuf_test_pb2
from pomagma.io.protobuf import InFile, OutFile
from pomagma.util import in_temp_dir
from pomagma.util.testing import for_each
def parse(text, Message=protobuf_test_pb2.TestMessage):
message = Message()
text_format.Merge(text, m... | 1,386 | 418 |
"""
Copyright 2020 The OneFlow 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 applicable l... | 2,039 | 703 |
import re
from django.template import Library, Node, TemplateSyntaxError
from django.template.base import token_kwargs
from django.urls import Resolver404, resolve
from django.utils.html import format_html
register = Library()
class MenuItemNode(Node):
def __init__(self, nodelist, pattern, kwargs):
self... | 1,577 | 461 |
""" Log initializer """
from __future__ import absolute_import, division, print_function, unicode_literals
import itertools
import logging
import sys
import os
from logging.handlers import RotatingFileHandler
from rich.logging import RichHandler
from typing import List
DEBUG = logging.DEBUG
INFO = logging.INFO
ERROR ... | 3,984 | 1,257 |
import argparse
from pathlib import Path
import torch
import torch.nn.functional as F
from sklearn.metrics import precision_recall_fscore_support, roc_curve, auc
import matplotlib.pyplot as plt
import numpy as np
from data.data_loader import ActivDataset, loader
from models.focal_loss import FocalLoss
from models.ete_... | 6,613 | 2,382 |
from structure_helper_class import structure_helper
from model_train_helper_class import model_train_helper
import matplotlib.pyplot as plt
import pandas as pd
from tabulate import tabulate
class convex_hull:
def get_convex_hull_points(structure_name_to_object_map, draw_hull = True, model = None, model_str =... | 4,031 | 1,144 |
# <<BEGIN-copyright>>
# Copyright 2021, Lawrence Livermore National Security, LLC.
# See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
# <<END-copyright>>
"""
Store and report warnings and errors in a PoPs database.
PoPs.check() returns a nested list of warning objects:
>>> ... | 5,460 | 1,549 |
from canoser import Struct, Uint8, bytes_to_int_list, hex_to_int_list
from libra.transaction.transaction_argument import TransactionArgument, normalize_public_key
from libra.bytecode import bytecodes
from libra.account_address import Address
class Script(Struct):
_fields = [
('code', [Uint8]),
... | 2,077 | 613 |
from Calculators.Division import division
def sampleMean(data):
sample_data = data[0:999]
n = len(sample_data)
return round(division(n, sum(sample_data)), 1)
| 172 | 63 |
from collections import defaultdict
def read_line_to_list(as_type=int):
return map(as_type, raw_input().strip().split(' '))
N, M, T = read_line_to_list()
candies_ = [read_line_to_list() for _ in range(N)]
class CollectCandies(object):
def __init__(self, n, m, t, candies):
self.dim = n, m
s... | 1,901 | 699 |
# ----------------------------------------------------------------------
# |
# | __init__.py
# |
# | David Brownell <db@DavidBrownell.com>
# | 2018-02-18 14:37:39
# |
# ----------------------------------------------------------------------
# |
# | Copyright David Brownell 2018.
# | Distribute... | 13,818 | 3,339 |
# Databricks notebook source exported at Mon, 14 Mar 2016 03:21:05 UTC
# MAGIC %md
# MAGIC **SOURCE:** This is from the Community Edition of databricks and has been added to this databricks shard at [/#workspace/scalable-data-science/xtraResources/edXBigDataSeries2015/CS100-1x](/#workspace/scalable-data-science/xtraRes... | 3,213 | 1,314 |
from unittest import mock
import astropy.units as u
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pytest
from einsteinpy.coordinates import SphericalDifferential
from einsteinpy.plotting import StaticGeodesicPlotter
@pytest.fixture()
def dummy_data():
sph_obj = SphericalDiff... | 2,075 | 831 |
#from inv_ind.py import inverted_index
import search
class main:
#vector_space = inverted_index()
# *************************** INPUTTING THE QUERY ***************************
k = input('Enter value of k:') #Accepting query from the user
query = input('Enter your search query:') #Accepting query fr... | 367 | 107 |
from enum import Enum
import typer
from fasta_reader import read_fasta
from deciphon_cli.core import ScanPost, SeqPost
from deciphon_cli.requests import get_json, get_plain, post_json
__all__ = ["app"]
app = typer.Typer()
class ScanIDType(str, Enum):
SCAN_ID = "scan_id"
JOB_ID = "job_id"
@app.command()
... | 2,017 | 813 |
import torch
import torch.nn as nn
from torch.hub import load_state_dict_from_url
class VGG(nn.Module):
def __init__(self, features, pretrained):
super(VGG, self).__init__()
self.features = features
if not pretrained:
self._initialize_weights()
def _initialize_weights(sel... | 1,655 | 640 |
from portfolio.models import Transaction, Security, Price, Account
from portfolio.models import PriceTracker
from django.contrib import admin
admin.site.register(Transaction)
admin.site.register(Security)
admin.site.register(Price)
admin.site.register(PriceTracker)
admin.site.register(Account)
| 296 | 81 |
import os
import shutil
class FileCache(object):
def __init__(self, cache_dir):
self.cache_dir = cache_dir + "/"
if not os.path.exists(self.cache_dir):
os.makedirs(self.cache_dir)
def write_cache(self, query, suggestions):
filename = self.cache_dir + query.replace(" ", "-... | 1,295 | 382 |
""" The components module has all optical components that are used in optics
"""
class Mirror:
def __init__(self,):
pass
class Lense:
def __init__(self,):
pass
class Mediam:
def __init__(self,):
pass
class BeamSpliter:
def __init__(self,):
... | 391 | 130 |
from twisted.internet.defer import succeed
from twisted.internet.task import Clock
from twisted.trial.unittest import TestCase
from txraft import Entry, RaftNode, MockRPC, STATE
from txraft.commands import AppendEntriesCommand, RequestVotesCommand
class MockStoreDontUse(object):
def __init__(self, entries=None):... | 10,915 | 3,487 |
import os, sys
sys.path.append(os.path.expanduser("~/workspace/"))
from pyutils.common import *
def load_fe_metrics(ifilepath):
n_byte_partial_miss, n_req_partial_miss = 0, 0
n_byte_push_chunk, n_byte_chunk_hit, n_req_chunk_hit, n_byte_ICP_chunk = 0, 0, 0, 0
n_req_ICP_chunk, n_req_skip_chunk = 0, 0
... | 6,867 | 2,785 |
"""
Django settings for ToDo project.
Generated by 'django-admin startproject' using Django 1.11.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# ... | 4,116 | 1,533 |
from . import (
canopy,
evapotranspiration,
radiation,
snow,
soil,
)
| 89 | 34 |
from django.urls import path
from django_security_headers_example.core.views import LandingPageView
urlpatterns = [
path("", view=LandingPageView.as_view(), name="landing_page"),
]
| 188 | 60 |
from __future__ import absolute_import
import mock
import pytest
import pandas as pd
from collections import OrderedDict
from sagemaker.analytics import ExperimentAnalytics
@pytest.fixture
def mock_session():
return mock.Mock()
def trial_component(trial_component_name):
return {
"TrialComponentNa... | 14,071 | 4,589 |
# Generated by Django 2.1.7 on 2019-04-04 12:15
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('organizational_area', '0017_organizationalstructure_slug'),
mig... | 14,244 | 4,039 |
# coding:utf-8
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.nn.utils import clip_grad_norm_
from torch.utils.data import DataLoader
from tqdm import tqdm
import numpy as np
import math
import re
import sys
from Vocab import Vocab
from Dataset import Dataset
from RNN_RNN import RNN_R... | 10,325 | 3,904 |
import os
from random import shuffle
import pascalvoc_to_yolo
def generate_yolo_format_data(dataset_type, annotation_directory, image_id_directory, train_data_fraction, use_validation_experiments, image_data_directory, class_names_file, train_mode):
get_split_data(image_id_directory, train_data_fraction, use_validat... | 3,512 | 1,345 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-05-18 21:36
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('books', '0001_initial'),
]
operations = [
... | 547 | 193 |
#!/usr/bin/python3
import os
import sys
import syslog # FIXME: use systemd.journal.send()?
import gi
gi.require_version('Notify', '0.7')
import gi.repository.Notify # noqa: E402
__doc__ = """ an ersatz xterm that says "No!" and quits """
# Tell the central server.
# FIXME: ends up in user journ... | 1,385 | 453 |