text string | size int64 | token_count int64 |
|---|---|---|
__author__ = 'wcong'
import json
import datetime
class JSON(json.JSONEncoder):
def default(self, o):
o_type = type(o)
if o_type == datetime.datetime:
return o.strftime('%Y-%m-%d %H:%M:%S')
elif o_type == datetime.date:
return o.strftime('%Y-%m-%d')
elif has... | 410 | 138 |
import unittest
import json
from run import app
from app.api.V2.views.product_view import Product
class ProductstestCase(unittest.TestCase):
def setUp(self):
"""will be called before every test"""
self.client = app.test_client
self.product = {
"product_name" : "pro... | 2,234 | 601 |
# ServiceSchema.py
from __future__ import print_function
from __future__ import absolute_import
import blpapi
import time
from optparse import OptionParser
TOKEN_SUCCESS = blpapi.Name("TokenGenerationSuccess")
TOKEN_FAILURE = blpapi.Name("TokenGenerationFailure")
AUTHORIZATION_SUCCESS = blpapi.Name("AuthorizationSucc... | 12,008 | 3,549 |
#!/usr/bin/python2
"""
e3_tests.py
Test code for e3.py: pag 1639
e3 is used to generate Kc. The test cases assumes that COF = ACO and ACO aro
provided.
Ar and Ar_prime uses SAFER+
We use https://github.com/aer0s/python-mcrypt that is ONLY compatible with
python2.
"""
from sys import exit
from e3 import *
log.setL... | 15,931 | 8,493 |
import cv2,imutils, socket
import time
import threading
import time
import uuid
import logging, os
from functools import partial
from numpy import double
import requests
import json
import sys
import configparser
####### CONFIG PARAMS
#CONFIGSERVERIP = '127.0.0.1'
#CONFIGSERVERPORT = 9997
#logging.basicConfig(filena... | 16,033 | 4,882 |
from playsound import playsound
import sys
playsound(sys.argv[1])
| 71 | 26 |
pytest_plugins = [
'xchg.tests.data',
]
| 43 | 21 |
#!/usr/bin/env python3
"""
Utility for ChEBI SOAP API.
* https://www.ebi.ac.uk/chebi/webServices.do
"""
###
import sys,os,re,json,argparse,time,logging
import pandas as pd
#
from .. import chebi
#
##############################################################################
if __name__=='__main__':
epilog="Example ... | 2,303 | 853 |
import logging
import os
import sys
from collections import deque
from pickle import Pickler, Unpickler
from random import shuffle
from time import perf_counter
from othello.OthelloPlayers import *
import wandb
import numpy as np
from tqdm import tqdm
from Arena import Arena
from MCTS import MCTS
log = logging.getLo... | 9,793 | 2,890 |
'''
Extract the protocol information from the VIA headers and store it in a log file for later verification.
'''
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright o... | 1,351 | 430 |
"""
Compute the overall accuracy of a confusion matrix
"""
from __future__ import print_function
import sys
from optparse import OptionParser
import numpy as np
import cpa.util
from cpa.profiling.confusion import confusion_matrix, load_confusion
parser = OptionParser("usage: %prog [options] CONFUSION")
parser.add_opt... | 978 | 321 |
#!/usr/bin/env python
import rospy
from flexbe_core import EventState, Logger
from flexbe_core.proxy import ProxyActionClient
from control_msgs.msg import *
from trajectory_msgs.msg import *
"""
Created on 05/18/2015
@author: Spyros Maniatopoulos
"""
class GotoSingleArmJointConfigState(EventState):
"""
Directly... | 4,813 | 1,836 |
"""A wrapper 'hub' for the Litter-Robot API and base entity for common attributes."""
from datetime import time, timedelta
import logging
from types import MethodType
from typing import Any, Optional
from pylitterbot import Account, Robot
from pylitterbot.exceptions import LitterRobotException, LitterRobotLoginExcepti... | 4,008 | 1,177 |
#!/usr/bin/env python3
from hashlib import sha256
import hmac
import binascii
from collections import namedtuple
Point = namedtuple("Point", "x y")
#E : y 2 + a 1 xy + a 3 y = x 3 + a 2 x 2 + a 4 x + a 6
Curve = namedtuple("Curve", "a1 a3 a2 a4 a6")
def CurveToString(curve):
out = "y2"
if curve.a1:
i... | 41,824 | 21,939 |
from __future__ import print_function
import sublime
import sublime_plugin
import re
import sys
try:
from latextools_utils import is_bib_buffer, is_biblatex_buffer
except ImportError:
from .latextools_utils import is_bib_buffer, is_biblatex_buffer
if sys.version_info > (3, 0):
strbase = str
else:
st... | 4,848 | 1,729 |
# Generated by Django 3.1.1 on 2020-09-09 15:47
from django.db import migrations, models
import django.db.models.deletion
import django_extensions.db.fields
class Migration(migrations.Migration):
dependencies = [
('stock', '0004_auto_20200908_1407'),
]
operations = [
migrations.CreateMo... | 4,652 | 1,322 |
from django.conf.urls import url
from webhookhandler import views
urlpatterns = [
url(r'^$', views.webhook, name='webhook'),
] | 131 | 44 |
import pytest
import numpy as np
from covid19sim.distribution_normalization.dist_utils import lp_solve_wasserstein, lp_solution_to_transport_plan,\
get_rec_level_transition_matrix
def test_lp_solve_wasserstein():
dist_0 = np.array([0.8, 0.0, 0.0, 0.2])
dist_1 = np.array([0.4, 0.2, 0.3, 0.1])
expecte... | 1,585 | 790 |
# -*- coding: utf-8 -*-
"""
Created on Tues Aug 21 11:42:00 2018
2520 is the smallest number that can be divided by each of the numbers
from 1 to 10 without any remainder.
Problem: What is the smallest positive number that is evenly divisible by all
of the numbers from 1 to 20?
Answer: 232792560
Program c... | 1,018 | 387 |
from jinja2 import Markup
from .routes import Routes
class RoutesGenerator(object):
def generate(self, group=None, nonce=""):
payload = Routes(group).to_json()
return self._generate_base_js(payload, nonce)
def generate_for_file(self, group=None):
"""Generate method used by command to ... | 887 | 282 |
import numpy as np
from utils import coco_tools
class CocoEvalidation():
def __init__(self, groundtruth_boxes,groundtruth_classes,groundtruth_valids,class_names):
self.groundtruth_boxes = groundtruth_boxes
self.groundtruth_classes = groundtruth_classes
self.groundtruth_valids = groundtruth... | 3,710 | 1,177 |
import inspect
class Map:
map = {}
def __init_subclass__(cls, **kwargs):
Map.map = cls.map
@staticmethod
def harvest_map():
return Map.map
class Model:
nodes = []
def __init_subclass__(cls, **kwargs):
Model.nodes.append(Model.harvest_attr(cls))
... | 847 | 267 |
import operator
action = {
"+" : operator.add,
"-" : operator.sub,
"/" : operator.truediv,
"*" : operator.mul,
"**" : pow
}
num1 = int(input("Enter the num1 value : "))
num2 = int(input("Enter the num2 value : "))
operation = raw_input("Enter the operation : ")
print("The ans is", (action[operat... | 337 | 120 |
r"""This module provides utilities for computing the grid for contours of a
function reconstruction plot.
Required ingredients:
* sampled posterior probability distribution :math:`P(\theta)`
* independent variable :math:`x`
* dependent variable :math:`y`
* functional form :math:`y = f(x;\th... | 19,324 | 6,096 |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: model_pb2.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _ref... | 4,711 | 1,791 |
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import *
import win32gui
import sys
import json
import get_hwnd
import get_time
f = open('setting.json', encoding='utf-8')
setting_data = json.loads(f.read())
# 根据title截图
def prtsc(title):
hwnd = win32gui.FindWindow(None, title)
app = QApplication(sys... | 598 | 238 |
# Copyright 2019 VMware, 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
#
# Unless required by a... | 3,400 | 1,097 |
from flask import jsonify
from flask_login import login_required
from .podClass import Pod
from . import pod
@pod.route('/', methods=['GET', ])
@login_required
def pod_count():
ret = Pod().all_list()
online, offline = 0, 0
for i in ret.items:
item = i.status.container_statuses[-1]
if item.... | 745 | 259 |
# -*- coding: utf-8 -*-
# pylint: disable=expression-not-assigned,line-too-long,missing-module-docstring
import sys
from kohtaaminen.cli import app
if __name__ == '__main__':
sys.exit(app(prog_name='kohtaaminen')) # pragma: no cover
| 240 | 94 |
import xml.etree.ElementTree as ET
import os
ns = "{http://www.tei-c.org/ns/1.0}"
n = 0
for file in os.listdir('tei'):
# traverse files
if file.startswith('GF'):
path = os.path.join('tei', file)
# open file
for doc in os.listdir(path):
n += 1
print(n) # should ... | 1,058 | 311 |
# coding=utf-8
from scrapy import log
from scrapy.spider import BaseSpider
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.http import Request
from scrapy.selector import HtmlXPathSelector
from social_scrapper.items import OpportunityItem
import re
import string
class MecenovaSpider(BaseS... | 3,173 | 1,016 |
import asyncio
import diffusion.datatypes
from diffusion.features.control.session_trees.branch_mapping_table import (
BranchMappingTable,
)
server_url = "ws://localhost:8080"
principal = "control"
credentials = diffusion.Credentials("password")
path = "foo/bar"
topic_type = diffusion.datatypes.STRING
value = "bla... | 2,351 | 616 |
import random
import json
from numpy.lib.utils import source
import torch
import speech_recognition as sr
r = sr.Recognizer()
from .model import NeuralNetwork
from .nltk_utils import bag_of_words, tokenize
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
with open('./src/data/data.json', 'r') ... | 1,757 | 576 |
from collections import deque
V = int(input())
edge = [[] for _ in range(V)]
for _ in range(V):
u, _, *v = map(lambda x: int(x)-1, input().split())
edge[u] = v
dist = [-1] * V
dist[0] = 0
que = deque([0])
while len(que):
v = que.popleft()
for c in edge[v]:
if dist[c] == -1:
dist[c] ... | 407 | 167 |
import os.path
import logging
from configparser import ConfigParser
from lib.args import Args
import lib.connection as Connection
__all__ = ['Config']
def getlist(self, section, option):
return [x.strip() for x in self.get(section, option).split(',')]
def fetchServerConfig(self):
log = logging.getLogger('C... | 1,350 | 451 |
def eggs(someParameter):
someParameter.append('hello')
spam = [1,2,3]
eggs(spam)
print(spam)
| 98 | 42 |
from django.db import models
class Chef(models.Model):
name=models.CharField(max_length=50)
position=models.CharField(max_length=50)
description=models.TextField()
photo=models.ImageField(upload_to='chef/')
class Meta:
verbose_name ='Chef'
verbose_name_plural='Chefs'
def __str... | 608 | 199 |
from distutils.core import setup
setup(
name="conjugate_prior",
packages=["conjugate_prior"],
install_requires=[
'setuptools',
'scipy',
'numpy',
'matplotlib',
],
long_description="https://github.com/urigoren/conjugate_prior/blob/master/README.md",
long_descriptio... | 740 | 244 |
import pandas as pd
import numpy as np
import unittest
import common_python.util.dataframe as dataframe
IGNORE_TEST = False
IS_PLOT = False
COL_A = 'a'
COL_B = 'b'
COL_C = 'c'
DF = pd.DataFrame({COL_A: range(3)})
DF[COL_B] = 10*DF[COL_A]
SIZE = 3
DFS = [DF for _ in range(SIZE)]
DF1 = pd.DataFrame({COL_A: range(SIZE),... | 1,674 | 678 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-09-22 09:06
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Create... | 7,412 | 2,026 |
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import noise
map = lambda n, start1, stop1, start2, stop2: ((n-start1)/(stop1-start1))*(stop2-start2)+start2
class PVector():
def __init__(self, _x, _y):
self.x = _x
self.y = _y
def add(self, v):
... | 1,327 | 528 |
import urllib3
class HttpRequest:
__http=None
def __init__(self):
self.__http = urllib3.PoolManager()
def post(self,url,data={},headers={}):
self.__http.request('POST',url,data,headers)
def get(self,url,headers={}):
self.__http.request('get',url,{},headers) | 305 | 106 |
import time
import random
import selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException
def yout... | 6,421 | 2,105 |
import os
import sys
import click
import pathlib
from subprocess import check_call, PIPE, STDOUT
from utils.cert import openssl_installed
from utils.misc import get_realpath
gen_tls_script = pathlib.Path(__file__).parent.parent.joinpath('scripts/gencert.sh').absolute()
@click.command()
@click.option('-p', '--path', ... | 962 | 322 |
# kargs example
print('Demonstrating how kargs works in functions')
def f(**kargs):
# prints dict
print ('\nkargs =',kargs)
# raises exception
# equivalent to calling print(a=1,b=2) order of arguments based on dict
d = dict(a=1,b=2)
print (**d)
#Call successfully (watch what i... | 369 | 140 |
from UdonPie import System
from UdonPie import UnityEngine
from UdonPie.Undefined import *
class MatchTargetWeightMask:
def __new__(cls, arg1=None):
'''
:returns: MatchTargetWeightMask
:rtype: UnityEngine.MatchTargetWeightMask
'''
pass
@staticmethod
def ctor(arg1, ... | 1,795 | 520 |
"""
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merg... | 11,572 | 3,323 |
# Copyright 2021, Peter Birch, mailto:peter@lightlogic.co.uk
#
# 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... | 3,222 | 925 |
import uuid
def new_uid():
"""
Generate a new uid.
"""
return uuid.uuid4()
def get_owner():
"""
dummy stub for now, will eventually
reliably/securely(?) determine the owner somehow.
"""
return "skinner"
def run_on_empty(func, arg_list, arg_dict, key, **kwargs):
"""
Che... | 1,111 | 347 |
from .new_reader import NewReader
from .predictor import Predictor | 67 | 19 |
import sys
from .lib import parse_input
def main():
print()
if __name__ == '__main__':
main()
| 107 | 40 |
import numpy as np
from scipy.special import logsumexp
from scipy.special.basic import psi
class MACEWorker():
# Worker model: MACE-like spammer model --------------------------------------------------------------------------------
# alpha[0,:] and alpha[1,:] are parameters for the spamming probability
#... | 8,871 | 3,433 |
import numpy as np
import argparse
import imutils
import time
import cv2
from mss import mss
COLORS = open("RoadSeg/seg-colors.txt").read().strip().split("\n")
COLORS = [np.array(c.split(",")).astype("int") for c in COLORS]
COLORS = np.array(COLORS, dtype="uint8")
net = cv2.dnn.readNet("RoadSeg/seg-model.net")
#读取配... | 2,069 | 988 |
import logging
from homeassistant import config_entries
from homeassistant.const import ATTR_ATTRIBUTION
from homeassistant.components.switch import SwitchEntity, DEVICE_CLASS_SWITCH
from . import SleepIQDataUpdateCoordinator, SleepIQDevice
from .const import ATTRIBUTION_TEXT, DOMAIN
_LOGGER = logging.getLogger(__nam... | 6,229 | 1,903 |
from aws_cdk import core as cdk
# For consistency with other languages, `cdk` is the preferred import name for
# the CDK's core module. The following line also imports it as `core` for use
# with examples from the CDK Developer's Guide, which are in the process of
# being updated to use `cdk`. You may delete this im... | 9,711 | 2,583 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-12-04 00:00
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('intake', '0030_add_visitor_model'),
]
operations = [
migrations.AlterModelOptions(
... | 480 | 162 |
#!/usr/bin/env python3
# read PMS3001 data from the serial port. timestamp each line when it
# arrives. batch into 30-record chunks and insert all records into the
# database. also write json-formatted records to stdout.
import aqi
import argparse
import datetime
import json
import psycopg2
import psycopg2.extras
imp... | 2,356 | 834 |
#!/usr/bin/python3
import matplotlib.pyplot as plt
x = [0, 1, 2, 3]
y = [0, 1, 4, 9]
fig, ax = plt.subplots()
fig.suptitle("simple")
ax.plot(x, y, "r")
plt.show() | 165 | 86 |
import re
from bs4 import BeautifulSoup
from app.config.setting import DEFAULT_PROBLEM_RATING
from app.libs.spider_http import SpiderHttp
from app.spiders.base_spider import BaseSpider
class NowcoderSpider(BaseSpider):
def get_user_info(self, oj_username, accept_problems):
username = oj_username.oj_user... | 2,804 | 899 |
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("core", "0112_sourcelocation_last_imported_at"),
]
operations = [
migrations.RunSQL(
sql="update source_location set last_imported_at = created_at",
reverse_sql=migrations.Ru... | 347 | 109 |
import numpy as np
import pylab as pl
from scipy import interpolate
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi+np.pi/4, 10)
y = np.sin(x)
x_new = np.linspace(0, 2*np.pi+np.pi/4, 100)
#f_linear = interpolate.interp1d(x, y)
tck = interpolate.splrep(x, y) # 原始点(xi,yi)
y_bspline = interpolate.splev(x_ne... | 556 | 312 |
"""
A small frog wants to get to the other side of a river. The frog is initially located at one bank of the river (position −1) and wants to get to the other bank (position N). The frog can jump over any distance F(K), where F(K) is the K-th Fibonacci number. Luckily, there are many leaves on the river, and the frog c... | 2,539 | 899 |
# Generated by Django 2.2.14 on 2020-07-09 03:16
from django.db import migrations, models
import olympia.hero.models
class Migration(migrations.Migration):
dependencies = [
('hero', '0011_auto_20200624_1809'),
]
operations = [
migrations.AlterField(
model_name='primaryheroim... | 499 | 180 |
"""
Python bindings for
`Drake: Model-Based Design and Verification for Robotics
<https://drake.mit.edu/>`_.
This Python API documentation is a work in progress. Most of it is generated
automatically from the C++ API documentation, and thus may have some
C++-specific artifacts. For general overview and API documentati... | 5,512 | 1,793 |
from datetime import date, timedelta
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView
from apps.goods.models import GoodsVisitCount
from apps.meiduo_admin.serializers.statistical import GoodsVisitCountSerialzer
from apps.orders.m... | 3,794 | 1,466 |
"""
https://towardsdatascience.com/custom-transformers-and-ml-data-pipelines-with-python-20ea2a7adb65
Download the dataset from Kaggle,
https://www.kaggle.com/harlfoxem/housesalesprediction?select=kc_house_data.csv
and place it in the 'data' directory of this repo.
"""
from sklearn.base import BaseEstimator, Trans... | 5,732 | 1,766 |
from py_models_parser.core import dump_result, parse, parse_from_file
__all__ = ["parse", "parse_from_file", "dump_result"]
| 125 | 43 |
from abc import ABC, abstractmethod
from functools import lru_cache, cached_property
from itertools import product, combinations
from statistics import mean
from typing import (
final, Final, Iterable, Dict, Collection, Optional, Tuple, Sequence
)
from nltk.corpus import wordnet
from pymagnitude import Magnitude
... | 5,965 | 1,834 |
import numpy as np
def vec_reg_linear_grad(x, y,theta, lambda_):
m = x.shape[0]
x_t = x.transpose()
error = x.dot(theta) - y
nabela = x_t.dot(error) / m
# print(nabela)
nabela[1:] = nabela[1:] + theta[1:] * (lambda_ / m)
return nabela
if __name__ == "__main__":
X = np.array([
... | 590 | 300 |
"""
dolbyio_rest_apis.communications.monitor.models
~~~~~~~~~~~~~~~
This module contains the models used by the Dolby.io APIs.
"""
from dolbyio_rest_apis.core.helpers import get_value_or_default, in_and_not_none
from typing import List
class PagedResponse(dict):
"""Representation of a paged response."""
def... | 12,032 | 3,798 |
#!/usr/bin/env python3.7
# -*- coding: utf-8 -*-
"""
Test the coverlovin2 project using pytest.
Technique and recommendations taken from https://docs.pytest.org/en/latest/
Parts of this file follow breaks formatting conventions. Allowed since this is
test code and since long lines of repetitive test cases deserve ex... | 51,094 | 17,001 |
#! /usr/bin/python
"""square.py -- Make some noise about a square.
"""
class Square:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
my_square = Square(5, 2)
print my_square.area()
| 267 | 100 |
from collections import UserDict
class SuperDictOf(UserDict):
def __eq__(self, other):
if not isinstance(other, dict):
return False
for k, v in self.items():
if k not in other or v != other[k]:
return False
return True
def __repr__(self):
... | 368 | 106 |
#
# Copyright (c) 2010 Brian E. Granger
#
# This file is part of pyzmq.
#
# pyzmq is free software; you can redistribute it and/or modify it under
# the terms of the Lesser GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option)... | 7,740 | 2,722 |
import shutil
import tempfile
import warnings
from os.path import dirname, join, realpath
_filenames = [
"davies_pvalue.npz",
"optimal_davies_pvalue.npz",
"danilo_nan.npz",
"bound.npz",
"inf.npz",
]
class data_file(object):
def __init__(self, filenames):
global _filenames
sel... | 1,654 | 504 |
import datetime
from Domain.Entities.Piece import Color
class Game:
board = None
piece_factory = None
start_date = None
end_date = None
pieces_white = None
pieces_black = None
captured_white = None
captured_black = None
finished = False
winner = None
turn = None
curre... | 1,738 | 535 |
import numpy as np
import cv2
import random
import os
path = "./Concept_Dataset_script_generated/"
def make_geometric_objects(path, number, geom):
path = path + geom + "/"
if not os.path.exists(path):
os.makedirs(path)
for i in range(number):
image = np.ones((240,240,3), np.uint... | 2,630 | 978 |
from src import *
inputPath = 'data/daily/'
outputPath = 'data/monthly/'
formatter = FormatData()
formatter.getMonthlyData(inputPath, outputPath)
| 149 | 51 |
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
from models.model import Model
class RfClass(Model):
def __init__(self, model_params):
super().__init__(model_params,'RF Classifier')
def build_model(self):
max_depth = self.model_params['max_depth']
n_estimators =... | 469 | 149 |
#!/usr/bin/python
# (c) 2006 Jim Tilander
import sys
import os
import string
import re
import base64
import zlib
P4EXE = 'p4'
NEWFILEPATTERN = re.compile( r'==== ([^#]+)#([\d]+) - (.+) ====(.*)$' )
MARKER = '================'
USAGE = """Usage: p4diff <outputfile> [options]
Produces input to p4patch
O... | 3,742 | 1,306 |
"""Copyright 2014 Cyrus Dasadia
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, software
distr... | 4,329 | 1,363 |
#!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that msvs_configuration_attributes and
msbuild_configuration_attributes are applied by using
them to set the OutputDir... | 756 | 303 |
NATIVE = 'XRP'
ALPHABET = 'rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'
| 87 | 62 |
"""
# PyPortal referee stopwatch for figure skating competitions
# Author(s): Don Korte
# Module: code.py is mainline initialization and master loop
#
# github: https://github.com/dnkorte/skating_stopwatch.git
#
# MIT License
#
# Copyright (c) 2019 Don Korte
#
# Permission is hereby granted, free of charge, to any ... | 8,016 | 2,561 |
import pyspeckit as psk
from pyspeckit.spectrum import models
from astropy.table import Table
from spectral_cube import SpectralCube
import numpy as np
import matplotlib.pyplot as plt
import despotic
import pyspeckit.spectrum.readers.read_class
import os
import shutil
if not os.path.exists('ph2cogrid.fits'):
if n... | 2,746 | 921 |
from flask import Flask, request, abort, jsonify
app = Flask(__name__)
@app.route('/', methods=['POST'])
def upload():
if not request.is_json:
abort(400)
content = request.get_json()
security_groups = set()
for module in content['modules']:
resources = module['resources']
sgs = [x... | 730 | 254 |
import pyrebase
import atexit
from neurosity.config import PyRebase
class neurosity_sdk:
def __init__(self, options):
if ("device_id" not in options):
raise ValueError("Neurosity SDK: A device ID is required to use the SDK")
options.setdefault("environment", "production")
self.... | 7,537 | 2,179 |
"""
Blackbody temperature calculations
"""
import numpy as np
import ChiantiPy.tools.constants as const
class blackStar:
"""
Calculate blackbody radiation
Parameters
----------
temperature : `~numpy.ndarray`
Temperature in Kelvin
radius : `~numpy.ndarray`
Stellar radius in cm... | 2,624 | 795 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# pylint: disable=missing-module-docstring
import json
import logging
import datetime
try:
HAS_TABULATE = True
import tabulate
except ImportError:
HAS_TABULATE = False
try:
from dnac_rest_client import DnacRestClient
except ImportError:
from ansible_collection... | 6,854 | 2,444 |
# -*- coding: utf-8 -*-
"""
part-of-speech tagger
__author__ = 'Jamie (jamie.lim@kakaocorp.com)'
__copyright__ = 'Copyright (C) 2019-, Kakao Corp. All rights reserved.'
"""
###########
# imports #
###########
from argparse import Namespace
import json
import logging
import re
import torch.nn.functional as F
from ... | 2,460 | 868 |
'''
List number of reviews for all Coffee Shops.
'''
def query_all_shop_reviews(cursor, cnx):
query = "SELECT reviews.shopID, coffee_shops.name, COUNT(*)FROM reviews JOIN coffee_shops ON reviews.shopID = coffee_shops.id GROUP BY shopID;"
cursor.execute(query)
myresult = cursor.fetchall()
for result ... | 2,614 | 870 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# lib/eapeak/parse.py
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of... | 41,128 | 17,955 |
from re import U
from sys import unraisablehook
from flask import Flask, g,render_template,flash,redirect,url_for,session,logging,request
from flask_mysqldb import MySQL
from wtforms import Form,StringField,TextAreaField,PasswordField,validators
from passlib.hash import sha256_crypt
from functools import wraps
... | 50,422 | 19,297 |
import argparse
import logging
import os.path
import numpy as np
import pandas as pd
import patsy
_logger = logging.getLogger(__name__)
_basedir = os.path.abspath(os.path.dirname(__file__))
def create(data_path):
target_fname = os.path.join(data_path, "customer.parquet")
if os.path.exists(target_fname):
... | 6,116 | 2,482 |
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import datetime
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import pandas as pd
from pollution import start_date, start_date_string, end_date, end_date_string, parameters
from pollution import location_to_c... | 1,745 | 610 |
import django
from os import path
SECRET_KEY = 'not secret'
INSTALLED_APPS = ('response_timeout', 'test')
TEMPLATE_DEBUG = DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'response_timeout.db',
},
}
ROOT_URLCONF = 'test.urls'
# Testing
if django.VERSIO... | 1,015 | 396 |
from strawberry import mutation
from gql.services.shopper import ShopperServices
from gql.utils.authentication.shopper import ShopperAuth
from gql.types.order import OrderStatusCode
from asgiref.sync import sync_to_async
services = ShopperServices()
class ShopperMutation:
@mutation
@sync_to_async
def lo... | 673 | 202 |
#
# Python GUI - File selection dialogs - Gtk
#
import os
from gi.repository import Gtk
from GUI.Files import FileRef
from GUI.AlertFunctions import confirm
from GUI.Applications import application
#------------------------------------------------------------------
class _FileDialog(Gtk.FileChooserDialog):
def _... | 4,648 | 1,753 |
{% extends "degree.py" %}
{%- block checkArgs %}
{%- if fn.alt_args %}
{{ macro.argCheck(fn.alt_args) }}
{% endif %}
{%- if fn.args %}
{{ macro.argCheck(fn.args) }}
{% endif %}
{%- if fn.opts %}
{{ macro.optCheck() }}
{% endif %}
{%- endblock %} | 318 | 111 |
from __future__ import absolute_import
from .ContClass import ContClass
| 73 | 20 |