text
string
size
int64
token_count
int64
def comment_dialog(data=None): """ Function takes in a JSON object, and uses the following format: https://api.slack.com/dialogs Returns created JSON object, then is sent back to Slack. """ text = "" state = "" project_holder = None item_holder = None if data is not None: ...
2,968
749
"""Test the HaHomematic config flow.""" from typing import Any from unittest.mock import patch from homeassistant import config_entries from homeassistant.components.hahm.config_flow import ( ATTR_BICDOS_RF_ENABLED, ATTR_BICDOS_RF_PORT, ATTR_HMIP_RF_ENABLED, ATTR_HOST, ATTR_HS485D_ENABLED, ATTR...
8,105
2,818
from functools import partial class counter: """ A counter decorator to track how many times a function is called. """ def __init__(self, func): self.func = func self.count = 0 def __call__(self, *args, **kwargs): self.count += 1 return self.func(*args, **kwargs) ...
792
221
#|----------------------------------------------------------------------------- #| This source code is provided under the Apache 2.0 license -- #| and is provided AS IS with no warranty or guarantee of fit for purpose. -- #| See the project's LICENSE.md for details. -- ...
5,883
1,743
#!/usr/bin/python3 class CardDao(): def __init__(self): # constructor super().__init__() self.create() self.return() self.update() self.delete() self.populate() def create(self): # there will be create for cards print('Create') def return(...
571
176
from unittest import TestCase from eskedit.kmethods import * class Test(TestCase): def test_generate_kmers(self): print('Testing %s' % 'test_generate_kmers') for i in range(1, 8): self.assertEqual(len(generate_kmers(i)), 4 ** i) def test_gen_random_sequence(self): print('...
3,416
1,208
from django.urls import reverse_lazy, reverse from django.shortcuts import get_object_or_404, render, HttpResponse, HttpResponseRedirect from requests.auth import HTTPBasicAuth from .models import User, Node from .forms import CustomUserCreationForm, UserCreationForm from django.views.generic import ListView from djan...
8,747
2,594
#from weakref import WeakValueDictionary import random, operator, weakref def format_service_group(group): """pretty prints the group""" rstr = '%s [%s]' if group.cover != None: # Spy for IntSec return rstr % (group.cover, group.cover.firm) elif group.spyon != None: return rstr % (group.spyon, group.spyon.firm...
1,569
587
import asyncio import unittest from moex.service import Cbr, Moex class CbrTest(unittest.TestCase): def setUp(self) -> None: self.cbr = Cbr('01.01.2021') def test_usd(self): self.assertEqual(self.cbr.USD, 73.88) def test_euro(self): self.assertEqual(self.cbr.EUR, 90.79) class...
2,195
963
import streamlit as st import pandas as pd import numpy as np import plotly.express as px st.title("Relatório de Aula") df = pd.read_csv('data/emocoes.csv') agg = pd.read_csv('data/agg.csv') Engajado = df[df['emocao'] == 'Engajado'] Engajado_agg = Engajado.groupby(['emocao', 'pessoa']).size().reset_index(name='size')...
2,820
1,052
import argparse import json import os from os import listdir from os.path import isfile, join class RegisterOtherNominate: # Register the prize winners of each award to the formatting style. def __init__(self): parser = argparse.ArgumentParser() parser.add_argument("-d", "--directory", ...
4,410
1,175
class Table: # Constructor # Defauls row and col to 0 if less than 0 def __init__(self, col_count, row_count, headers = [], border_size = 0): self.col_count = col_count if col_count >= 0 else 0 self.row_count = row_count if row_count >= 0 else 0 self.border_size = border_size if ...
5,477
1,689
from .. import db from .base import BaseModel class ChildDatum(BaseModel): __tablename__ = 'child_data' # fields parent_id = db.Column(db.Integer, db.ForeignKey('data.id'), nullable=False) datum_id = db.Column(db.Integer, db.ForeignKey('data.id'), nullable=False) name = db.Column(db.String(length...
676
232
import dataclasses as dc from typing import Any, Dict, Iterable, List, Optional from loguru import logger from mate3.field_values import FieldValue, ModelValues from mate3.read import AllModelReads from mate3.sunspec.fields import IntegerField from mate3.sunspec.model_base import Model from mate3.sunspec.models impor...
13,474
3,718
#!/usr/bin/env python import rospy from srv_sub_pub.srv import * NAME = "add_two_ints_server" def add_two_ints(req): print("Returning [%s + %s = %s]" % (req.a, req.b, (req.a + req.b))) return AddTwoIntsResponse(req.a + req.b) def add_two_ints_server(): rospy.init_node(NAME) s = rospy.Service('add_t...
490
202
#!/usr/bin/env python # -*- coding: utf-8 -*- import tornado.web class Handler(tornado.web.RequestHandler): def initialize(self): pass
148
53
import multiprocessing as mp class ModuleRecursion(object): """Class to handle recursion. Simple class to handle tracking and storing prior sub-domains discovred. """ def __init__(self): """class init. """ self.recursion_queue = mp.Queue() def add_subdomain(self, domain): """add subdomain to Q. ...
1,113
450
import os from pyspark import StorageLevel from geospark.core.SpatialRDD import PolygonRDD from geospark.core.enums import IndexType, FileDataSplitter from geospark.core.geom.envelope import Envelope from geospark.core.spatialOperator import RangeQuery from tests.test_base import TestBase from tests.tools import test...
1,691
549
from typing import Dict from river import base __all__ = ["Renamer", "Prefixer", "Suffixer"] class Renamer(base.Transformer): """Renames features following substitution rules. Parameters ---------- mapping Dictionnary describing substitution rules. Keys in `mapping` that are not a feature's...
2,004
705
from open_publishing.core import FieldGroup from open_publishing.core import FieldDescriptor from open_publishing.core.enums import CatalogType, VLBCategory, AcademicCategory from open_publishing.core import SimpleField from open_publishing.extendable_enum_field import ExtendableEnumField from open_publishing.genre im...
4,660
1,098
import urllib.request,json from .models import Source,Article # Getting Api Key api_key = None #Getting the base urls source_base_url = None article_base_url = None def configure_request(app): global api_key,source_base_url,article_base_url api_key = app.config['SOURCE_API_KEY'] source_base_url = app.conf...
2,263
672
# normal libraries import math import numpy as np # priv_libraries from corai_util.finance.src.financials import compute_price, compute_integral from corai_util.finance.src.implied_vol import implied_volatility_newton, total_implied_vol_newton phi_heston = lambda xx: (1 - (1 - np.exp(-xx)) / xx) / xx phi_heston_lambd...
5,027
1,938
import unittest from get_all_permutations_of_string import get_all_permutations_of_string, get_all_permutations_of_string_with_dups class Test_Case_Get_All_Permutations_Of_String(unittest.TestCase): def test_get_all_permutations_of_string(self): self.assertListEqual(get_all_permutations_of_string("tea"), [...
687
265
#! /usr/bin/env python # -*- mode: python; indent-tabs-mode: nil; -*- # vim:expandtab:shiftwidth=2:tabstop=2:smarttab: # # Copyright (C) 2011 Patrick Crews # # # This program 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 Softwar...
8,171
2,400
print filter((lambda x: (x%2) ==0 ), [1,2,3,4,5,6]) print filter((lambda x: (x%2) !=0 ), [1,2,3,4,5,6])
104
57
l=[0]*100 l[0]=1 l[1]=2 for x in range (2,100): l[x]=l[x-1]+l[x-2] #print l f=0 for c in l: if c%2==0 and c<4000000: f=f+c print f
156
103
#!/usr/bin/env/python3 """Recipe for training a wav2vec-based ctc ASR system with librispeech. The system employs wav2vec as its encoder. Decoding is performed with ctc greedy decoder. To run this recipe, do the following: > python train_with_wav2vec.py hparams/train_with_wav2vec.yaml The neural network is trained on C...
12,809
4,164
from __future__ import annotations from ..utils import normalize_single_outer_inner_index def test_normalize_single_outer_inner_index() -> None: divisions = (0, 12, 14, 20, 23, 24) indices = [0, 1, 2, 8, 12, 13, 14, 15, 17, 20, 21, 22] results = [ (0, 0), (0, 1), (0, 2), (...
907
401
"""Implements the EClientSocket interface for the Interactive Brokers API.""" import threading import ibapipy.config as config from ibapipy.core.network_handler import NetworkHandler class ClientSocket: """Provides methods for sending requests to TWS.""" def __init__(self): """Initialize a new instan...
16,413
4,653
import os from datetime import datetime PROJECT_PATH = os.path.dirname(os.path.realpath(__file__)) IDENTIFIER = datetime.now().strftime('%Y-%m-%d_%H-%M-%S') #numerical libs import numpy as np import random import matplotlib matplotlib.use('TkAgg') import cv2 # torch libs import torch from torch.utils.data.sampler...
2,234
794
import numpy as np import cv2 import matplotlib.pyplot as plt import numpy as np from keras.models import model_from_json # Load the saved model json_file = open('models/model.json', 'r') loaded_model_json = json_file.read() json_file.close() loaded_model = model_from_json(loaded_model_json) # load weights into new mo...
1,460
546
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 12 18:28:54 2020 @author: Dr J A Christen (CIMAT-CONACYT, Mexico) jac at cimat.mx Instantaneous reproduction numbers calculations. Rts_P, Implementation of Cori et al (2013) Rts_AR, new filtering version using an autoregressive linear model of Ca...
38,889
15,485
class cluster(object): def __init__(self,members=[]): self.s=set(members) def merge(self, other): self.s.union(other.s) return self class clusterManager(object): def __init__(self,clusters={}): self.c=clusters def merge(self, i, j): self.c[i]=self.c[j]=self.c[i...
678
242
import FWCore.ParameterSet.Config as cms process = cms.Process("ProcessOne") process.load("CondCore.DBCommon.CondDBCommon_cfi") process.CondDBCommon.DBParameters.authenticationPath = '/nfshome0/popcondev/conddb' # # Choose the output database # process.CondDBCommon.connect = 'oracle://cms_orcon_prod/CMS_COND_42X_ECAL_...
2,989
957
from algosdk import logic from algosdk.future.transaction import ApplicationOptInTxn, AssetOptInTxn, ApplicationNoOpTxn, PaymentTxn, AssetTransferTxn from ..contract_strings import algofi_manager_strings as manager_strings from .prepend import get_init_txns from ..utils import TransactionGroup, Transactions, randint, i...
9,907
2,906
import rumps import requests import json API_URL = 'https://koinex.in/api/ticker' UPDATE_INTERVAL = 60 CURRENCIES = { 'Bitcoin': 'BTC', 'Ethereum': 'ETH', 'Ripple': 'XRP', 'Litecoin': 'LTC', 'Bitcoin Cash': 'BCH', } class KoinexStatusBarApp(rumps.App): def __init__(self): super(Koin...
1,661
554
from flask import Flask, jsonify from time import strftime from socket import gethostname from socket import gethostbyname app = Flask(__name__) @app.route('/') def welcome(): message = 'Please add /docker after the port 8888' return message @app.route('/docker') def docker(): currentDate = strftime('%...
900
304
import numpy as np from numpy.core.fromnumeric import mean from numpy.core.numeric import True_ from numpy.testing._private.utils import rand from polynomial_regression import PolynomialRegression from generate_regression_data import generate_regression_data from metrics import mean_squared_error # mse from math impor...
8,605
3,238
# EG10-20 Twinkle Twinkle classes import time import snaps class Note: def __init__(self, note, duration): self.__note = note self.__duration = duration def play(self): snaps.play_note(self.__note) time.sleep(self.__duration) tune = [Note(note=0, duration=0.4), Note(note=0, d...
753
287
# 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, Version 2.0 (the # "License"); you may not u...
3,523
1,327
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # LavaVu conf based on conf.py from underworld2 # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup ------------...
7,706
2,363
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import collections import mkkm_mr import networkx as nx from sklearn.cluster import KMeans, SpectralClustering from snf_simple import SNF from pamogk import config from pamogk import label_mapper from pamogk.data_processor import rnaseq_processor as rp, synapse_rppa_pro...
25,824
9,279
import requests from lxml import html from bs4 import BeautifulSoup import json import codecs import re #In this variable I will store the information as a dictionary with this structure: # {number : "Name"} ms_dict = {} links_dict = {"links" : []} for index in range(1,27000): print(index) page = requests.get('ht...
1,703
693
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import numpy as np import pytest import GPy from math import isclose from emukit.model_wrappers.gpy_quadrature_wrappers import QuadratureRBF, RBFGPy, BaseGaussianProcessGPy from emukit.quadrature.methods i...
2,590
1,091
import unittest import sys sys.path.insert(2, "..") from awsec2instances_includes.ProtocolService import ProtocolService class test_ProtocolService(unittest.TestCase): def test_execption_wrong_argument(self): wrong_argument = "some-invalid" with self.assertRaises(Exception): ProtocolSe...
2,039
627
from .constants import SPECIAL_TOKENS try: import re2 as re except ImportError: import re def twitter_sentiment_token_matching(token): """Special token matching function for twitter sentiment data.""" if 'URL_TOKEN' in SPECIAL_TOKENS and re.match(r'https?:\/\/[^\s]+', token): return SPECIAL_TO...
873
392
"""A setuptools based setup module. See: https://packaging.python.org/guides/distributing-packages-using-setuptools/ """ from setuptools import setup, find_packages from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f...
1,503
495
# # Solver class using Scipy's adaptive time stepper # import casadi import pybamm import scipy.integrate as it import numpy as np class ScipySolver(pybamm.BaseSolver): """Solve a discretised model, using scipy._integrate.solve_ivp. Parameters ---------- method : str, optional The method to ...
3,457
1,009
import datetime from dateutil.parser import parse from mongoengine import DateTimeField, FileField from mongoengine.connection import DEFAULT_CONNECTION_NAME #from mongoengine.python_support import str_types from six import string_types as str_types import io from django.conf import settings if settings.FILE_DB == se...
5,204
1,454
import sys from PySide6 import QtGui class OutLog: def __init__(self, edit, out=None, color=None): """(edit, out=None, color=None) -> can write stdout, stderr to a QTextEdit. edit = QTextEdit out = alternate stream ( can be the original sys.stdout ) color = alternate color (...
821
251
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import re import unittest COLOR = "shiny gold" FNAME = "input.txt" N_ITER = 1e7 TEST_FNAME = "test_input.txt" def main(): """Main function.""" data = load_input(FNAME) part1(data) part2(data) print("\nUnittests") unittest.main() def part1(d...
5,079
1,605
#!/usr/bin/env python3 #coding: UTF-8 import os import sys import time import json import argparse from os.path import join, exists, dirname from upgrade import check_upgrade from utils import call, get_conf, get_script, get_command_output, get_install_dir installdir = get_install_dir() topdir = dirname(installdir) ...
1,937
636
import sys, os import nltk import numpy as np class Patch(): def __init__(self): self.id = -1 self.parent_code = '' self.child_code = '' self.patches = [] self.verdict = False self.distance = 0 self.verdict_token = False pass def __repr__(self): ...
4,774
1,655
# Copyright (c) 2016-2018 Koninklijke Philips N.V. All rights reserved. A # copyright license for redistribution and use in source and binary forms, # with or without modification, is hereby granted for non-commercial, # experimental and research purposes, provided that the following conditions # are met: # - Redistrib...
4,934
1,688
"""Helper Functions Some Misc Functions used in this app """ import secrets import string from functools import wraps from urllib.parse import urljoin, urlparse from dateutil import parser from flask import abort, current_app, request from flask_login import current_user from flask_migrate import upgrade def setup_...
4,024
1,116
import numpy as np import matplotlib import matplotlib.pyplot as plt import scipy.linalg as la print("loading time series... ") plt.figure(figsize=(16,9)) timeSeries = np.loadtxt('TheftTS.txt',delimiter=',',dtype=float) # load data hourly = timeSeries[:,0] plt.plot(hourly,'r-', label='Theft') timeSeries = np.loadtxt...
1,094
443
""" Creating training file from own custom dataset >> python annotation_csv.py \ --path_dataset ~/Data/PeopleDetections \ --path_output ../model_data """ import os import sys import glob import argparse import logging import pandas as pd import tqdm sys.path += [os.path.abspath('.'), os.path.abspath('..')] ...
2,733
913
from pegasos import bgd_pegasos import numpy as np import pandas as pd import pickle import sys def read_data(file): x = pd.read_csv(file, header=None) if x.shape[1] > 784: y = np.array(x[[784]]).flatten() x = x.drop(columns=[784]) else: y = np.zeros(x.shape[0]) x = x.as_matri...
3,280
1,200
import numpy as np # Inner (or dot) product a = np.array([1,2]) b = np.array([3,4]) np.inner(a, b) a.dot(b) # Outer product a = np.array([1,2]) b = np.array([3,4]) np.outer(a, b) # Inverse m = np.array([[1,2], [3,4]]) np.linalg.inv(m) # Inner (or dot) product m = np.array([[1,2], [3,4]]) minv = np.linalg.inv(m) m....
1,533
774
import os import platform import unittest # ZODB >= 3.9. The blob directory can be a private cache. shared_blob_dir_choices = (False, True) RUNNING_ON_TRAVIS = os.environ.get('TRAVIS') RUNNING_ON_APPVEYOR = os.environ.get('APPVEYOR') RUNNING_ON_CI = RUNNING_ON_TRAVIS or RUNNING_ON_APPVEYOR def _do_not_skip(reason):...
14,337
4,023
# -*- coding: utf-8 -*- """Example generation for testing. Exports dict of examples, useful for testing as fixtures. example_dict: dict indexed by triple 1st element = mtype - str 2nd element = considered as this scitype - str 3rd element = int - index of example elements are data objects, considered examples f...
2,435
980
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue Jul 9 15:34:36 2019 @author: eseliuni """ from __future__ import print_function #from builtins import str #from builtins import range import os def get_coordinate_from_line(coordinate, line): """ Returns a value of a coordinate from a line ...
2,951
959
def start(password=None): pass
35
12
import os import base64 import botocore import boto3 import json import urllib from chalice import BadRequestError from chalice import ChaliceViewError from chalice import Chalice app = Chalice(app_name='a3x') app.debug = True REGION = 'us-east-1' BUCKET = 'freko-001' S3 = boto3.resource('s3') REKOGNITION = boto3.cl...
4,294
1,445
# -------------------------------------------------------- # Written by Yufei Ye (https://github.com/JudyYe) # -------------------------------------------------------- from __future__ import print_function from __future__ import absolute_import from __future__ import division # Copyright (c) Facebook, Inc. and its affi...
7,387
2,652
import shutil import traceback from pathlib import Path from pprint import pprint from typing import List, Optional, Union from marshmallow import ValidationError from bioimageio.spec import export_resource_package, load_raw_resource_description from bioimageio.spec.shared.raw_nodes import URI from bioimageio.spec.sh...
3,294
989
import numpy as np def max_cycles_test(mod): max_cycles = 4 parallel_env = mod.parallel_env(max_cycles=max_cycles) observations = parallel_env.reset() dones = {agent: False for agent in parallel_env.agents} test_cycles = max_cycles + 10 # allows environment to do more than max_cycles if it so wi...
1,309
423
''' MIT License Copyright (c) 2020 Autonomous Vision Group (AVG), Max Planck Institute for Intelligent Systems Tübingen 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, inclu...
3,460
1,147
""" Slixmpp: The Slick XMPP Library Copyright (C) 2012 Nathanael C. Fritz, Lance J.T. Stout This file is part of Slixmpp. See the file LICENSE for copying permission. """ import logging from slixmpp.xmlstream import register_stanza_plugin from slixmpp.plugins.base import BasePlugin, register_plugin ...
4,855
1,290
#! python3 # Combines all the pafs in the current working directory into a single pdf import PyPDF2, os, sys, logging class Merge (): """ Merge all pdfs in the current folder, or specific list of files, by name, into a single pdf file """ def __init__ (self, file_output = "", replace = False, d...
3,578
981
# -*- coding: utf-8 -*- import traceback from JobBrowserBFF.TestBase import TestBase from biokbase.Errors import ServiceError import unittest import re UPSTREAM_SERVICE = 'mock' ENV = 'mock' JOB_ID_WITH_LOGS = '59820c93e4b06f68bf751eeb' # non-admin JOB_ID_NO_LOGS = '5cf1522aaa5a4d298c5dc2ff' # non-admin JOB_ID_NOT_F...
3,941
1,347
"""Index related entity names Revision ID: 323f8d77567b Revises: 82b34e2777a4 Create Date: 2016-11-16 13:00:25.782487 """ # revision identifiers, used by Alembic. revision = '323f8d77567b' down_revision = '82b34e2777a4' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated ...
674
272
import random high_score = 0 def dice_game(): global high_score while True: print("Current High Score: ", high_score) print("1) Roll Dice") print("2) Leave Game") choice = input("Enter your choice: ") if choice == "2": print("Goodbye") break ...
772
225
def test_delete_bucket(gs): gs.delete_bucket()
51
20
"""Copyright [2020] [Jiatong Shi]. 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, softwar...
29,762
9,817
# Author Toshihiko Aoki # # 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, softw...
10,115
3,140
from django.urls import path from dev.views import FindMyIp,FindMyGps app_name = 'dev' urlpatterns = [ # path('', Main.as_view(), name = 'index'), path('findmyip', FindMyIp.as_view(), name = 'findmyip'), path('findmygps', FindMyGps.as_view(), name = 'findmygps'), ]
279
107
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ Topic: 处理html和xml文本 Desc : """ import html def html_xml(): s = 'Elements are written as "<tag>text</tag>".' print(s) print(html.escape(s)) # Disable escaping of quotes print(html.escape(s, quote=False)) s = 'Spicy Jalapeño' print(s.enc...
406
163
__all__ = ['db_utils', 'RfamDB', 'parse_taxbrowser']
53
23
__copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" from typing import Optional from . import FlatRecursiveMixin, BaseExecutableDriver, DocsExtractUpdateMixin class CraftDriver(DocsExtractUpdateMixin, FlatRecursiveMixin, BaseExecutableDriver): """Drivers inherit...
625
200
# Copyright 2017 Google 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 applicable law or ...
5,543
1,676
import datetime import json from ariadne import MutationType, QueryType, convert_kwargs_to_snake_case from ariadne_token_auth.decorators import login_required from django.contrib.auth import get_user_model from habits import models as habit_models from utils.general import get_user from utils.handlers.errors import Er...
5,876
1,929
import csv, pylab as pl, re DB = dict(); BD = dict(); whales_ = []; classes = []; line_num = 0; with open('data/train.csv', 'rb') as train_class_data: data = csv.reader(train_class_data, delimiter=','); for line in data: if (line_num == 0): line_num += 1; continue; keys...
2,542
1,015
from typing import Union from datetime import datetime import os import tempfile from contextlib import contextmanager import logging from collections import Counter import yaml logger = logging.getLogger(__name__) class Yammler(dict): _no_dump = ["changed"] _metavars = ["fspath", "updated_at"] def __i...
5,990
1,867
# Generated by Django 4.0.2 on 2022-03-25 11:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('calc', '0023_delete_handle_alter_calctag_options_and_more'), ] operations = [ migrations.CreateModel( name='Ldstp', ...
879
282
# -*- coding: utf-8 -*- import os # Module with fdf-aware dictionary from tkdict import FDFDict from aiida.orm.calculation.job import JobCalculation from aiida.common.exceptions import InputValidationError from aiida.common.datastructures import CalcInfo from aiida.common.utils import classproperty from aiida.common....
14,356
3,991
import uuid import os from datetime import datetime from django.db import transaction from api.management.data_script import OperationalDataScript from api.models.CompliancePeriod import CompliancePeriod from api.models.Organization import Organization from api.models.OrganizationActionsType import OrganizationActio...
5,974
1,871
from challenge.agoda_cancellation_estimator import AgodaCancellationEstimator from IMLearn.utils import split_train_test from IMLearn.base import BaseEstimator import numpy as np import pandas as pd def load_data(filename: str): """ Load Agoda booking cancellation dataset Parameters ---------- fi...
3,456
1,077
#!/usr/bin/env python3 import scripthelper scripthelper.add_argument("-n", "--name", help="Name to greet") logger, args = scripthelper.bootstrap_args() if args.name: logger.debug("Name was provided") logger.info(f"Hello {args.name}") else: logger.warning("Name was not provided")
294
103
#backslash and new line ignored print("one\ two\ three")
71
22
#!/usr/bin/env python r""" Front-facing script to find drifting, narrowband events in a set of generalized cadences of ON-OFF radio SETI observations. The main function contained in this file is :func:`find_event_pipeline` calls find_events from find_events.py to read a list of turboSETI .dat files. It then finds eve...
15,575
4,598
import numpy as np import matplotlib.pyplot as plt #Dahlquist test #sol1ex = lambda t: np.exp(-t) #sol2ex = lambda t: np.exp(-2*t) #oscillator 1 sol1ex = lambda t: np.cos(t**2/2) sol2ex = lambda t: np.sin(t**2/2) #oscillator 2 #sol1ex = lambda t: np.exp(np.sin(t**2)) #sol2ex = lambda t: np.exp(np.cos(t**2)) name = 'O...
1,558
788
"""MNE visual_92_categories dataset.""" from .kiloword import data_path, get_version
86
29
# Dmitry Kisler © 2020-present # www.dkisler.com from typing import List, Dict from sklearn.metrics import f1_score, accuracy_score def model_performance(y_true: List[List[str]], y_pred: List[List[str]]) -> Dict[str, float]: """Accuracy calculation function Args: y_true: List...
1,688
562
#!/usr/bin/env python3 """Interpret an L-String as a set of 3D Turtle commands and record the turtle's path. Multiple lines of input will be treated as a continuation of a single L-String. Default commandset: F,G - Step forward while drawing f,g - Step forward without drawing -,+ - Yaw around the normal ...
3,451
1,098
""" @author: yuboya """ ### pins position to be sent to robot ## from TransformationCalculation: import numpy as np import math def PointsToRobot(alpha, deltax,deltay,deltaz,xyzc): sina = math.sin(alpha) cosa = math.cos(alpha) pointrs = [] for pointc in xyzc: # ...
699
307
import requests import json from json import JSONDecodeError base_uri = "https://api.github.com/" licenses = ['afl-3.0', 'apache-2.0', 'artistic-2.0', 'bsl-1.0', 'bsd-2-clause', 'license bsd-3-clause', 'bsd-3-clause-clear', 'cc', 'cc0-1.0', 'cc-by-4.0', 'cc-by-sa-4.0', 'wtfpl', 'ecl-2.0', 'epl-1.0', 'epl-2.0', 'eu...
2,418
841
import os import tempfile import transaction from onegov.core import log from onegov.core.utils import safe_move class MailDataManager(object): """ Takes a postman and an envelope and sends it when the transaction is commited. Since we can't really know if a mail can be sent until it happens, we sim...
3,055
853
from django.conf import settings from django.db import models from django.dispatch import receiver from django.urls import Resolver404, resolve from django.utils.functional import cached_property from django.utils.translation import gettext_lazy as _ from cms import operations from cms.models import CMSPlugin, Placeho...
3,603
1,062
#!/usr/bin/env python #coding=utf-8 import json from lib.sqs import zhihufav_sqs from lib.tasks import add_note def get_sqs_queue(): sqs_info = zhihufav_sqs.get_messages(10) for sqs in sqs_info: sqs_body = sqs.get_body() receipt_handle = sqs.receipt_handle sqs_json = json.loads(sqs_bo...
553
221