text
string
size
int64
token_count
int64
import pytest def define_benchmarked_example(name, example): import matplotlib matplotlib.use("Agg") image = example() @pytest.mark.parametrize("n", [512, 1024, 2048]) def benchmark_test(benchmark, n): filename = None if n == 512: filename = "docs/_static/examples...
425
147
import smtplib smtpUser = '' smtpPass = '' toAdd = '' fromAdd = smtpUser subject = '' header = 'To: ' + '\n' + 'From: ' + fromAdd + '\n' + 'Subject :' + subject body = '' print header + '\n' + body smtp = smtplib.SMTP('smtp.gmail.com', 587) smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login(smtpUser, smtpPass)...
387
174
#! /usr/bin/env python from zplot import * import sys import random # a simple label/arrow combination function def label_with_arrow(canvas, x, y, text, size, anchor, dx, dy): ax, ay = x, y if anchor == 'top': ay = ay + size elif anchor == 'bottom': ay = ay - size else: print '...
1,376
568
import glob import os import python_nbt.nbt as nbt import requests from pycraft.error import PycraftException from pycraft.region import Region class Player: def __init__(self, world_path): if not os.path.exists(world_path): print(f'Saved world not found: "{world_path}"') raise P...
2,700
866
inp = [] with open("input", "r") as f: for line in f.readlines(): inp = inp + line.rsplit()[0].split(",") # In form (BUS_ID, index) busses = [(int(x), i) for i, x in enumerate(inp[1:]) if x != "x"] # Chinese remainder theorem time = 0 prod = 1 for id, i in busses: while (time + i)%id != 0: ...
387
159
import os from setuptools import setup, find_packages def parse_requirements(filename): """ load requirements from a pip requirements file """ lineiter = (line.strip() for line in open(filename)) return [line for line in lineiter if line and not line.startswith("#")] version = '0.1.1' README="""Djang...
1,143
340
#!/usr/bin/env python from __future__ import division, print_function from WMCore.Database.DBFormatter import DBFormatter class GetSubsWithoutJobGroup(DBFormatter): """ _GetSubsWithoutJobGroup_ Finds whether there are unfinished subscriptions for Production and Processing task types where JobCreato...
1,599
459
import os import glob import collections import json import numpy as np from absl import app, flags flags.DEFINE_string('results_dir', 'results/linkpred_d_sweep/fsvd', 'Directory where run files are written.') FLAGS = flags.FLAGS def main(_): files = glob.glob(os.path.join(FLAGS.results_dir, '*...
1,092
395
# Copyright (c) 2021 Emanuele Bellocchia # # 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, merge, publish,...
3,737
1,048
# coding: utf-8 from django import forms from django.utils.translation import ugettext_lazy as _ from captcha.fields import ReCaptchaField from .models import Signatory from .utils import mark_safe_lazy as safe HELP_CAPTCHA = safe(_('Just a small act to prevent spam. <em>Sorry about this!</em>')) class SignupForm(f...
738
237
import json def save_json(file_path, mappings): with open(file_path, "w+") as file: json.dump(mappings, file) def file_to_speaker_map(speaker_to_file_map): file_to_speaker = {} for speaker in speaker_to_file_map: files = speaker_to_file_map.get(speaker) for file in files: ...
768
268
#!/usr/bin/env python3 import requests import json import sys #area(32.227754,-110.959464,32.236005,-110.944097); overpass_url = "http://overpass-api.de/api/interpreter" overpass_query = """ [out:json]; area[name="Tucson"]; (node["building"="yes"](area); way["building"="yes"](area); rel["building"="yes"](area); ); ...
2,232
858
# -*- coding: utf-8 -*- qntCaso = int(input()) for caso in range(qntCaso): numTotalRena, numTotalRenaPuxaraoTreno = map(int, input().split()) listRena = [list(map(str, input().split())) for linha in range(numTotalRena)] listRena = sorted(listRena, key= lambda x: (-int(x[1]),int(x[2]),float(x[3]),x[0])...
485
200
""" Tests for signal handlers. """ import logging import pytest from course_access_groups.models import Membership from course_access_groups.signals import ( on_learner_account_activated, on_learner_register, ) from test_utils.factories import ( MembershipRuleFactory, UserFactory, UserOrganizatio...
2,754
857
# # Copyright 2021 Red Hat Inc. # SPDX-License-Identifier: Apache-2.0 # """Query Handling for all APIs.""" import datetime import logging from dateutil import parser from dateutil import relativedelta from django.core.exceptions import FieldDoesNotExist from django.db.models.functions import TruncDay from django.db.mo...
12,180
3,404
import sys import click @click.command('group', short_help='Create user group') @click.option('--name', help='Group name') @click.option('--text', help='Description of user group') @click.option('--delete', '-D', metavar='ID', help='Delete user group using ID') @click.pass_obj def cli(obj, name, text, delete): "...
649
200
test = { 'name': 'q4c', 'points': 2, 'suites': [ { 'cases': [ {'code': ">>> top_lac_schools.labels == ('Name', 'City', 'Region', 'Applied', 'Admitted', 'Enrolled', 'Acceptance Rate')\nTrue", 'hidden': False, 'locked': False}, {'code': '>>> top_lac_schools.num_rows == 1...
1,677
596
#!/usr/bin/env python3 import rospy from std_msgs.msg import String class hello: def __init__(self): self.word = "Hello," self.pub = rospy.Publisher('/hello', String, queue_size=1) self.rate = rospy.Rate(1) def publish_word(self): while not rospy.is_shutdown(): ...
492
171
class SVGMgr: def __init__(self, blob: bytes): self.blob = blob self.payload_name = "unsigned char* payload[]" self.chunk_size = 10 def mask(self) -> dict[str:str]: """Mask the data as a X""" # format the blob! return self.format_blob() def format_blob(self...
766
247
# Simple path demo # Meant to demonstrate the WA Simulator API # ----------------------------------------------------------------- # Import the simulator import wa_simulator as wa import matplotlib.pyplot as plt # Command line arguments parser = wa.WAArgumentParser(use_sim_defaults=False) parser.add_argument("-p", "-...
1,348
488
# coding: utf-8 # ### Machine Learning Application - Genre Classification # UDSL-SNU Big Data Academy # 20170725 # ##### Import libraries # In[1]: import h5py import numpy as np import matplotlib.pyplot as plt from sklearn import cross_validation from sklearn.preprocessing import StandardScaler from sklearn.me...
4,684
1,972
from typing import Any import json import base64 import binascii import datetime as dt __all__ = ("JSON",) class JSON(json.JSONEncoder): """A JSON encoder that supports datetime values.""" def default(self, o): if isinstance(o, dt.datetime): return o.astimezone(dt.timezone.utc).isoform...
1,232
386
# https://openpyxl.readthedocs.io/ # https://automatetheboringstuff.com/chapter12/ # https://www.ablebits.com/office-addins-blog/2014/09/24/excel-drop-down-list/ # http://stackoverflow.com/questions/18595686/how-does-operator-itemgetter-and-sort-work-in-python from canvas.core.courses import get_course_by_sis_id,...
6,023
2,138
import yaml class FeatureAnalysis(object): def __init__(self, **kwargs): self.input_params = {} self.yaml_data = None self.input_params.update(kwargs) self.yaml_data = self._load_yaml() def _load_yaml(self): ''' Read yaml template from path @param file...
3,949
1,248
""" *********************************************************************** This code has been sourced from https://github.com/bninja/pika-pool/blob/master/pika_pool.py Governed by the following BSD licence sourced from https://github.com/bninja/pika-pool/blob/master/LICENSE. No copyright notice is available. Redistr...
7,359
2,466
# Copyright 2008-2015 Luc Saffre # # License: BSD (see file COPYING for details) """See :mod:`ml.boards`. .. autosummary:: :toctree: models mixins """ from lino.api import ad, _ class Plugin(ad.Plugin): "See :class:`lino.core.Plugin`." verbose_name = _("Boards") def setup_config_menu(con...
702
271
#!/usr/bin/env python # Copyright (c) 2002-2008 ActiveState Software # Author: Trent Mick (trentm@gmail.com) """Quick directory changing (super-cd) 'go' is a simple command line script to simplify jumping between directories in the shell. You can create shortcut names for commonly used directories and invoke ...
1,628
548
''' Unit tests to verify that our proposed proximity functions work as expected. Proximity function (defined in Util) are used to determine if two estimated parameters are "close enough" within some numerical tolerance to be treated as equivalent. We eventually use these functions to assess whether learning algorithms...
2,294
875
# Copyright (c) 2020 Arda Seremet <ardaseremet@outlook.com> TURN_ON_BASE = 16 TURN_OFF_BASE = 116 TOGGLE_BASE = 0 TEMP_MONOSTABLE_BASE = 200 STATUS_XML_PATH = "status.xml"
173
87
from sympy import * from sympy.abc import * import functions as func from decimal import * def findAbsFuncU(function, U, variable, means, roundornot=True): """ This function is used to find the absolut compound U, as well as the values of U of temp variables :param function: (String) the formula ...
3,672
1,255
# -*- coding: utf-8 -*- """ This module contains metadata about the project. """ from __future__ import unicode_literals title = 'swid_generator' version = '1.1.0' description = 'Application which generates SWID-Tags from Linux installed packages, package-files and ' \ 'directories using tools like DPGK ...
489
154
''' Contains generalized events and the command handlers. ''' #pylint: disable=too-few-public-methods import logging import types from collections import defaultdict # Events # Event constants: # Format: NAME = 'identifier' # when, (args) BOT_START = 'tombot.bot.start' # bot's start, (bot) BOT_SHUTD...
3,946
1,207
from dataclasses import dataclass from .cards import Trick from .player import Player from .partners import TeamID from .game_actions import BaseAction class BaseEvent: pass @dataclass(frozen=True) class ActionTakenEvent(BaseEvent): player: Player action: BaseAction def __str__(self): retu...
638
203
"""Common functionality module."""
35
8
from abc import ABCMeta, abstractmethod import unsupervised.clustering.utils.initial_assignments as init_assign class ICluster: __metaclass__ = ABCMeta def __init__(self, data): self.X = data self.assign = [] self.centroids = [] self.initial_assignment = init_assign.random_assig...
425
126
''' 将有序数组转换为二叉搜索树 给你一个整数数组 nums ,其中元素已经按 升序 排列,请你将其转换为一棵 高度平衡 二叉搜索树。 高度平衡 二叉树是一棵满足「每个节点的左右两个子树的高度差的绝对值不超过 1 」的二叉树。 ''' from typing import List class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right ''' 思路:递归创建树。 时间复杂度:O(n) 空间...
990
469
import urllib2 import threading import Configuration import cv def download(url): try: response = urllib2.urlopen(url, timeout = 5) data = response.read() return data except Exception, e: print str(e) return None class DownloaderThread(threading.Thread): def __init_...
1,863
538
#=============================================================================== # SM 2/2016 # Code exclusively for computing association_index_attacker using full # association index given the pair of attackers (M, N) and data D. #=============================================================================== import...
1,310
624
import os import torch import logging from PIL import Image from itertools import compress from torch.utils.data import DataLoader, RandomSampler, SequentialSampler import torchvision.transforms as transforms from torchvision.datasets import ImageFolder from pynet.datasets.core import AbstractDataManager, DataItem, Set...
8,800
2,641
#!/usr/bin/env python from time import sleep import rospy from rdda_ur5_control.srv import SetRddaParam, RddaData, Move, MoveTraj, NoParam if __name__ == "__main__": rospy.wait_for_service('rdda_ur5_control/home_rdda') rospy.wait_for_service('rdda_ur5_control/set_rdda_stiffness') rospy.wait_for_service('r...
1,734
748
#!/usr/bin/env python3 import numpy as np import os import dill import json import pandas as pd import torch import matplotlib.pyplot as plt import plotly.graph_objects as go from smp_manifold_learning.motion_planner.feature import SphereFeature, LoopFeature from smp_manifold_learning.differentiable_models.utils impor...
24,569
7,206
import urllib.request,json from .models import Quote get_quote_url='http://quotes.stormconsultancy.co.uk/random.json' def get_quote(): ''' This gets thejson respond and allows you to access the url information ''' with urllib.request.urlopen(get_quote_url) as url: get_quote_data = url.read(...
1,062
315
from ioc_writer import ioc_api from ioc_writer import ioc_et from ioc_writer import ioc_common from ioc_writer import utils from ioc_writer import managers __all__ = ['ioc_api', 'ioc_common', 'ioc_et', 'utils', 'managers']
222
81
import os , json import requests from github import Github, InputGitAuthor import conf dir_path = os.path.dirname(os.path.realpath(__file__)) # OAUTH APP clientId = conf.clientID clientSecret = conf.clientSecret def ask_user_permission(code): """ get user permission when authenticating via github""" res = None ...
3,537
1,210
# install package before running: # pip install bibtexparser import bibtexparser with open('publications.bib') as bibtex_file: # bib_database = bibtexparser.load(bibtex_file) bib_database = bibtexparser.bparser.BibTexParser(common_strings=True).parse_file(bibtex_file) md_string = "" for entry in bib_database...
1,928
694
#!/usr/bin/env python3 import setuptools with open("requirements.txt") as fh: install_requires = fh.read() name = "bento_filters" version = "1.0.0" release = "1.0.0" setuptools.setup( name=name, version=release, author="LightArrowsEXE", author_email="Lightarrowsreboot@gmail.com", description...
698
247
# coding=utf-8 from tqdm import tqdm import sys import argparse from torch import optim from basic_opt import * from prototypical_loss import prototypical_loss as loss_fn from protonet import ProtoNet sys.path.append(os.getcwd()) from dataset.data_loader import data_loader from torch.optim.lr_scheduler import MultiSte...
5,256
1,881
import os from typing import Optional, List from kcu import sh, kpath def create_scenes( in_path: str, output_folder_path: str, threshold: float=0.5, min_scene_duration: float=1.5, max_scene_duration: float=30, debug: bool=False ) -> Optional[List[str]]: os.makedirs(output_folder_path,...
2,141
734
# -*- coding: utf-8 -*- # Copyright 2022 <Huawei Technologies Co., Ltd> # # 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 # # Unle...
1,294
488
#!/usr/bin/python # _*_ coding: utf-8 _*_ """ # Author: Piotr Miller # e-mail: nwg.piotr@gmail.com # Website: http://nwg.pl # Project: https://github.com/nwg-piotr/tint2-executors # License: GPL3 # Credits: RaphaelRochet/arch-update # https://github.com/RaphaelRochet/arch-update # Icon by @edskeye Arguments [-C<aur_...
5,097
1,689
# -*- coding: utf-8 -*- """ tests.unit.doc_test ~~~~~~~~~~~~~~~~~~~~ """ # Import Python libs from __future__ import absolute_import import collections import logging import os import re # Import Salt libs import salt.modules.cmdmod import salt.utils.files import salt.utils.platform from tests.support.runtes...
21,558
6,632
import glob mult=1 with open("combined_blocks_clustered.csv", 'w') as outfile: for f in glob.glob("*hierarchical_clusters.csv"): print f with open(f, 'rU') as infile: if mult==1: outfile.write(infile.next()) else: infile.next() for line in infile: line = line.strip()...
733
281
# Copyright (c) 2022, White Hat Global and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import cint, cstr from frappe.model.document import Document class ProductOptions(Document): def validate(self): sel...
1,913
689
from .tcplotter import time_vs_temp from .tcplotter import eu_vs_radius from .tcplotter import rate_vs_radius_eu from .tcplotter import rate_vs_age_tc
151
53
'''display_sars_cov2_infection_study_results.py This script is executed using the CMD tag in the Dockerfile in order to display modeling study results to the console and to an html site allocated on the host machine. ''' from flask import Flask, render_template from shutil import move from os import getcwd app = Flas...
884
290
import requests from stem import Signal from stem.control import Controller from fake_useragent import UserAgent import random, time headers = { 'User-Agent': UserAgent().random } print(requests.get('https://ident.me', headers=headers).text) proxies = { 'http': 'socks5://127.0.0.1:9050', 'https': 'socks5://...
871
318
from PIL import Image import imagehash import os import pandas as pd class RemoveDuplicate: def __init__(self,img_ds_path, csv_file_path = None, csv_file_name = 'dataset.csv'): self.img_ds_path = img_ds_path self.hash_db = set() self.count_duplicate = 0 self.count_corrupt = 0 ...
2,781
848
""" argparse.py Argument parser helper for both the UWSGI runner and CLI Credits: https://mike.depalatis.net/blog/simplifying-argparse.html """ import sys import argparse HEADER = """ ___. \_ |__ _________ | __ \ / _ \__ \ | \_\ ( <_> ) __ \_ |___ /\____(____ / \/ ...
1,327
414
import networkx as nx import pandas as pd import numpy as np class hierarchy: G=nx.DiGraph() def __init__(self,nodes): self.G.add_node('0', depth = 0) n = open(nodes,'r') for line in n.readlines(): self.get_nodes(line.strip()) def get_nodes(self,line): node_name="" edge_name="" nodes = ...
2,420
1,089
#!/usr/bin/env python import copy import os import sys; sys.path.append(os.getcwd()) # Handle relative imports from ricecooker.utils import downloader, html_writer from ricecooker.chefs import SushiChef from ricecooker.classes import nodes, files from ricecooker.config import LOGGER # Use logger ...
12,058
3,424
from tkinter import * from tkinter import ttk import os.path #para checar se o arquivo existe import solicitar import imprimir import fechar icone = ".\data\icone.ico" icone_existe = os.path.exists(icone) while True: cor_fundo = 'white' fonte_texto = "Arial" tamanho_texto = 12 tamanho_titulo = 16 ...
5,085
1,786
from flask import Flask, request, flash from flask import render_template from flask import redirect from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///listasuper.sqlite3' app.config['SECRET_KEY'] = 'uippc3' db = SQLAlchemy(app) class Super(db.Model): ...
1,966
674
from ._jsontemplate import *
29
11
import scipy.io from matplotlib import pyplot as plt import numpy as np def load_imu_data(): dt = 0.01 gyro_data = scipy.io.loadmat('./source/11.ARS/ArsGyro.mat') acce_data = scipy.io.loadmat('./source/11.ARS/ArsAccel.mat') ts = np.arange(len(gyro_data['wz'])) * dt gyro = np.concatenate([ ...
4,309
1,751
import typing def binary_search( predicate: typing.Callable[[int], bool], lower_bound: int, upper_bound: int, ) -> typing.Optional[int]: """ Find the positive integer threshold below which a search criteria is never satisfied and above which it is always satisfied. Parameters --------...
1,119
289
# Note: Kaggle only runs Python 3, not Python 2 # We'll use the pandas library to read CSV files into dataframes import pandas as pd import numpy as np from sklearn import preprocessing from sklearn.linear_model import SGDRegressor from sklearn import decomposition, pipeline, metrics, grid_search from sklearn.metrics ...
8,326
5,741
''' given a wordking dir calculate the result for each epoch saving and save it as txt file ''' import os import mmcv import argparse import os.path as osp import shutil import tempfile import torch import torch.distributed as dist from mmcv.runner import load_checkpoint, get_dist_info from mmcv.parallel import MMDat...
2,482
978
import grpc import logging from absl import app, flags import example_python.app_02_grpc.proto.greeter_pb2 as greeter_pb2 import example_python.app_02_grpc.proto.greeter_pb2_grpc as greeter_pb2_grpc flags.DEFINE_integer('port', 50051, 'Port to serve book service on') def main(argv): client = greeter_pb2_grpc.Gr...
573
213
# Copyright (c) 2015, Frappe Technologies Pvt Ltd and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.website.website_generator import WebsiteGenerator from frappe.website.utils import get_comment_list class FrappeJo...
3,118
1,205
import math if(__name__=="__main__"): pos1=[-5,-2] #positions of the bots pos2=[-9,2] ang1=123 #initial direction of bots ang2=21 def cosinv(num): #function to return cos inverse in degrees ang=math.acos(num) ang=180*ang/(math.pi) return(ang) def ro...
2,314
1,025
import pandas as pd from internal_review.set_internal_review_file import set_internal_review_files from utils.PUMA_helpers import clean_PUMAs, puma_to_borough def access_to_jobs(geography, write_to_internal_review=False): indicator_col_name = "access_employment_count" clean_df = load_clean_source_data(indicat...
1,346
445
# A compilation of Python programs for learning purposes. def print_hi(name): print(f'Hi, {name}') # Press the green button in the gutter to run the script. if __name__ == '__main__': print_hi('Python') # See PyCharm help at https://www.jetbrains.com/help/pycharm/
279
95
""" run the scrape bot from inside the project using an exported function from this module. """ __all__ = ['run'] from scrapy.crawler import CrawlerProcess from .spiders import JobScraperSpider def run(url): process = CrawlerProcess({ 'USER_AGENT': 'AppleWebKit/537.36 (KHTML, like Gecko)' }) pr...
388
137
import argparse import sys import os import time reload(sys) sys.setdefaultencoding('utf-8') sys.path.insert(0, "/misc/kcgscratch1/ChoGroup/jasonlee/dl4mt-c2c/bpe2char") # change appropriately import numpy import cPickle as pkl from mixer import * def translate_model(jobqueue, resultqueue, model, options, k, normal...
8,272
2,730
import os from cacgan.data import FormulaDataset, GroupAB from cacgan.gans import AugCycleGan from cacgan.gans import Trainer from cacgan.utils import SEED, seed_rng, load_pkl """ print a txt file describing the structure of augcyc """ seed_rng(SEED) dataset = load_pkl("../dataset/dataset_ab.pkl") dataset: FormulaD...
607
236
# Generated by Django 3.1.2 on 2020-10-17 13:50 import django.contrib.auth.models from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('reddit_dashboard', '0001_initial'), ] operations = [ migrations.AlterModelManagers( name='dashboarduse...
894
266
import ctypes import csv import os import numpy as np import tflite_runtime.interpreter as tflite import time import platform import collections import operator ''' source /home/cristian/virtualenvs/coral/bin/activate python test_accuracy.py ''' # Configuration parametres print_results = True load_results = False writ...
20,473
7,109
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Aug 13 13:31:08 2018 @author: nmei Cross experiment validation """ import os working_dir = '../data/' import pandas as pd from tqdm import tqdm pd.options.mode.chained_assignment = None import numpy as np from sklearn.metrics import roc_auc_score fr...
10,037
3,111
# -*- coding: utf-8 -*- """ Created on Fri Jul 26 17:43:03 2019 @author: Eric Danielson """ from skimage import io import os import argparse from tqdm import tqdm argparser = argparse.ArgumentParser( description='Train and validate YOLO_v2 model on any dataset') argparser.add_argument( '-i',...
924
334
# Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC (NTESS). # Under the terms of Contract DE-NA0003525 with NTESS, # the U.S. Government retains certain rights in this software. # #This script starts the HQTrace Plugin #@Christopher Wright #@category HQTracer #@keybinding alt shift t #@menupa...
574
197
#!/env/usr/bin python """ server.py Tool to visualize GPS coordinates for donkeycar. """ from flask import Flask, request, send_from_directory, jsonify import json # File that stores the GPS markers DATA_FILE = 'data.json' # JSON status messages SUCCESS = {'status' : {'success': True}} FAIL = {'status': {'success':...
2,816
878
# Copyright 2019 Brian Quinlan # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
6,635
2,134
# -*- coding: utf-8 -*- # @Time : 02/01/2021 23:37 # @Author : tomtao # @Email : tp320670258@gmail.com # @File : urls.py # @Project : error_view_demo from django.urls import path from . import views urlpatterns = [ path('405.html', views.view_405, name='405'), path('403.html', views.view_403, name='403') ]
316
150
from eurostatapiclient.models.dataset import dimension_list_size from eurostatapiclient.models.dimension import ItemList, Dimension import unittest from eurostatapiclient.models.dataset import Dataset import datetime import json import os TEST_ASSET_DIR = os.path.join(os.path.dirname(__file__), 'assets') ADD_DATASET =...
3,376
1,069
from __future__ import unicode_literals from MediaTracker.flask_app_and_db import flask_app as app from MediaTracker import models from flask import render_template, request from MediaTracker.forms import MediaForm from MediaTracker.controllers import media_controller, tag_controller from urllib.parse import urlencode...
3,001
897
#!/usr/bin/env python import ply.lex as lex # Commonmark specification by John MacFarlane # http://spec.commonmark.org/0.21/ # The spec uses BMP Unicode codepoints: # U+NNNN where 0000 <= NNNN <= FFFF # https://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane # The building blocks are: # character, li...
3,448
948
# greeting = input("Kya naam hai aapka?") # print(greeting) # greeting = input("Kya naam hai aapka?") # print(greeting) greeting = input("Hello, pirate ji! Andar aane ka password batao?") if "AbraKaDabra" == greeting: print("Andar aao ji!") else: print("Bhaag jaa pirate!")
283
117
# 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 2.3.33.0 # ...
4,409
1,113
"""Test methods in `qibo/core/hamiltonians.py`.""" import pytest import numpy as np from scipy import sparse from qibo import hamiltonians, K from qibo.tests.utils import random_complex def random_sparse_matrix(n, sparse_type=None): if K.name in ("qibotf", "tensorflow"): nonzero = int(0.1 * n * n) ...
11,446
4,517
import matplotlib.pyplot as plt import datetime as datetime import numpy as np import pandas as pd import talib import seaborn as sns from time import time from sklearn import preprocessing from pandas.plotting import register_matplotlib_converters from .factorize import FactorManagement import scipy.stats as stats imp...
9,451
3,096
import numpy as np from cykhash import count_if_int64, count_if_int64_from_iter, Int64Set_from, Int64Set_from_buffer from cykhash import count_if_int32, count_if_int32_from_iter, Int32Set_from, Int32Set_from_buffer from cykhash import count_if_float64, count_if_float64_from_iter, Float64Set_from, Float64Set_from_buffe...
3,179
1,383
''' A test simulation involving the SEIR flu model in isolation. ''' from pram.data import GroupSizeProbe, ProbeMsgMode from pram.entity import Group, Site from pram.rule import SEIRFluRule from pram.sim import Simulation rand_seed = 1928 probe_grp_size_flu = GroupSizeProbe.by_attr('flu', SEIRFluRule.ATTR, SE...
1,188
466
from models.model_zoo import *
31
11
from ProjectEulerCommons.Base import * Answer( int(''.join(map(str, first_true_value(permutations(list(range(10))), pred = lambda enum: enum[0] == 1000000 - 1)))) ) """ ------------------------------------------------ ProjectEuler.Problem.024.py The Answer is: 2783915460 Time Elasped: 1.132969617843628sec...
374
139
import pytest from test_first import fake _SENTINEL = 'test_first-sentinel-a72004be-7a66-42f5-bdcf-7d71eb7283e3' class Patcher: def __init__(self): self.__stack = [] def __call__(self, module, attribute, mock = None): if hasattr( module, attribute ): original = getattr( module, at...
866
270
from os import listdir, makedirs from os.path import abspath, basename, dirname, isdir, join import re import csv import numpy as np import pandas as pd from scipy import stats, ndimage, signal import matplotlib.pyplot as plt from matplotlib import cm, rc from mpl_toolkits.axes_grid1 import make_axes_locatable from ma...
12,721
5,200
# File: splunkoncall_consts.py # # Copyright (c) 2018-2021 Splunk Inc. # # Licensed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) # # Define your constants here INTEGRATION_URL_MISSING = "Integration URL required in asset configuration" UPDATE_INCIDENT_ERROR = "Error updating incident"
309
117
"""Utility functions to parse master NIST table. """ from astropy.table import Column, Table, vstack import glob import numpy as np def sort_table_by_element(table, elem_list): """Build table based on list of elements Parameters ---------- table: astropy table Table to sort elem_list: lis...
1,716
535
import aiohttp from typing import Dict class CenterBankApi: """ class implements api cbr """ def __init__(self, session: aiohttp.ClientSession) -> None: self.link = "https://www.cbr-xml-daily.ru/daily_json.js" self.obj = dict() self.date: str = "" self.session: aiohtt...
1,223
391
import sys sys.path.insert(0, '..') sys.path.insert(0, '../EnergyCost') from qpthlocal.qp import QPFunction from qpthlocal.qp import QPSolvers from qpthlocal.qp import make_gurobi_model from ICON import * from sgd_learner import * from sklearn.metrics import mean_squared_error as mse from collections import defaultdict...
40,932
12,782