text
string
size
int64
token_count
int64
""" Fatture in Cloud API v2 - API Reference Connect your software with Fatture in Cloud, the invoicing platform chosen by more than 400.000 businesses in Italy. The Fatture in Cloud API is based on REST, and makes possible to interact with the user related data prior authorization via OAuth2 protocol. # noq...
16,271
5,217
# coding: utf-8 import datetime import unittest import jpholiday class TestYear2018(unittest.TestCase): def test_holiday(self): """ 2018年祝日 """ self.assertEqual(jpholiday.is_holiday_name(datetime.date(2018, 1, 1)), '元日') self.assertEqual(jpholiday.is_holiday_name(datetime....
2,992
1,422
import numpy __author__ = 'roberto' def rad_degrees(type_to, value): if type_to == 'rad': value = value*numpy.pi/180 if type_to == 'deg': value = value*180/numpy.pi return value
222
93
""" conjur_api Package containing classes that are responsible for communicating with the Conjur server """ __version__ = "0.0.5" from conjur_api.client import Client from conjur_api.interface import CredentialsProviderInterface from conjur_api import models from conjur_api import errors from conjur_api import provid...
324
90
#!/usr/bin/env python # -*- coding: utf-8 -*- # # C++ version Copyright (c) 2006-2007 Erin Catto http://www.box2d.org # Python version by Ken Lauer / sirkne at gmail dot com # # This software is provided 'as-is', without any express or implied # warranty. In no event will the authors be held liable for any dam...
9,346
3,259
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import annotations import math class Point: def __init__(self, x: int = 0, y: int = 0): self.x = x self.y = y def __eq__(self, other: object) -> bool: if isinstance(other, Point): return (self.x == other.x) an...
1,309
449
""" Script to convert Zarr store to the NetCDF format file. Usage: python zarr_to_netcdf.py -i ZarrStoreName -o NetCDFFileName Convert Zarr data stored in ZarrStoreName to the NetCDF file NetCDFFileName. """ import argparse import timeit import warnings import xarray as xr from itscube_types import Coords, DataVars...
6,128
2,207
import pyaf.tests.periodicities.period_test as per per.buildModel((24 , 'B' , 200));
87
37
#!/usr/bin/env python # -*- coding: utf-8 -*- from conans import ConanFile, CMake, tools import os class CppHttpLibConan(ConanFile): name = "cpp-httplib" version = "0.2.1" url = "https://github.com/zinnion/conan-cpp-httplib" description = "A single file C++11 header-only HTTP/HTTPS server and client l...
932
339
from rest_framework.viewsets import ReadOnlyModelViewSet from backmarker.api.serializers.driver_serializer import DriverSerializer from backmarker.models.driver import Driver class DriverViewSet(ReadOnlyModelViewSet): queryset = Driver.objects.all() serializer_class = DriverSerializer lookup_field = "ref...
328
86
# -*- coding: utf-8 -*- """Response ====== Response Class """ from deepgo.core.kernel.popo import VO class Response(VO): def __init__(self): self.code = 0 def json(self): return self.__dict__
215
86
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pathlib import Path import pytest from pants.option.custom_types import ( DictValueComponent, ListValueComponent, UnsetBool, dict_with_files_option, dir_option, ...
4,793
1,851
str = "The quick brown fox jumps over the lazy dog." # initial string reversed = "".join(reversed(str)) #.join() method merges all of the charactera print(reversed[0:43:2]) # print the reversed string
201
67
import os import sys import syglass as sy from syglass import pyglass import numpy as np import tifffile import subprocess def extract(projectPath): project = sy.get_project(projectPath) head, tail = os.path.split(projectPath) # Get a dictionary showing the number of blocks in each level #codebreak() resolution_...
1,660
564
""" scaffoldgraph.analysis.enrichment Module contains an implementation of Compound Set Enrichment from the papers: - Compound Set Enrichment: A Novel Approach to Analysis of Primary HTS Data. - Mining for bioactive scaffolds with scaffold networks: Improved compound set enrichment from primary screening data. """ fr...
7,531
2,382
# Lee el fichero y procésalo de tal manera que sea capaz de mostrar # la temperatura máxima para una ciudad dada. Esa ciudad la debe poder # recibir como un argumento de entrada. Si la ciudad no existe, se deberá # manejar a través de una excepción. import csv provincia = input('Diga el nombre de la ciudad: ') with...
803
238
# Copyright (c) 2015 IBM Corporation and others. # # 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...
4,059
1,241
""" Plugs Newsletter Emails """ from plugs_mail.mail import PlugsMail class NewsletterSubscribed(PlugsMail): """ Email sent to subscriber after newsletter subscription """ template = 'NEWSLETTER_SUBSCRIBED' description = 'Email sent to subscriber after newsletter subscription' class NewsletterUns...
537
157
# -*- coding: utf-8 -*- import os import sys import mimetypes from io import BytesIO try: from urllib2 import Request, urlopen, URLError from urllib import urlencode except ImportError: from urllib.request import Request, urlopen from urllib.parse import urlencode from urllib.error import URLError...
4,526
1,305
#!/usr/bin/python import fileinput import json url_base = "https://dds.cr.usgs.gov/srtm/version2_1/SRTM3" regions = [ "Africa", "Australia", "Eurasia", "Islands", "North_America", "South_America", ] srtm_dict = {} srtm_directory = "srtm.json" for region in regions: print("Processing", ...
775
312
from configs.icra_benchmark.config import BaseEnvConfig, BasePolicyConfig, BaseTrainConfig, Config class EnvConfig(BaseEnvConfig): def __init__(self, debug=False): super(EnvConfig, self).__init__(debug) class PolicyConfig(BasePolicyConfig): def __init__(self, debug=False): super(PolicyConfig...
495
153
from django.apps import AppConfig class BiosConfig(AppConfig): name = 'bios'
83
28
from __future__ import absolute_import from datetime import datetime, timedelta import six import time import logging from sentry.utils.compat.mock import patch, Mock from sentry.event_manager import EventManager from sentry.eventstream.kafka import KafkaEventStream from sentry.eventstream.snuba import SnubaEventStre...
3,982
1,184
#! /bin/bash/python3 '''Ejemplo de un script que puede ser importado como módulo.''' titulo = "Espacio muestral" datos = (76, 81, 75, 77, 80, 75, 76, 79, 75) def promedio(encabezado, muestra): '''Despliega el contenido de encabezado,así como el cálculo del promedio de muestra, ingresado en una lista o tu...
470
204
genres = ['blues', 'classical', 'country', 'disco', 'hiphop', 'jazz', 'metal', 'pop', 'reggae', 'rock'] num_files = 100 with open(f'INPUT_FULL', 'w') as f: for genre in genres: for i in range(num_files): for j in range(6): f.write(f'/datasets/duet/genres/{genre}.{i:05d}.{j}.wav /...
368
160
import jinja2 import os import socket my_public_ip = os.popen("curl -L http://metadata/computeMetadata/v1beta1/instance/network-interfaces/0/access-configs/0/external-ip").read() my_private_ip = socket.gethostbyname(socket.gethostname()) template_contents = open('/root/appscake/nginx_config').read() template = jinja2...
549
189
#!/usr/bin/env python3 import sys from Window import Window from Constants import * from Algorithms.MergeSort import MergeSort from Algorithms.QuickSort import QuickSort from Algorithms.BubbleSort import BubbleSort from Algorithms.InsertionSort import InsertionSort from Algorithms.SelectionSort import SelectionSor...
909
264
from typing import Any import fastjsonschema from ..permissions.permission_helper import has_perm from ..permissions.permissions import Permissions from ..shared.exceptions import PermissionDenied, PresenterException from ..shared.patterns import Collection, FullQualifiedId from ..shared.schema import required_id_sch...
3,688
1,014
"""User specific settings.""" import matplotlib as mpl import matplotlib.pyplot as plt mpl.rcParams['font.size'] = 7 mpl.rcParams['pdf.fonttype'] = 42 mpl.rcParams['ps.fonttype'] = 42 mpl.rcParams['font.family'] = 'arial' mpl.rcParams['mathtext.fontset'] = 'stix' seqcmap = mpl.cm.cool_r try: import seaborn as sn...
638
245
# SPDX-License-Identifier: MIT from resolver.mindeps.__main__ import entrypoint, get_min_deps # noqa: F401 __all__ = ('entrypoint', 'get_min_deps')
152
65
#!/usr/bin/env python """ Commands that update or process the application data. """ from datetime import datetime import json from bs4 import BeautifulSoup from flask import render_template from fabric.api import task from fabric.state import env from facebook import GraphAPI from twitter import Twitter, OAuth from j...
9,433
3,146
from __future__ import annotations __all__ = ['Trainer'] from collections.abc import Callable, Collection, Iterator from dataclasses import dataclass import torch import torch.nn as nn import torch.optim from tqdm.auto import tqdm from .. import ichunked from .. import metrics as m from ._loader import _Loader from...
4,277
1,371
#!/usr/bin/env python # -*- coding: utf-8 -*- # # trapeza-import.py # # Copyright 2013-2014 David Reed <david@ktema.org> # This file is available under the terms of the MIT License. # from itertools import groupby from operator import itemgetter, attrgetter import hashlib import io import os import sys import pi...
14,450
3,923
#!/bin/python3 # author: Jan Hybs import tests tests.fix_paths() import yaml from unittest import TestCase from cihpc.cfg.config import global_configuration from cihpc.common.utils import extend_yaml repeat_yaml = ''' foo: !repeat a 5 ''' range_yaml = ''' foo: !range 1 5 bar: !range 1 2 6 ''' sh_yaml = ''' foo:...
1,200
418
from OrderedVector import OrderedVector class Greedy: def __init__(self, goal): self.goal = goal self.found = False self.travelled_distance = 0 self.previous = None self.visited_cities = [] def search(self, current): current.visited = True self.visited_...
991
279
import os import sys from dataclasses import dataclass import click import numpy as np import xgboost as xgb from rich import print, traceback WD = os.path.dirname(__file__) @click.command() @click.option('-i', '--input', required=True, type=str, help='Path to data file to predict.') @click.option('-m', '--model', ...
3,262
1,109
from .base_operator import QuantOperatorBase from .qdq_base_operator import QDQOperatorBase from ..quant_utils import QuantizedValue # For operators that support 8bits operations directly, and output could # reuse input[0]'s type, zeropoint, scale; For example,Transpose, Reshape, etc. class Direct8BitOp(QuantOperatorB...
1,597
485
from platform import architecture from qiling import Qiling from typing import Union from asm_practice.coding.challenge import ArchSpec, Challenge, TestCase challenges = [] amd64 = ArchSpec( pwntools_arch="amd64", pwntools_os="linux", qiling_rootfs="qiling/examples/rootfs/x86_linux/", qiling_ostype="...
3,659
1,387
""" Copyright 2020 The Magma Authors. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES O...
2,331
653
import graphene from ....order import OrderStatus, models from ...core.mutations import ModelBulkDeleteMutation class DraftOrderBulkDelete(ModelBulkDeleteMutation): class Arguments: ids = graphene.List( graphene.ID, required=True, description='List of draft order IDs t...
732
210
from threading import Thread from typing import Any, Iterable, Mapping from types_extensions import Function, void, safe_type class CallbackThread(Thread): """ An extension to python's threading API allowing for a callback to be executed upon completion of the given function. The callback is executed wit...
1,978
580
# proxy module from traitsui.wx.button_editor import *
55
18
# Copyright 2020 University of Adelaide # # 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 ...
2,756
1,290
from django.utils.html import format_html def full_address(self): return format_html('%s - <b>%s,%s</b>' % (self.address, self.city, self.state)) # null derek yazylmaly hat admin.site.empty_value_display = '???' admin.site.register(Item) # str funksivany ady bilen gorkezyar class ItemAdmin(admin.ModelAdmin): ...
4,723
1,490
from standard import HDB, NatureStd if __name__ == "__main__": hb = HDB('hbba') db = HDB('dbba') data = db.search('政务云工程评价指标体系及方法') print(data) # first_record = data["records"][0] # name = f'{first_record["code"]}({first_record["chName"]}' # db.download(pk=first_record['pk'], name=name) ...
465
223
from __future__ import division, absolute_import, print_function from past.builtins import xrange import unittest import numpy.testing as testing import numpy as np import fitsio import os from numpy import random from redmapper import Cluster from redmapper import Configuration from redmapper import CenteringWcenZre...
6,478
2,259
""" usage: turn all docx files into markdown files python run_pandoc.py transform-docs turn all tex files nto markdown files python run_pandoc.py transform-docs --doctype=tex move all csv, md, pptx, docx, png, jpeg, jpg etc. into Book/subdir folders, where subdir is the suffix filename and write a file ...
6,581
2,166
from PIL import Image from PIL import ImageFile from io import BytesIO import _webp def _accept(prefix): return prefix[:4] == b"RIFF" and prefix[8:16] == b"WEBPVP8 " class WebPImageFile(ImageFile.ImageFile): format = "WEBP" format_description = "WebP image" def _open(self): self.mode = "RGB"...
979
378
from turtle import Turtle, Screen from random import choice from time import sleep from queue import SimpleQueue w: int w, h = (853, 480) wn = Screen() wn.screensize(w, h) wn.bgcolor("#d3d3d3") Room_state = {"Clean": "#FFFFFF", "Dirty": "#b5651d"} cleaned = 0 def filler(t, color, delay=0, vacclean = ...
4,149
1,750
d = {'key1': 1, 'key2': 2, 'key3': 3} for k in d: print(k) # key1 # key2 # key3 for k in d.keys(): print(k) # key1 # key2 # key3 keys = d.keys() print(keys) print(type(keys)) # dict_keys(['key1', 'key2', 'key3']) # <class 'dict_keys'> k_list = list(d.keys()) print(k_list) print(type(k_list)) # ['key1', 'key...
1,226
604
import django DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } INSTALLED_APPS = ['flows', 'flows.statestore.tests', 'django_nose'] SECRET_KEY = 'flow_tests' if django.VERSION < (1, 6): TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner' TES...
560
225
from rest_framework import serializers from localground.apps.site.api.serializers.base_serializer import \ BaseSerializer, NamedSerializerMixin, ProjectSerializerMixin, \ GeometrySerializerMixin from localground.apps.site import models, widgets from localground.apps.site.api import fields import re class Vide...
4,154
1,110
# Testing out some stuff with async and await async def hello(name): print ("hello" + name) return "hello" + name # We can use the await statement in coroutines to call # coroutines as normal functions; i.e. what it implies is that # if we runt return await func(*args) in a courtoune # is like running r...
957
320
#!/usr/bin/python import numpy as np from matplotlib import pyplot as plt theta = np.asarray([[.8,.2],[.1,.9]]) psi = np.asarray([3.,9.]) N = 100 K = 2 # sample z z = np.empty(N,dtype='int') z[0] = 1 for i in range(1,N): z[i] = np.random.choice(np.arange(K),size=1,replace=True,p=theta[z[i-1]]) y = np.random.r...
465
241
""" Copyright (c) 2017 Cyberhaven Copyright (c) 2017 Dependable Systems Laboratory, EPFL 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 right...
19,721
5,894
import collections from functools import lru_cache from itertools import groupby, permutations from operator import attrgetter from typing import Counter, FrozenSet, Generic, List, Tuple, TypeVar, Union, cast from attr import attrs, evolve from .basic_types import Beat, CheaperFraction, NoteObject, Time, make_ordered...
11,758
3,592
# WS server chat import asyncio import websockets import torch from transformers import AutoTokenizer, AutoModel, AutoModelWithLMHead model_name = "sberbank-ai/rugpt2large" # "sberbank-ai/rugpt3large_based_on_gpt2" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelWithLMHead.from_pretrained(mode...
2,271
758
import binascii import io import os import ssl from .compat import decode_from_bytes, encode_to_bytes SSL_PROTOCOL = ssl.PROTOCOL_SSLv23 class MocketSocketCore(io.BytesIO): def write(self, content): super(MocketSocketCore, self).write(content) from mocket import Mocket if Mocket.r_fd a...
1,595
647
number = int(input()) raiz = number/2 for i in range(1,20): raiz = ((raiz ** 2) + number) / (2 * raiz) print(raiz)
121
56
import gym import numpy as np import torch import Config import NN import json PATH_DATA = 'models/data23.15.9.40.json' PATH_MODEL = 'models/model23.15.9.40.p' with open(PATH_DATA, 'r') as f: json_load = json.loads(f.read()) obs_rms_mean = np.asarray(json_load["obs_rms_mean"]) obs_rms_var = np.asarra...
1,726
692
import json from PIL import Image with open('/home/tianpei.qian/workspace/data_local/sl4_front_1.0/sl4_side_val_1.7.json') as f: val_1_7 = json.load(f) with open('sl4_side_val_1.7/results.json') as f: new_1_8 = json.load(f) ROOT = '/home/tianpei.qian/workspace/data_local/sl4_front_1.0/' for old, new in zip(...
1,111
470
""" Generate data for ablation analysis for ICML 2017 workshop paper. """ import random from torch.nn import functional as F from railrl.envs.pygame.water_maze import ( WaterMazeMemory, ) from railrl.exploration_strategies.ou_strategy import OUStrategy from railrl.launchers.launcher_util import ( run_experime...
3,815
1,241
from setuptools import setup with open('README.md', encoding='utf-8') as f: long_description = f.read() setup( name='Py-Meta-Utils', version='0.7.8', description='Metaclass utilities for Python', long_description=long_description, long_description_content_type='text/markdown', url='https...
1,053
354
import math # Returns a percentile of an array. It is assumed that the array is already # sorted. # # The array must not be empty. # # Percentile must have a value between [0, 1.0]. def percentile(array, percentile): assert len(array) assert percentile >= 0.0 and percentile <= 1.0 index = int(math.ceil(percentil...
363
120
"""Classes for use with Yambo Representation of a spectrum. Main functionality is to read from Yambo output, o.qp files and also netcdf databases. """ import re import copy as cp import numpy as np import asetk.atomistic.fundamental as fu import asetk.atomistic.constants as atc from . import cube class Dispersion: ...
9,512
3,177
import unittest import os import json import pandas as pd import numpy as np class TestingExercise2_07(unittest.TestCase): def setUp(self) -> None: ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(ROOT_DIR, '..', 'dtypes.json'), 'r') as jsonfile: self.dtyp =...
733
253
""" The implementation of PAN (Pyramid Attention Networks) based on Tensorflow. @Author: Yang Lu @Author: Zan Peng @Github: https://github.com/luyanger1799 @Github: https://github.com/Cousin-Zan @Project: https://github.com/luyanger1799/amazing-semantic-segmentation """ from utils import layers as custom_layers from ...
6,684
2,665
from uuid import UUID from sqlalchemy import select, bindparam from nivo_api.cli.bra_record_helper.persist import persist_zone, persist_massif from nivo_api.core.db.connection import connection_scope from nivo_api.core.db.models.sql.bra import ZoneTable, DepartmentTable, MassifTable from test.pytest_fixtures import...
2,340
720
class Item: def __init__(self,weight,value) -> None: self.weight=weight self.value=value self.ratio=value/weight def knapsackMethod(items,capacity): items.sort(key=lambda x: x.ratio,reverse=True) usedCapacity=0 totalValue=0 for i in items: if usedCapacity+i.weight<=c...
780
264
import itertools import numpy as np from jspp_imageutils.image.types import GenImgArray, GenImgBatch from typing import Tuple, Iterable, Iterator # TODO: fix everywhere the x and y axis nomenclature """ chunk_image_on_position -> returns images chunk_image_generator -> returns images chunk_data_image_generator -> re...
4,146
1,368
if __name__ == "__main__": import argparse import pickle import os from tqdm import tqdm from build_scene import * from block_data import COLOR_BID_MAP BLOCK_DATA = pickle.load( open("/private/home/aszlam/minecraft_specs/block_images/block_data", "rb") ) allowed_blocktypes ...
1,598
588
import requests # Copyright 2017 Xiaomi, 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 agree...
1,256
425
"""Manage interfaces on HPCOM7 devices. """ from pyhpecw7.utils.xml.lib import reverse_value_map from pyhpecw7.features.errors import InterfaceCreateError, InterfaceTypeError,\ InterfaceAbsentError, InterfaceParamsError, InterfaceVlanMustExist from pyhpecw7.features.vlan import Vlan from pyhpecw7.utils.xml.lib im...
18,904
5,034
from django.contrib import admin from django.urls import path, include from src.base import urls as base_api urlpatterns = [ path('admin/', admin.site.urls), path('rest_api/', include( base_api.urlpatterns )), ]
233
74
"""Compute ordinary Voronoi diagrams in Shapely geometries.""" import operator import numpy import scipy.spatial import shapely.geometry import shapely.geometry.base import shapely.prepared def pointset_bounds(coords): return ( min(coords, key=operator.itemgetter(0))[0], min(coords, key=operator...
1,610
551
"""Plots composite saliency map.""" import argparse import numpy import matplotlib matplotlib.use('agg') from matplotlib import pyplot from gewittergefahr.gg_utils import general_utils as gg_general_utils from gewittergefahr.gg_utils import file_system_utils from gewittergefahr.plotting import imagemagick_utils from m...
12,147
4,497
#!/usr/bin/env python3 # =============================================================================== # NAME: CompFactory.py # # DESCRIPTION: This is a factory class for instancing the Component # and building up the Port and Arg configuration required. # # AUTHOR: reder # EMAIL: reder@jpl.nasa.gov # D...
16,089
4,465
class Node: """ A node class used in A* Pathfinding. parent: it is parent of current node position: it is current position of node in the maze. g: cost from start to current Node h: heuristic based estimated cost for current Node to end Node f: total cost of present n...
7,896
2,332
""" Setup file """ import os from setuptools import setup, find_packages HERE = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(HERE, "README.rst")).read() CHANGES = open(os.path.join(HERE, "CHANGES.rst")).read() REQUIREMENTS = [ "dynamo3>=0.4.7", "future>=0.15.0", "pyparsing==2.1....
1,765
595
import multiprocessing import csv_exporter from combination.brute_force_combination_algorithm import \ BruteForceCombinationAlgorithm from combination.combiner import Combiner from combination.constrained_combination_algorithm import \ ConstrainedCombinationAlgorithm from config.config_importer import ConfigIm...
3,368
1,084
from setuptools import setup import src setup(name='lsankidb', version=src.__version__, install_requires=['AnkiTools'], description='"ls" for your local Anki database.', #FIXME this duplicates README.md long_description=""" .. image:: https://cdn.jsdelivr.net/gh/AurelienLourot/lsankidb@c...
1,959
650
from output.models.ibm_data.valid.s3_12.s3_12v06_xsd.s3_12v06 import ( ChildTypeBase, ChildTypeDerived, CtAlt1, CtAlt2, CtBase, Root, ) __all__ = [ "ChildTypeBase", "ChildTypeDerived", "CtAlt1", "CtAlt2", "CtBase", "Root", ]
274
131
import logging from injector import inject, singleton from starlette.config import Config from common.database import BaseDatabase LOGGER = logging.getLogger(__name__) @singleton @inject class MasterDatabase(BaseDatabase): def __init__(self, config: Config) -> None: super().__init__(config) se...
936
276
from . import baco_show # solution === (new_dataset, best_ant_road, acc_before_run, best_fit_so_far, total_feature_num, best_selected_features_num, best_fitnesses_each_iter, average_fitnesses_each_iter ,num_of_features_selected_by_best_ant_each_iter, time_temp, sample_num) def draw_baco(solution): if(len(solu...
832
304
# Copyright 2015-2019 Ilgar Lunin, Pedro Cabrera # 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...
2,035
672
from stix_shifter_utils.modules.base.stix_transmission.base_delete_connector import BaseDeleteConnector class DeleteConnector(BaseDeleteConnector): def __init__(self, api_client): self.api_client = api_client def delete_query_connection(self, search_id): return {"success": True}
307
93
#!/usr/bin/env python import sys import pprint from model.cs_rep import CS_Rep from pytz import timezone, utc from datetime import datetime, timedelta from lib.calendar import Google_Calendar, google_ts_to_datetime, DEFAULT_DATE, LOS_ANGELES_TZ from lib.conf import CFG from model.db_session import DB_Session_Factory f...
6,525
1,887
"""Can messenger class.""" from __future__ import annotations import asyncio from inspect import Traceback from typing import List, Optional, Callable, Tuple import logging from opentrons_hardware.drivers.can_bus.abstract_driver import AbstractCanDriver from opentrons_hardware.firmware_bindings.arbitration_id import (...
5,500
1,516
import cv2 import rect import numpy as np class Scanner(object): def __init__(self): pass def __del__(self): pass def auto_canny(self, image, sigma=0.33): v = np.median(image) lower = int(max(0, (1.0 - sigma) * v)) upper = int(min(255, (1.0 + sigma) * v)) ...
3,390
1,166
#LeetCode problem 54: Spiral Matrix class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: if(len(matrix)==0 or len(matrix[0])==0): return [] res=[] rb=0 re=len(matrix) cb=0 ce=len(matrix[0]) while(re>rb and ce>cb): ...
797
270
# python3 """Testing code to run the typed_ast based pyi parser.""" import sys from pytype import module_utils from pytype.pyi import parser from pytype.pyi.types import ParseError # pylint: disable=g-importing-member from pytype.pytd import pytd_utils if __name__ == '__main__': filename = sys.argv[1] with op...
717
256
from django.contrib import admin from .models import * admin.site.register(University) admin.site.register(Faculty) admin.site.register(Subject) admin.site.register(Teacher)
176
57
from pettingzoo.classic import tictactoe_v3 import os os.environ['CUDA_VISIBLE_DEVICES'] = '-1' import tensorflow as tf if tf.test.gpu_device_name(): print('GPU found') else: print("No GPU found") from src.q_learning.agent.agent import Agent from src.q_learning.network.dqn import DQN from src.q_learning.polici...
1,333
472
import multiprocessing import os bind = "{0}:{1}".format(os.environ.get('HOST', '0.0.0.0'), os.environ.get('PORT', '8080')) workers = os.environ.get('WORKERS', multiprocessing.cpu_count() * 2 + 1)
199
85
import pytest from tests.test_crud.main import app @pytest.fixture(scope='session', autouse=True) def startup(): import asyncio # asyncio.run(app.router.startup()) loop = asyncio.get_event_loop() loop.run_until_complete(app.router.startup())
261
94
from django.db import models """ Konzept: Man soll sich als Ehemaliger in die DB eintragen können (Nutzeraccount dafür nötig?) Es gibt ein Textfeld für den Lebenslauf und die Auswahl des aktuellen Ortes und der Tätigkeit. ehem, das kommt mir ziemlich eng vor, so wie die alte Version der olymp-db """ from Grundge...
794
259
from __future__ import absolute_import from time import sleep import sys from datetime import datetime from os.path import getmtime import random import requests import atexit import signal import logging from market_maker.bitmex import BitMEX from market_maker.settings import settings from market_maker.utils import l...
15,921
4,581
import numpy as np def import_accuracy(y_test, predictions): errors = abs(predictions - y_test) mape = 100 * (errors / y_test) accuracy = 100 - np.mean(mape) return accuracy
179
73
import pytest from django.urls import reverse @pytest.mark.skip(reason="WIP moving to pytest tests") def test_with_authenticated_client(client, django_user_model): email = 'admin@somewhere.com' password = 'password123' admin_user = django_user_model.objects.create_superuser( email, password) c...
2,406
756
###################################################################### # mat4 - Matrix class (4x4 matrix) # # Copyright (C) 2002, Matthias Baas (baas@ira.uka.de) # # You may distribute under the terms of the BSD license, as # specified in the file license.txt. ####################################################...
24,375
11,436