text string | size int64 | token_count int64 |
|---|---|---|
from geolucidate.links.tools import default_link
def yahoo_maps_link(type='hybrid', link=default_link):
'''
Returns a function for generating links to Yahoo Maps.
:param type: map type, one of 'map', 'satellite', or 'hybrid'
:param link: Link-generating function; defaults to :func:`~.default_link`
... | 1,006 | 389 |
"""
Common Django settings for campussim project.
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent.parent
# Application definition
INSTALLED_APPS = [
### Django apps for core functionalitites and packages for static fi... | 4,056 | 1,333 |
##############################################################################
# EVOLIFE www.dessalles.fr/Evolife Jean-Louis Dessalles #
# Telecom ParisTech 2014 www.dessalles.fr #
##############################################################################
... | 4,784 | 1,622 |
# Aziz Nechi
# If you have any trouble with submitting to S3, please contact me. This part is on me.
# As for the conversion, the fetching from url and the sound editing, I have made sure
# of its veracity.
# Please make sure the url you provide is correct, and doesn't block downloads from
# unknown sources.
# Your ... | 5,562 | 1,793 |
#
# PySNMP MIB module GUDEADS-EPC2X6-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/GUDEADS-EPC2X6-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:20:33 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... | 16,783 | 8,002 |
# -*- coding: utf-8 -*-
"""
====================================================
Jsonwspresponse :mod:`jsonwspclient.jsonwspresponse`
====================================================
"""
import logging
from . import jsonwspexceptions as excs
from . import jsonwsputils as utils
from .jsonwspmultipart import MultiPa... | 5,343 | 1,460 |
# /Volumes/usb1/ms2/
#
# /media/usbstick/MS_challenge1_train_data
#
#
def writeToFile(content):
with open('MStrainFloat2.lst', 'a') as f:
f.write(content)
with open('MStrainFloat.lst', 'r') as f:
lines = f.readlines()
counter = 0
content = ""
for line in lines:
line = line.replace("/Volumes/usb1/ms2/", "/media/... | 503 | 210 |
import os
import json
from onir import util, pipelines
import onir
import pickle
@pipelines.register('catfog')
class CatfogPipeline(pipelines.BasePipeline):
name = None
@staticmethod
def default_config():
return {
'max_epoch': 1000,
'early_stop': 20,
'warmup': -... | 8,986 | 2,855 |
import importlib
import os
import sys
try:
import unicodecsv as csv
except ImportError:
print "warning: unicodecsv not found. Please install it"
import csv
from urlparse import urlparse
import json
settings_module = os.environ.setdefault('FLASK_SETTINGS_MODULE', 'core.settings.loc') # other StoryMap code ex... | 6,514 | 2,019 |
famous = ['steve jobs','bill gates', 'gandhi']
print(f"Hello {famous[0].title()}, I'd like to invite you to dinner with me!")
print(f"Hello {famous[1].title()}, I'd like to invite you to dinner with me!")
print(f"Hello {famous[2].title()}, I'd like to invite you to dinner with me!")
print("I'm inviting",len(famous), "p... | 339 | 129 |
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
class SchemaViewTestCases(TestCase):
def test_schema_view(self):
response = self.client.get(reverse('schema'))
self.assertEqual(response.status_code, status.HTTP_200_OK)
| 291 | 85 |
# Copyright (c) 2018 Intel 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 in... | 1,425 | 394 |
from keras.models import model_from_json
from sklearn.metrics import classification_report
from load_data import read_file, preprocess_doc, \
pad_sequences, build_input_data_rnn, build_vocab
from model import AttentionWithContext, dot_product
# load json and create model
json_file = open('model.json', 'r')
loaded... | 2,028 | 759 |
# A simple example
# Author: Martin Lackner
from __future__ import print_function
import sys
sys.path.insert(0, '..')
import profiles
import perpetual_rules as perpetual
apprsets1 = {1: [1], 2: [1], 3: [2], 4: [3]}
apprsets2 = {1: [1], 2: [2], 3: [2], 4: [3]}
apprsets3 = {1: [1], 2: [1], 3: [2], 4: [3]}
voters = [1... | 879 | 359 |
import os
from pymongo import MongoClient
client = MongoClient(os.getenv("MONGODB_IP", "127.0.0.1"), 27017)
db = client.discord_logger
def add_message(guild, message_id, time, content, author, channel):
post = {
"message_id": str(message_id),
"time": str(time),
"content": str(content),
... | 424 | 154 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | 1,337 | 376 |
import sys
from .istream import istream
from .ostream import ostream
from .io import pin
from .io import pout
from .io import perr
sys.settrace(io.__iostream_checker__) # need fix | 182 | 58 |
import numpy as np, pandas as pd, networkx as nx, itertools, sys, traceback
def assemble_data(data_folder):
"""
We don't include a dummy for missings for data.church because Card and Guiliano do not report its coefficient. We don't include a dummy for missings for data.parent_HS, data.parent_college because Ca... | 5,278 | 2,012 |
# -*- coding: utf-8 -*-
"""
This module
"""
import attr
import typing
from ..core.model import (
Property, Resource, Tag, GetAtt, TypeHint, TypeCheck,
)
from ..core.constant import AttrMeta
#--- Property declaration ---
@attr.s
class PropInstanceAccessControlAttributeConfigurationAccessControlAttributeValue(Pr... | 14,428 | 4,552 |
class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
result = {}
for index, number in enumerate(sorted(nums)):
if number not in result:
result[number] = index
return [result[number] for number in nums]
| 299 | 81 |
from django.db import models
from posthog.models.dashboard import Dashboard
from posthog.models.utils import UUIDModel, sane_repr
# We call models that grant a user access to some resource (which isn't a grouping of users) a "privilege"
class DashboardPrivilege(UUIDModel):
dashboard: models.ForeignKey = models.F... | 1,184 | 371 |
import weakref
from html import escape
import warnings
MAX_IMG_VIEWS_BEFORE_WARNING = 10
class HTMLDocument(object):
"""
Embeds a plot in a web page.
If you are running a Jupyter notebook, the plot will be displayed
inline if this object is the output of a cell.
Otherwise, use open_in_browser() t... | 3,496 | 1,030 |
import json
from ..exceptions import AuthFailed, AuthUserError
from ..exceptions import RequestFailed, RateLimitedError
def validate_response(session, response, auth=False):
try:
try:
js_response = json.loads(response.text)
except:
response.raise_for_status()
if... | 1,244 | 334 |
!/usr/bin/python
# Exploit Title: FTPGetter 5.89.0.85 Remote SEH Buffer Overflow
# Date: 07/14/2017
# Exploit Author: Paul Purcell
# Contact: ptpxploit at gmail
# Vendor Homepage: https://www.ftpgetter.com/
# Vulnerable Version Download: Available for 30 days here: (https://ufile.io/2celn) I can upload again upon requ... | 4,640 | 3,047 |
from keras import models, optimizers
from keras.layers import Input, Dense, Activation, Flatten, Conv2D, Lambda, MaxPooling2D, Dropout
def Convnet():
# Model architecture
model = models.Sequential()
model.add(Conv2D(16, (3, 3), input_shape=(66, 200, 3), activation='relu'))
model.add(MaxPooling... | 882 | 357 |
import assertpy
import pytest
from google.protobuf.json_format import MessageToDict, Parse
from feast import proto_json
from feast.protos.feast.serving.ServingService_pb2 import (
FeatureList,
GetOnlineFeaturesResponse,
)
from feast.protos.feast.types.Value_pb2 import RepeatedValue
FieldValues = GetOnlineFeat... | 5,233 | 1,941 |
from os.path import join as oj
import importlib
import numpy as np
import os
import rulevetting
import rulevetting.api.util
DATA_PATH = oj(os.path.dirname(os.path.abspath(__file__)), '..', 'data')
def test_models(project):
"""Check that each baseline is implemented properly
"""
if not project == 'None'... | 1,584 | 545 |
#/usr/bin/python
#-*- coding: utf-8 -*-
#system modules
import sys
#add root path into the sys.path
# sys.path.append('./')
#custom modules
from Model.model import Model
if __name__ == "__main__":
if len(sys.argv)>1:
cmd=sys.argv[1]
if cmd=='score':
from evaluate import score
... | 634 | 201 |
from django.test import Client, RequestFactory, TestCase
from django.contrib.sessions.middleware import SessionMiddleware
from core.serializers import RepoSerializer
from core.models import Repo
from .views import *
import datetime
# Create your tests here.
class RepoSerializerTestCase(TestCase):
def setUp(self):... | 3,295 | 1,006 |
# In this example, we implement the sunflower equation. First, we do it regularly, then we repeat the process using callbacks.
from jitcdde import jitcdde, y, t
import numpy as np
a = 4.8
b = 0.186
tau = 40
# Regular implementation
# ----------------------
# To implement the sine function, we use SymEngine’s sine. T... | 1,910 | 666 |
from collections import Counter
from datasets import load_dataset
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
from nlprule import Rules, Tokenizer, SplitOn
from argparse import ArgumentParser
# gets a window from start - offset to end + offset or until a newline character is reached
def win... | 3,249 | 1,048 |
from algorithms import DNEH_SMR, destruction_reconstruction, local_search
from API.functions import PT, c_range, makespan
import numpy as np
import random
import math
# Soluciones probadas:
# Makespan: (36, 44, 52)
# Secuencias:
# [7, 8, 6, 10, 1, 9, 5, 4, 2, 3]
# [7, 8, 6, 10, 5, 9, 1, 4, 2, 3]
# [6, 1, 9, 7, 8, 10,... | 3,541 | 1,998 |
#!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distribut... | 12,614 | 3,712 |
#!/usr/bin/env python3
from carvpath import CarvPath,SparseFragment,BaseFragment
import unittest
class carvpathTest(unittest.TestCase):
# Positive test 1
def testsparse1(self):
cp1 = CarvPath([SparseFragment(1000)])
cp2 = CarvPath([SparseFragment(234)])
cp3 = cp1 + cp2
self.asse... | 904 | 381 |
from pygears.lib import check, drv, serialize
from pygears.typing import Uint, Array
din = drv(t=Array[Uint[8], 4], seq=[(1, 2, 3, 4), (5, 6, 7, 8)])
active = drv(t=Uint[2], seq=[2, 3])
serialize(din, active) \
| check(ref=[[1, 2], [5, 6, 7]])
| 250 | 126 |
'''
_______ _______ _______ _______ ________ ___ _______ __ __ ___________
/ __ / / ___ \ / ____/ / _____/ / ______\ / / / ____/ / \ / / /____ _____/
/ /__/ / / |__| | / /___ / /____ / / / / / /___ / \ / / / /
/ ______/ / __ ___/ / ____/ /___... | 10,087 | 3,011 |
def summation(num):
return int(num * (num+1) / 2)
number = int(input('The number will always be a positive integer greater than 0.'))
print(f'summation = {summation(number)}')
| 184 | 66 |
class ForgettingHash:
"""A fixed size hash that deletes the least used elements when full.
max_len must be more than 0
Uses a second dict with the same keys to record usage
Value is refereed to as 'content'
"""
def __init__(self, max_len, items=None): # type: int, list
if max_len <= ... | 1,848 | 545 |
# -*- coding: utf-8 -*-
# PyCi
#
# Copyright (c) 2009, The PyCi Project
# Authors: Wu Ke <ngu.kho@gmail.com>
# Chen Xing <cxcxcxcx@gmail.com>
# URL: <http://code.google.com/p/pyci>
# For license information, see COPYING
"""TagSet package.
Contains several tag set used for tagging segmentation like CRF.
"""... | 552 | 206 |
import os
import tempfile
import unittest
from elasticdl.proto import elasticdl_pb2
from elasticdl.python.common.model_utils import (
get_module_file_path,
load_module,
)
from elasticdl.python.master.checkpoint_service import CheckpointService
from elasticdl.python.master.servicer import MasterServicer
_model... | 4,281 | 1,213 |
from flask import Flask
from service import light_controller as light_service
app = Flask('Smart Home')
RESPONSE_OK = ("", 200)
@app.route('/api/light/<room>/<type>/<command>', methods=['GET'])
def control_light(room, type, command):
light_service.control_light(room, type, command)
return RESPONSE_... | 534 | 208 |
"""This module provides a class for storing and evaluating circles"""
from functools import cached_property
from math import pi
from typing import Optional, Tuple
from .point2d import Point2D
from .vector2d import Vector2D
class Circle:
"""This class stores and provides methods for evaluating circles"""
de... | 3,525 | 1,056 |
#!encoding=utf-8
'''
Created on 2015年10月12日
@author: Yafei
'''
import MySQLdb
import sys
class DB(object):
'''
classdocs
'''
def __init__(self, conf):
'''
Constructor
'''
self.db_host = conf.db_host
self.db_port = conf.db_port
self.db_user = conf.db_us... | 3,742 | 1,712 |
from fabric.api import run, cd
from fabric.operations import put, prompt
CODE_DIR = '~/camera-agent'
PHOTO_DIR = '~/photos'
CONFIG_PATH = '~/settings.ini'
def deploy():
# TODO kill camera-agent process
# delete directory 'camera-agent'
run('rm -rf ' + CODE_DIR)
# TODO copy raspberry-pi files to 'camera-agent'... | 565 | 209 |
# -*- coding: utf-8 -*-
"""
stamps.config
~~~~~~~~~~~~~
Stamps.com configuration.
:copyright: 2014 by Jonathan Zempel.
:license: BSD, see LICENSE for more details.
"""
from configparser import NoOptionError, NoSectionError, SafeConfigParser
from urllib.request import pathname2url
from urllib.pars... | 3,464 | 963 |
from django.apps import AppConfig
class ProductSearchConfig(AppConfig):
name = 'flaim.product_search'
| 108 | 32 |
#!/usr/bin/env python3
"""Calculate distances using the topic models on the course material/discussion
posts feature vectors.
"""
import os
import numpy as np
from datetime import datetime
from numpy import ravel
from pickle import load
from json import dump
from scipy.spatial.distance import cosine, euclidean
from gen... | 9,134 | 3,104 |
"""
Definition of views.
"""
from datetime import datetime
from django.shortcuts import render
from django.http import HttpRequest
from .graficoLinhaTempo import GraficoLT as graphLT
from .graficoBarra import GraficoBarra as graphBar
from .graficoScatter import GraficoScatter as grapScatter
import plotly as pl
def ... | 7,555 | 2,433 |
#!/usr/bin/env python
from setuptools import setup
import os
import sys
HERE = os.path.abspath(os.path.dirname(__file__))
VERSION_NS = {}
with open(os.path.join(HERE, 'nblineage', '_version.py')) as f:
exec(f.read(), {}, VERSION_NS)
setup_args = dict (name='lc-nblineage',
version=VERSION_NS['__version__'],... | 862 | 298 |
# Copyright 2021 VMware, Inc.
# SPDX-License-Identifier: Apache-2.0
from vdk.internal.control.utils.cli_utils import GqlQueryBuilder
from vdk.internal.control.utils.cli_utils import QueryField
def test_query_builder_simple():
jobs_builder = GqlQueryBuilder()
jobs_builder.start().add_return_new("jobs").add_ret... | 1,868 | 618 |
from fastapi import APIRouter, Depends
from typing import List
from src.utils.crud_router import include_generic_collection_document_router
from src.dependencies import current_active_user
from src.services.homeworks import HomeworkService, HomeworkCompletedService
dependencies: List[Depends] = [Depends(current_activ... | 955 | 242 |
# Generated by Django 3.1.5 on 2021-01-21 15:29
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('accounts', '0003_auto_20210121_2039'),
]
operations = [
migrations.CreateM... | 1,357 | 409 |
from joblib import Parallel, delayed
from sklearn.utils import check_random_state
from exps.train import run
seeds = check_random_state(42).randint(0, 100000, size=20).tolist()
# Takes 15 minutes on a 40 CPU computer
Parallel(n_jobs=40, verbose=10)(delayed(run)(estimator, seed)
for es... | 573 | 197 |
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('fromcsv', help="Path to classified bug csv")
parser.add_argument('tocsv', help="Path to new csv")
args = parser.parse_args()
fromcsv = open(args.fromcsv)
tocsv = open(args.tocsv)
from_lines = [x.strip() for x in fromcsv.readlines()]
to_lines = [... | 742 | 260 |
#
# Copyright (C) 2014 Dell, Inc.
#
# 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 wri... | 3,053 | 894 |
import cv2
import os
import sys
import shutil
import subprocess
face_cascade = cv2.CascadeClassifier('Face_cascade.xml')
original_path = sys.argv
#original_path = "D:\College Stuff\Machine Learning\Tests\Minor Project\Test 1 - without ED\data\Anne"
#new_path = original_path + "1"
#os.rename(original_path,new_path)
i=0
... | 1,980 | 799 |
#!/usr/bin/env python3
import string
import random
import os
import sys
import time
import json
def main():
lives = 8
guessed = set()
# Opening words database
try:
words = open('words.json')
except IOError:
print('Can\'t locate words.json in local directory.')
time.sleep... | 3,763 | 1,007 |
# The game mode is REVERSE: You do not have access to the statement. You have to guess what to do by observing the following set of tests:
# 01 Test 1
# Input
# Expected output
# +-+--+-+++--+
# 1
# 02 Test 2
# Input
# Expected output
# +++++++---
# 4
# 03 Test 3
# Input
# Expected output
# -+-+-+-+-+-+
# 0
# 04 Test 4... | 421 | 171 |
#
# Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.
#
# File: concurrent1.py
#
# Purpose: Demonstrates a simple implementation of a concurrent optimizer.
#
# The concurrent optimizer starts a few parallel optimizations
# of the same problem using different algori... | 6,593 | 2,184 |
"""The fixtures for `lino_xl.lib.statbel.countries`.
These are just wrappers to those in :mod:`lino_xl.lib.countries.fixtures`.
.. autosummary::
:toctree:
all_countries
be
demo
eesti
few_cities
few_countries
"""
| 243 | 98 |
import geopy.distance
from math import degrees
import numpy as np
def makeNewPoint(geoJsonPoint):
return (geoJsonPoint[1], geoJsonPoint[0])
def makeVector(pointA, pointB):
return [pointB[0] - pointA[0], pointB[1] - pointA[1]]
def distanceMeteres(point1, point2):
return geopy.distance.geodesic(point1, poi... | 640 | 238 |
#!/usr/bin/env python
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
lastchange.py -- Chromium revision fetching utility.
"""
import optparse
import os
import re
import subprocess
import sys
de... | 2,886 | 980 |
from typing import List
from ansible_self_service.l3_services.dto import AppCollection, App
from ansible_self_service.l4_core.models import AppCatalog
class AppService:
"""Provide an interface to app related features."""
def __init__(self, app_catalog: AppCatalog):
self._app_catalog = app_catalog
... | 657 | 193 |
import numpy as np
import urllib
from lxml import etree
import batman
import ldtk
from scipy.interpolate import interp1d
# from joblib import Parallel, delayed
import random
import matplotlib.pyplot as plt
from scipy.spatial.qhull import QhullError
import multiprocessing
import logging
import sys
def planet_gen_wrapp... | 9,111 | 3,363 |
from datetime import date
from django.shortcuts import resolve_url as r
from django.test import TestCase
from django.utils import timezone
from .models import Choice, Question
class IndexTest(TestCase):
def setUp(self):
Question.objects.create(text='What is your favorite color?')
Question.object... | 3,015 | 949 |
import unittest
import numpy as np
from rl_parsers import MDP_Parser
class MDP_Test(unittest.TestCase):
def test_gridworld(self):
parser = MDP_Parser(optimize=False)
mdp = parser.parse_file('tests/mdp/gridworld.mdp')
self.assertEqual(mdp.discount, 0.95)
self.assertListEqual(mdp... | 748 | 296 |
"""
Visualization setup file.
"""
from setuptools import setup
requirements = ["imageio", "numpy", "matplotlib", "trimesh[easy]", "autolab_core", "pyrender"]
exec(open("visualization/version.py").read())
setup(
name="visualization",
version=__version__,
description="Visualization toolkit for the Berkele... | 1,235 | 372 |
#!/usr/bin/env python
#################################################################################
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# #
# Licensed under the Apache License, Version 2.0 ... | 18,024 | 4,413 |
#!/usr/bin/env python
from __future__ import print_function
import csv
from flask import Flask
from flask import request, jsonify, make_response
app = Flask(__name__)
FILE ="serial-ip.csv"
@app.route('/device', methods=["GET"])
def get_all():
#print (request.args)
#print("Method {}".format(request.method))
... | 1,208 | 369 |
password="pbkdf2(1000,20,sha512)$b38a05727410f589$82dc4c62c2132fdc53b2e69c6a362f5369ad31dd"
| 92 | 76 |
from ansible.module_utils.six import string_types
def in_loop_list(
val, loop_var, path=[], module='stat', param='exists', param_val=True):
"""Verifies if any of the loop results have the desired value"""
ret = False
for result in loop_var['results']:
item = result['item']
for f... | 1,217 | 303 |
import argparse, os, json, io
def dir_path(string):
if os.path.isdir(string):
return string
else:
raise NotADirectoryError(string)
def dir_path(string):
if os.path.isdir(string):
return string
else:
raise NotADirectoryError(string)
# Parse CONTROL File
def simpleInse... | 2,883 | 959 |
#-*- coding:utf-8 -*-
"""
__init__
Copyright (c) 2018 Tetsuya Shinaji
This software is released under the MIT License.
http://opensource.org/licenses/mit-license.php
Date: 2018/03/01
"""
from __future__ import absolute_import
from .core import Dict
__version__ = "0.3.1"
| 300 | 124 |
# -*- coding: utf-8 -*-
'''
Created on Mar 20, 2011
@author: Mourad Mourafiq
@copyright: Copyright © 2011
other contributers:
'''
from django.conf.urls import patterns, include, url
from calendars.views import calendar_tables as calendar_tables
from calendars.views import events as events
urlpatterns = patterns(''... | 859 | 314 |
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
from azure.core.credentials import AccessToken
from azure.core.exceptions import ClientAuthenticationError
from azure.identity import CredentialUnavailableError, ClientS... | 3,724 | 1,109 |
from ..generator import Generator
from ..platforms import available_platforms
from ..target import Target
import os
class XCConfigGenerator(Generator):
@staticmethod
def identifier():
return 'xcconfig'
def __xcconfig(self, needy, target, sdk, arch):
header_search_paths = []
libr... | 2,538 | 874 |
class InterpolationEvaluationException(KeyError):
pass
class expression_dictionary(dict):
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
try:
return eval(key,self)
except Exception, e:
rai... | 864 | 303 |
# -*- coding: utf-8 -*-
import json
import os
import re
import sys, getopt
import threading
from warnings import simplefilter
import flask
from flask import request, abort, make_response, jsonify
from utils import nlp_config
from utils import log_util
from core import train_model, predict_model
from pubsub import cons... | 6,166 | 2,069 |
from datetime import timedelta, date
from forty.managers.project_manager import Config
from forty.views import RemainedStatusView
from forty.models import StatusModel
from forty.tools import ActionsBuilder as A
from ..model_test_case import ModelTestCase
class TestStatusModelRemainedMethod(ModelTestCase):
def _... | 1,587 | 510 |
import os
from http import HTTPStatus
from dotenv import load_dotenv
from flask import Flask, Response, request
from telegram import Update
from telegram.ext import messagequeue as mq
from telegram.ext.dispatcher import Dispatcher
from telegram.utils.request import Request
import pdf_bot.dispatcher as dp
import pdf_b... | 1,215 | 412 |
###############################################################################
# BSD 3-Clause License
#
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Author & Contact: Guilin Liu (guilinl@nvidia.com)
###############################################################################
"""
Code by Guilin... | 2,650 | 882 |
#!/usr/bin/env python
# Rumah Sahaja backend
import jwt
import hashlib
import datetime
from functools import wraps
from flask_sqlalchemy import SQLAlchemy
from flask import Flask, request, jsonify, make_response
from flask_cors import CORS
app = Flask(__name__)
app.config.from_pyfile('rs.cfg')
__DEBUG__ = True
__Fr... | 7,543 | 2,338 |
import time
from model.parser import LALR
def elapsed(since):
'''
Returns elapsed time since 'since'.
'''
now = time.time()
elapsed = now - since
return elapsed
def filter_dict(pred, dict_):
'''
Filters a dictionary based the predicate provided.
'''
for key, val in dict_.it... | 524 | 163 |
#!/usr/bin/env python
def can_build(env, platform):
# Editor only module
return env["tools"]
def configure(env):
pass
def is_enabled():
# Enable manually with `module_gdscript_transpiler_enabled=yes` option.
return True
| 245 | 80 |
"""
@Project : PowerForecast
@Module : base.py
@Author : HjwGivenLyy [1752929469@qq.com]
@Created : 3/12/19 1:47 PM
@Desc : basic module of entire project
"""
import numpy as np
from sklearn.metrics import mean_squared_error, mean_absolute_error
from sklearn.model_selection import train_test_split
FI... | 1,334 | 515 |
import Levenshtein as Lev
import numpy as np
from utils.model_utils import get_most_probable
from ignite.metrics import Metric, Accuracy
from ignite.metrics.metric import reinit__is_reduced
from datasets.librispeech import get_vocab_list, sequence_to_string
import torch
def werCalc(s1, s2):
"""
Computes the Wo... | 3,331 | 1,155 |
def decapitalize(key):
return key[0].lower() + key[1:]
| 59 | 24 |
#!/usr/bin/env python
# update_readme.py
#
# Copyright (C) 2020-2021 Karl T Debiec
# All rights reserved.
#
# This software may be modified and distributed under the terms of the
# BSD license.
"""Updates readme."""
import re
from inspect import cleandoc, getfile
from os.path import dirname, join, splitext
fr... | 3,416 | 1,068 |
import bpy
class QuickMocapTemplatePanel:
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = "Tools"
bl_options = {"DEFAULT_CLOSED"}
| 179 | 76 |
#! /usr/bin/env python3
'''Usage:
./inventory_to_shippo_labels.py tshirt_inventory.xlsx labels.csv'''
import copy
import csv
import math
import re
from sys import argv
import warnings
import openpyxl
# Measured masses of t-shirts by size, in oz
SHIRT_WEIGHTS = {'MXS': 3.45 / 1,
'MS': 11.45 / 3,
... | 7,060 | 2,298 |
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, absolute_import, division
""" Work out the first ten digits of
the sum of the following one-hundred 50-digit numbers.
"""
from projecteulerhelper import *
##########################################
def ProjectEuler13()... | 1,299 | 477 |
# Generated with the AWS CLI with the following command:
# aws elbv2 describe-ssl-policies --query 'SslPolicies[?SslProtocols==[`TLSv1.2`]].Name'
TLS_1_2_POLICIES = {
"ELBSecurityPolicy-TLS-1-2-2017-01",
"ELBSecurityPolicy-TLS-1-2-Ext-2018-06",
"ELBSecurityPolicy-FS-1-2-Res-2019-08",
"ELBSecurityPolic... | 739 | 303 |
from ev3dev2simulator.connection.ClientSocket import get_client_socket
from ev3dev2simulator.connection.message.RotateCommand import RotateCommand
from ev3dev2simulator.connection.message.StopCommand import StopCommand
FOREVER_MOCK_SECONDS = 45
class MotorConnector:
"""
The MotorConnector class provides a tr... | 4,733 | 1,248 |
import collections
import datetime
from merc import feature
from merc import message
INFO_TEMPLATE = """\
____
__/ / /___ _ ___ ________
/_ . __/ ' \/ -_) __/ __/
/_ __/_/_/_/\__/_/ \__/
/_/_/
The Modern Extensible Relay Chat daemon, version {version}.
Copyright (C) {year}, #merc-devel
This softwar... | 2,758 | 1,003 |
'''Необходимо реализовать модуль divisor_master. Все функции модуля принимают на вход натуральные числа от 1 до 1000.
Модуль содержит функции:
1) проверка числа на простоту (простые числа - это те числа у которых делители единица и они сами);
2) выводит список всех делителей числа;
3) выводит самый большой простой дел... | 1,878 | 771 |
# This script automates the generation of the DFU file from the release build.
# File paths are generated relative to the repo, so should work where ever the repo is put.
#
# Requires pywinauto.
# pip install pywinauto
from pywinauto.application import Application
from pywinauto.timings import Timings
import time
f... | 1,848 | 695 |
#!/usr/bin/env python3
from subprocess import Popen
import pathlib
submodules = []
if __name__=='__main__':
Popen("git init",shell=True).wait()
for sm in submodules:
Popen(f"git submodule add {sm}",shell=True).wait()
if submodules:
Popen("git submodule update --init --recursive",shell=True... | 436 | 144 |
import requests
import random
def send_otp(number):
url = "https://www.fast2sms.com/dev/bulk"
otp = random.randint(10000, 99999)
querystring = {"authorization": "ZM2aEdmsy3WHNI8xejK6kiJ4hCYrBuwfn9t5QSLpov0VRb7lcP0qHGS5fkgWtPNX2YhFrQy9JnBOZTD6",
"sender_id": "FSTSMS", "language": "engli... | 640 | 254 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Abstract: Unit tests for the implementations of the core concept 'network'
"""
__author__ = "Michel Zimmer"
__copyright__ = "Copyright 2014"
__credits__ = ["Michel Zimmer"]
__license__ = ""
__version__ = "0.1"
__maintainer__ = ""
__email__ = ""
__date__ = "December 2... | 3,084 | 1,230 |
#!/usr/bin/python3
"""This module contains a function that writes an
Object to a text file, using a JSON representation.
"""
import json
def save_to_json_file(my_obj, filename):
"""Writes an Object to a text file, using a JSON representation.
Arguments:
my_obj {obj} -- python object.
file... | 441 | 137 |