text string | size int64 | token_count int64 |
|---|---|---|
from copy import deepcopy
from .base import MetricsLayerBase, SQLReplacement
from .field import Field
class Join(MetricsLayerBase, SQLReplacement):
def __init__(self, definition: dict = {}, explore=None, project=None) -> None:
self.project = project
self.explore = explore
if definition.ge... | 4,470 | 1,286 |
def loopy(items):
# Code goes here
for item in items:
if item[0] == "a":
continue
else:
print(item)
| 136 | 45 |
# Generated by Django 2.1 on 2018-08-15 17:28
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='SnakeName',
fields=[
('name', models.CharFiel... | 473 | 149 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Utility . """
from typing import List, Union
class Matrix:
""" Represents mathematical matrix and its operations"""
def __init__(self, values: List[List[Union[int, float]]]):
if not (
isinstance(values, List) and
... | 5,404 | 1,594 |
from django.shortcuts import render, redirect
from documentapp.models import document
from documentapp.models import functionModel
from documentapp.form import PostForm
from django.contrib.auth import authenticate
from django.contrib import auth
from django.http import HttpResponse
from django.contrib.auth.models impo... | 3,639 | 1,571 |
"""Smart card reader monitoring classes.
ReaderObserver is a base class for objects that are to be notified
upon smartcard reader insertion/removal.
ReaderMonitor is a singleton object notifying registered ReaderObservers
upon reader insertion/removal.
__author__ = "http://www.gemalto.com"
Copyright 2001-2012 gemal... | 8,500 | 2,185 |
from lamarepy import geometry as g
from show_q import show_q
| 61 | 20 |
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='jira-cloud-python',
version='1.0.0',
description='API wrapper for Jira Cloud written in Python',
long_description=read('README.md'),
long_description_con... | 559 | 182 |
from django.db import models
# Create your models here.
class WeatherForecastDay(models.Model):
country_code = models.CharField(max_length=8)
for_day = models.DateField()
average_temp_c = models.DecimalField(max_digits=5, decimal_places=2)
# created_at = models.DateTimeField(auto_now_add=True
cla... | 460 | 154 |
#-*- coding: utf-8 -*-
#!/usr/bin/python3
#!/Author : Gibartes
from moduleInterface.defines import *
from moduleInterface.interface import ModuleComponentInterface
#from defines import *
#from interface import ModuleComponentInterface
from structureReader import structureReader as sr
#import _struct... | 8,150 | 2,740 |
from PyQt5.QtWidgets import QWidget, QVBoxLayout
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import numpy as np
from scipy.interpolate import griddata
class MplPlotWidget(QWidget):
def __init__(self, parent... | 1,037 | 364 |
#
# PySNMP MIB module ASCEND-MIBIPXRT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASCEND-MIBIPXRT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:11:35 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | 5,982 | 2,351 |
import csv
from ij import ImagePlus, CompositeImage, IJ, gui
from ij.plugin import ImagesToStack
#Prepare Stack of 20x Images for a given OR WT/Ctrl/cKO
#Auto-levels each panel (biology of interest here is overlap & correlation red/green, not absolute levels).
reader = csv.DictReader(open('/path/to/blinded/annotation... | 1,705 | 627 |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Unsupervised Cross-lingual Representation Learning at Scale
"""
import torch
from typing import List
from torch import nn
from fairseq.mod... | 6,385 | 2,067 |
import time, os
from jitpy import setup, extra_source
setup(os.environ['PYPY_HOME'])
from jitpy.wrapper import jittify
import numba, numpy
ARRAY_SIZE = 10000
NUMBER = 1000
def f(a, s):
for k in range(10):
for i in xrange(a.shape[0]):
s += a[i]
return s
def prepare_f():
return numpy.a... | 2,111 | 850 |
# Copyright (c) 2017, MD2K Center of Excellence
# - Nasir Ali <nasir.ali08@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above cop... | 5,189 | 1,680 |
import unittest
from furnishings import *
class TestFurnishings(unittest.TestCase):
def setUp(self):
self.home = []
self.home.append(Bed('Bedroom'))
self.home.append(Sofa('Living Room'))
self.home.append(Table('Bedroom'))
self.home_map = map_the_home(self.home)
... | 653 | 221 |
'''
给定一个非空字符串 s,最多删除一个字符。判断是否能成为回文字符串。
示例 1:
输入: "aba"
输出: True
示例 2:
输入: "abca"
输出: True
解释: 你可以删除c字符。
注意:
字符串只包含从 a-z 的小写字母。字符串的最大长度是50000。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-palindrome-ii
'''
class Solution:
def validPalindrome(self, s: str) -> bool:
i = 0
j = len(s) -... | 679 | 345 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 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 ownership. The ASF licenses this file
# to you under the Apache License... | 9,361 | 2,748 |
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and license terms.
#
# ## ### ##... | 4,629 | 1,519 |
# -*- coding: utf-8 -*-
import sys
import time
import httplib2
AUTO_RECONNECT_TIMES = 5
crawl_tips_json = {}
SERVER = 'http://api.cn.faceplusplus.com/'
category_Arts_Entertainment = ['Aquarium', 'Arcade', 'Art Gallery', 'Bowling Alley', 'Casino', 'Circus', 'Comedy Club',
'Concert Hall... | 18,875 | 5,651 |
from setuptools import setup, find_packages
requires = ['colorama']
NAME = 'py4slide'
VER = '0.0.1'
setup(
name=NAME,
version=VER,
description='slide application by python.',
author='Sonoko Mizuki',
url='http://mizuki.co/',
license='BSD',
install_requires=requires,
packages=[NAME]
)... | 321 | 120 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-12 18:03
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
atomic = False
dependencies = [
('alerts', '0005_populate_muzzle_hashes'),
]
operations = [
... | 623 | 201 |
import urlparse
import urlresolver
import sys
from urllib import urlencode
import xbmc, xbmcgui, xbmcaddon, xbmcplugin
import sys
base_url = sys.argv[0]
addon_handle = int(sys.argv[1])
STREAMING_SOURCES = ["speedvideo", "openload", "rapidcrypt", "vcrypt"]
def build_url(query):
return '{0}?{1}'.format(base_url, ur... | 1,852 | 628 |
# Generated by Django 2.2.12 on 2020-10-04 16:32
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rechorder', '0006_auto_20200906_0816'),
]
operations = [
migrations.AlterField(
mod... | 623 | 211 |
'''
Write a program to get a positive integer (n) and display the number patterns as the examples
below.
'''
n = int(input())
print(' 1')
for i in range(2, n+1):
print(f'{i} '*i)
| 183 | 66 |
##
# \file propagate_mask.py
# \brief Script to propagate an image mask using rigid registration
#
# \author Michael Ebner (michael.ebner@kcl.ac.uk)
# \date Aug 2019
#
import os
import numpy as np
import SimpleITK as sitk
import pysitk.python_helper as ph
import pysitk.simple_itk_helper as sitkh
impor... | 4,715 | 1,581 |
from setuptools import setup
setup(name='lpm_client',
version='0.1',
description='Client module for lpm',
url='http://github.com/h-friederich/lpm_client',
author='Hannes Friederich',
author_email='h.friederich@gmx.ch',
license='BSD',
packages=['lpm_client'],
zip_safe=Tru... | 323 | 110 |
#!/usr/bin/env python
from iris_sdk.models.base_resource import BaseData, BaseResourceSimpleList
from iris_sdk.models.data.full_numbers import FullNumbers
from iris_sdk.models.maps.completed_numbers import CompletedNumbersMap
class CompletedNumbers(CompletedNumbersMap, BaseData):
@property
def items(self):
... | 527 | 155 |
import numpy as np
import matplotlib.pyplot as plt
# bars: list of length number of bins, with each entry having its histogram value
# filename: file to save plot to (in .png format)
# minrange: minimum value of leftmost bin
# maxrange: maximum value of rightmost bin
def plotHisto(bars, filename, minrange=0.0, maxra... | 843 | 267 |
class ParameterError(Exception):
def __init__(self, device_name, parameter_name):
self.device_name = device_name
self.parameter_name = parameter_name
class ParameterAlreadyRegistered(ParameterError):
def __str__(self):
return "parameter ({} {}) is already registered".format(
... | 921 | 237 |
# Copyright 2021 Google Research. 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 law... | 3,244 | 1,096 |
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# Copyright (c) 2008-2020 pyglet contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the follo... | 3,679 | 1,421 |
import numpy as np
from .rnn import RNNLayer
D = 2.0
def softmax(x):
expx = np.exp(x-np.max(x, axis=-1, keepdims=True))
return expx/np.sum(expx, axis=-1, keepdims=True)
def attention(key, data, sharpness):
# ++++
# returns [mb, capacity]
return softmax(np.einsum("mcl,ml->mc", data, key)*sharp... | 8,435 | 4,349 |
# coding=utf-8
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
from pants.build_graph.aliased_target import AliasTarget
from pants.task.task import Task... | 1,869 | 558 |
import os
def mk_parent_dir(f_name):
if not os.path.isdir(os.path.dirname(f_name)):
os.makedirs(os.path.dirname(f_name))
| 135 | 57 |
class A:
def f(x):
return x
def g(y):
def h(z):
return x + y + z
h(y)
A()
A.f(1)
A.g(2)(3)
| 135 | 63 |
from manipulation.modules.example_module.example_module import ExampleModule
from utils.logger import Logger
import time
logger = Logger(__name__)
@logger.for_all_methods(True)
class ExampleModuleSimple(ExampleModule):
def execute(self, param: dict):
#input_df = param['input_df']
#df = self.vari... | 487 | 151 |
"""
The MIT License (MIT)
Copyright (c) 2021 Losant IoT, Inc.
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, me... | 27,529 | 7,634 |
"""
自己实现
梯度下降解决线性回归问题
"""
import numpy as np
import matplotlib.pyplot as plt
def costFunction(X, y, theta=[0, 0]):
"""
损失函数
"""
m = y.size
h = X.dot(theta)
J = 1.0 / (2 * m) * (np.sum(np.square(h - y)))
return J
def gradientDescent(X, y, theta=[0, 0], alpha=0.01, num_iters=... | 1,676 | 867 |
import os
import sys
import rawpy
import cv2
import time
def split_image(img, side=3):
images = []
for i in range(side):
for j in range(side):
temp = img[1024*i:1024*(i+1),1024*j:1024*(j+1),:]
images.append(temp)
return images
if __name__ == '__main__':
src_name = '... | 2,106 | 825 |
"""
Classes/functions for configuring the whylogs app
.. autodata:: ALL_SUPPORTED_FORMATS
"""
from logging import getLogger
from typing import List, Dict, Optional
# import typing
import yaml as yaml
from marshmallow import Schema, fields, post_load, validate
from whylogs.app.output_formats import SUPPORTED_OUTPUT_F... | 10,297 | 2,923 |
# Generated by Django 3.0.9 on 2020-10-15 16:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0163_device_security_profile'),
]
operations = [
migrations.AddField(
model_name='subevent',
name='las... | 420 | 142 |
import os
import xml.etree.ElementTree as ET
class Quality:
def __init__(self, cyclomatic_complexity, lines_of_code):
self.cyclomatic_complexity = cyclomatic_complexity
self.lines_of_code = lines_of_code
def set_variables(self):
self.pmd_report = './build/reports/pmd/main.xml'
... | 3,895 | 1,249 |
"""Functions that help you work with QMK keymaps.
"""
import os
import qmk.path
# The `keymap.c` template to use when a keyboard doesn't have its own
DEFAULT_KEYMAP_C = """#include QMK_KEYBOARD_H
/* THIS FILE WAS GENERATED!
*
* This file was generated by qmk-compile-json. You may or may not want to
* edit it dire... | 2,561 | 878 |
#
# 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
# ... | 1,101 | 300 |
#
# PySNMP MIB module NET-SNMP-EXAMPLES-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NET-SNMP-EXAMPLES-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:08:14 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... | 7,348 | 3,199 |
# Copyright 2013 Donald Stufft and individual contributors
#
# 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... | 8,025 | 2,624 |
password = 'swordfish'
if password == 'swordfish':
print('acces granted')
else:
print('acces denied') | 109 | 36 |
#!/usr/bin/env python
import pycondor
if __name__ == "__main__":
# Declare the error, output, log, and submit directories for Condor Job
error = 'condor/error'
output = 'condor/output'
log = 'condor/log'
submit = 'condor/submit'
# Setting up first PyCondor Job
job1 = pycondor.Job('exampl... | 1,791 | 619 |
import numpy as np
from ._base import Criterion
class MSECriterion(Criterion):
"""Mean Square Error Criterion."""
def forward(self, pred: np.ndarray, y: np.ndarray) -> float:
loss = 0.5 * np.power(y - pred, 2)
return loss
def backward(self, pred: np.ndarray, y: np.ndarray) -> np.ndarray:... | 371 | 134 |
# Copyright 2019 Sebastian Kahl
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | 14,774 | 3,670 |
import numpy as np
arr = list()
for _ in range(int(input().split()[0])):
arr.append(list(map(int, input().split())))
arr = np.array(arr)
print(arr.transpose())
print(arr.flatten())
| 187 | 71 |
#################################################################################
# The Institute for the Design of Advanced Energy Systems Integrated Platform
# Framework (IDAES IP) was produced under the DOE Institute for the
# Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021
# by the softwar... | 14,119 | 4,483 |
#!/usr/bin/python
import subprocess
ps = subprocess.Popen(('ls', '-l'), stdout=subprocess.PIPE)
output = subprocess.check_output(('grep', 'subprocess-pipe.py'), stdin=ps.stdout)
ps.wait()
print("success")
print(output)
| 222 | 81 |
from src.pilot.Odometry import Odometry
import unittest
class OdometryTestCase(unittest.TestCase):
def setUp(self):
self.odometry = Odometry()
self.motor_position = (-259, 259)
pass
def test_calc_pos(self):
position = self.odometry.read_in(self.motor_position)
print(po... | 390 | 138 |
import argparse
import rssi
import numpy as np
"""
example usage
"""
def main(args):
"""
:param args: arguements given by the user
arguments for main:
Required:
-nwi: the name of your WIFI interface.
For MAC users, use this terminal command: system_profiler SPNetworkDat... | 2,146 | 624 |
from datetime import datetime
import os
from fastai.vision import models
experiment_name = 'original_w_negative'
experiment_description = """Using the original dataset including
the null observations"""
batch_size = 256
model_name = 'resnet18'
image_size = 256
model = models.resnet18
data... | 2,089 | 714 |
#!/usr/bin/env python
import rospy
from std_srvs.srv import Trigger, TriggerRequest
from std_msgs.msg import Bool, Int32, Float64
from move_base_msgs.msg import MoveBaseActionGoal
from geometry_msgs.msg import Point, Quaternion
from tf.transformations import quaternion_from_euler
# goal_x, goal_y = 11.8154, 9.47028
... | 1,349 | 541 |
from django.shortcuts import render
from django.http import HttpResponse
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse, HttpRequest
import core.online_file_manager as ofm
import json
import startup
import traceback
# Create your views here.
... | 1,130 | 315 |
import pickle
import torch
import torch.optim as optim
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from dynamic_disease_network_ddp import data_loader
from dynamic_disease_network_ddp import models
import pandas as pd
ncsr = pd.read_csv('../justage_vars_init.csv', index_col=0)
pkl = open('../... | 3,632 | 1,474 |
import json
import re
import xml.etree.ElementTree as ETree
from averell.utils import TEI_NAMESPACE as NS
from averell.utils import XML_NS
ECEP_NS = "{http://www.eighteenthcenturypoetry.org/ns}"
def get_poem_info(xml_file, lines_info, authors):
"""Poem parser for 'ECPA corpus'.
We read the data and find ele... | 5,295 | 1,683 |
from distutils.core import setup
setup(
name='Flask mrest',
version='0.0.1',
packages=['flask_mrest'],
url='https://bitbucket.org/deginner/flask-mrest',
license='MIT',
author='deginner',
author_email='support@deginner.com',
description='An MREST server using Python 2.7 and Flask'
)
| 316 | 110 |
class ggg:
def __init__(self, mail, passw):
self.mail = mail
self.passw = passw | 99 | 34 |
# Generated by Django 2.2.10 on 2020-02-27 16:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('chat', '0003_historyrecord'),
]
operations = [
migrations.AddField(
model_name='room',
name='permission',
... | 416 | 140 |
import os
import string
import random
from optparse import OptionParser
from PreprocessorHLSL import PreprocessorException
from PreprocessorHLSL import Preprocessor
from LexicalAnalyzerHLSL import LexicalAnalyzer
from SyntaxAnalyzerHLSL import SyntaxAnalyzer
def stage_from_filename(filename):
if filename[-7:] == 'cs... | 5,850 | 2,274 |
'''
Compute all the 146 features
'''
# Libraries
import requests
import numpy as np
import pickle
import os
from feature_gen import get_nf1, get_nf2, get_nf3, get_nf4
from pka import get_pka
from Bf_rhpy import get_bf_rhpy
import os.path
# Take in PDB ID and residue ID. (Ex: 1b2l, 137, A, Output: Disulfide)
def get_... | 1,938 | 1,019 |
from arcade.gui import UIDummy
from arcade.gui.widgets import Rect
from arcade.gui.widgets.layout import UIGridLayout
def test_place_widget(window):
dummy1 = UIDummy(width=100, height=100)
dummy2 = UIDummy(width=100, height=100)
dummy3 = UIDummy(width=100, height=100)
dummy4 = UIDummy(width=100, heigh... | 2,914 | 1,262 |
# coding: utf-8
"""
TextMagic API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 2
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
... | 4,421 | 1,437 |
import frappe
class TallyImportGodownItems:
def __init__(self, value, ow):
self.overwrite = ow
self.process_node = value
self.process()
def process(self):
if not frappe.db.exists({"doctype":"Warehouse","warehouse_name": self.process_node['@NAME']}):
godown_d... | 465 | 150 |
#!/usr/bin/env python3
import time
def timer(func, *args):
start = time.clock()
for i in range(10000):
func(*args)
return time.clock() - start;
| 166 | 61 |
"""Test case prototypes that can be used in other projects.
Note that this file won't be executed on its own by pytest.
You need to define your own test cases that inherit from the ones defined here.
"""
import numpy as np
import pytest
from zquantum.core.interfaces.functions import FunctionWithGradient
from ..grad... | 4,217 | 1,319 |
import lit.formats
import shutil
import os
config.name = "Test suite"
config.test_format = lit.formats.ShTest(True)
config.suffixes = ['.cs', '.test', '.il']
config.test_source_root = os.path.dirname(__file__)
config.test_build_root = os.path.join(config.my_obj_root, 'integration-test')
config.substitutions.append(... | 1,272 | 459 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django
from django.contrib import admin
if django.VERSION < (2, 0):
from django.conf.urls import include, url as re_path
else:
from django.urls import include, re_path
from django.conf.urls.i18n import i18n_patterns
urlpatterns = []
urlp... | 467 | 178 |
"""
PYFER - Encrypt and Decrypt messages.
-------------------------------------
CRYPT module:
Classes
-------
Machine: encryption and decryption machine.
Class Methods:
init: creates a Pyfer Crypt Machine.
-
scramble: uses the Crypt Machine to encrypt a message.
-
unsc... | 9,450 | 2,722 |
from typing import Iterable, Tuple, Dict
import argparse
from transformers import AutoModelForMaskedLM, PreTrainedTokenizer, AutoTokenizer
from transformers.tokenization_utils import BatchEncoding
import torch
import csv
from tqdm import tqdm
def put_on_gpu(encoding: BatchEncoding, device: int) -> Dict[str, torch.Ten... | 5,639 | 1,904 |
#!/usr/bin/python3
"""
Search for Unicode 12.1 Descriptions
uni binary from: https://github.com/arp242/uni
"""
import sys
import re
import subprocess
import json
if len(sys.argv) >= 2:
query = sys.argv[1]
try:
out: str = subprocess.check_output(["./uni", "-q", "search", query]).decode()
ou... | 1,733 | 622 |
"""
The layout engine. This builds the prompt_toolkit layout.
"""
from typing import Callable, Iterable, List, Optional
from prompt_toolkit.application.current import get_app, get_app_or_none
from prompt_toolkit.buffer import Buffer
from prompt_toolkit.document import Document
from prompt_toolkit.filters import Condit... | 15,586 | 4,255 |
from django.db import models
import datetime
class CompletedTrip(models.Model):
trip_id = models.CharField(max_length=200)
vehicle_id = models.CharField(max_length=200)
direction = models.CharField(max_length=200)
route = models.CharField(max_length=200)
start_location = models.CharField(max_length=200)
end_loc... | 1,184 | 409 |
from flask import render_template,request,redirect,url_for, abort
from . import main
from ..models import User, Pitch, Category, Comment
from flask_login import login_required, current_user
from .forms import PitchForm, CommentForm, CategoryForm
from .. import db
#Views
@main.route('/')
def index():
catego... | 2,707 | 880 |
from _Framework.ControlSurfaceComponent import ControlSurfaceComponent
class AMTraCInfoScene(ControlSurfaceComponent):
__module__ = __name__
__doc__ = " AMTraC-Info Scene "
def __init__(self, parent, scene):
ControlSurfaceComponent.__init__(self)
self._parent = parent
self._scene ... | 795 | 247 |
# -*- coding: utf-8 -*-
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the t... | 2,541 | 808 |
# -*- coding: utf-8 -*-
# Copyright (c) 2020 Alexey Pechnikov. All rights reserved.
# https://orcid.org/0000-0001-9626-8615 (ORCID)
# pechnikov@mobigroup.ru (email)
# License: http://opensource.org/licenses/MIT
# process [multi]geometry
def _NCubeGeometryToPolyData(geometry, dem=None):
#from shapely.geometry.base ... | 12,945 | 4,211 |
from transform import four_point_transform
import numpy as np
import argparse
import cv2
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", help = "path to the image file")
ap.add_argument("-c", "--coords",
help = "comma seperated list of source point... | 962 | 299 |
class Solution(object):
def minWindow(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
if not (s and t):
return ""
left,right = 0,0
max_res_len,res_left_pos,res_right_pos = 2**31-1,0,0
dict_t = dict()
for i in t:
... | 1,377 | 453 |
import argparse
import requests
import os
import sys
import hashlib
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('--method', dest='method', required=True,
choices={'GET', 'POST', 'PUT', 'PATCH'})
parser.add_argument('--url', dest='url', required=True)
... | 5,852 | 1,693 |
"""A rule to unpack c locale from the debian package."""
def _impl(ctx):
ctx.actions.run(
executable = ctx.executable._extract,
arguments = [
ctx.file.deb.path,
ctx.outputs.tar.path,
],
inputs = [ctx.file.deb],
outputs = [ctx.outputs.tar],
)
loca... | 790 | 233 |
"""
Preprocess mcd (modis land cover) dataset.
MODIS land cover fractions
https://lpdaac.usgs.gov/product_search/?collections=Combined+MODIS&collections=Terra+MODIS&collections=Aqua+MODIS&view=list
In:
Spatial: 0.0083 deg
Out:
Spatial: 0.033 deg
Steps:
1) Harmonize
2) Regrid
"""
import os
import xarray as xr
im... | 2,094 | 908 |
import numpy as np
import pandas as pd
import json
from scipy.stats import ttest_ind
# Loads files provided their path
# ===============================
def load_data(path):#,index):
# Loads the data
with open(path) as f:
g = json.load(f)
# Converts json dataset from dictionary to dataframe
#p... | 3,618 | 1,233 |
from flask import Blueprint
from flask_restful import Api, url_for
from config import config
from . import resource
# 蓝图
api_bp = Blueprint('user', __name__)
# api
api = Api(api_bp)
# 路由
api.add_resource(resource.UserApi, '/users/<int:pk>')
api.add_resource(resource.UserListApi, '/users')
api.add_resource(resource.Aut... | 438 | 165 |
#!/usr/bin/env python3
'''
咕咕機器人 (實做)
請在 config.py 設定好 token 再啟動,
並確保已經在 @BotFather 關閉了 Privary 設定:
/setprivary -> 設定 Disable
接著私訊您的機器人,或者是放到您的群組即可。
'''
import config as c
import strings as s # 匯入字串
from libs import botHandler, randomText
import time, sys, random
# 相關參數
# 設定 botHandler
bot = botHandler(c.toke... | 2,376 | 1,053 |
import os
import cv2
# get list of files:
# print(os.listdir())
file_list = os.listdir()
image_list = []
# now making my actual file list
for x in file_list:
if x[-3:] == "jpg":
image_list.append(x)
# print(image_list)
def batch_resize(img_list):
for x in img_list:
img = cv2.imread(x,1)
... | 461 | 182 |
""" Collect Compute Audits, History, and Logs """
# Use this script to forward Audits, and Console History and Logs from Prisma Cloud Compute to a SIEM.
# It is expected to be called once an hour, by default, to read from the Prisma Cloud API and write to your SIEM API.
# It depends upon the SIEM to deduplicate data, ... | 8,983 | 3,064 |
from typing import List
from apistar import http
from models import PostModel
from types_ import PostType # because types is part of the standard library
def create_post(post: PostType) -> http.JSONResponse:
instance = PostModel(**post)
instance.save()
return http.JSONResponse(PostType(instance), stat... | 567 | 179 |
import tensorflow as tf
from image_similarity_measures import quality_metrics
LPIPS_ALEX_MODEL_URL = "https://github.com/HedgehogCode/lpips-tf2/releases/download/0.1.0/lpips_lin_alex.h5"
LPIPS_ALEX_MODEL_NAME = "lpips_lin_alex_0.2.0"
LPIPS_ALEX_MODEL_MD5 = "a35b66a420f518161f715c0675d9bbfb"
lpips_model_alex = None
LP... | 3,742 | 1,663 |
class ServicoEmprestimo():
def __init__(self):
self._servico_bike = None
def set_servico_bike(self, servico_bike):
self._servico_bike = servico_bike
def reserva_bike(self, id_bike):
if self._servico_bike is None:
raise('ServicoEmprestimo nao possui forma de chega em ... | 448 | 162 |
class Solution:
def find_kth_number(self, n: int, k: int) -> int:
cur = 1
k -= 1
while k > 0:
step = self._step(n, cur, cur + 1)
# 判断是否k值在子节点中
if step <= k:
k -= step
cur += 1
else:
k -= 1
... | 575 | 198 |
# -*- coding: utf-8 -*-
"""
Implementation of a simple linear congruental generator
@author: ssklykov
"""
# %% Import section
import numpy as np
import matplotlib.pyplot as plt
# %% The algorithm implementation
def simpleLCG(a: int = 1, c: int = 1, mod: int = 2**31, n: int = 10, seed: float = 0):
"""
Algori... | 1,121 | 441 |
# Generated by Django 2.1.4 on 2019-08-19 18:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0017_timeseries_meta_original_filename'),
]
operations = [
migrations.AddField(
model_name='timeseries_meta',
... | 590 | 183 |
#-------------------------------------------------------------------------------
#
# Project: EOxServer <http://eoxserver.org>
# Authors: Martin Paces <martin.paces@eox.at>
# Fabian Schindler <fabian.schindler@eox.at>
#
#-------------------------------------------------------------------------------
# Copyrigh... | 2,896 | 794 |