text
string
size
int64
token_count
int64
#!/usr/bin/python3 from prometheus_client import start_http_server, Gauge import urllib.request import random from datetime import datetime import re import time test = False risks = ["vent violent", "pluie-inondation", "orages", "inondation", "neige-verglas", "canicule", "grand-froid", "avalanches", "vagues-submersi...
3,634
1,262
# # Copyright (C) [2020] Futurewei Technologies, Inc. # # FORCE-RISCV is 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 # # THIS SOFTWARE IS PR...
2,058
655
# main.py #----------------------------------------------------------------------# # # # #----------------------------------------------------------------------# from math import floor from sqlite3 import OperationalError import string, sqlite3 from urllib.parse import urlparse import http.server import socketserver ...
2,104
697
import base64 import os import random import re import socket import sys import ssl import string if sys.version_info[0] == 2: from BaseHTTPServer import HTTPServer as Server from SimpleHTTPServer import SimpleHTTPRequestHandler as Handler from SocketServer import ThreadingMixIn from httplib import UNA...
6,968
2,117
import flask from flask import Flask, url_for from tensorflow.keras.applications.imagenet_utils import preprocess_input, decode_predictions from tensorflow.keras.models import load_model from tensorflow.keras.preprocessing import image import numpy as np # instantiating a class object app = Flask(__name__) model_pat...
903
293
from __future__ import absolute_import from .helper import convert, run_aggregate_sims from django.core.files import File from celery import shared_task from django.core.mail import EmailMultiAlternatives from django.conf import settings from anymail.exceptions import AnymailError from config.celery import app from .m...
5,419
1,705
# Copyright 2022 Google LLC. # # 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, ...
6,566
2,382
import os from nornir.plugins.inventory import SimpleInventory dir_path = os.path.dirname(os.path.realpath(__file__)) class Test: def test(self): host_file = f"{dir_path}/data/hosts.yaml" group_file = f"{dir_path}/data/groups.yaml" defaults_file = f"{dir_path}/data/defaults.yaml" ...
9,680
2,293
import argparse import json import os import requests import lib.cf as cf import lib.aws as aws import lib.gh as gh version = "v1.0" api_base = 'https://api.cloudflare.com/client/v4/zones' api_key = os.getenv("CLOUDFLARE_API_KEY") content_type = 'application/json' email = os.getenv("CLOUDFLARE_EMAIL") github_repo = "...
5,016
1,294
from flask import request, jsonify from functools import wraps from schema import SchemaError def json_required(func): @wraps(func) def wrapper(*args, **kwargs): if not request.data or not request.json: return jsonify({ 'status': 'Error', 'reason': 'No JSON ...
867
218
#============================================================================= # # JDI Unit Tests # #============================================================================= """ JDI Unit Tests ============== Run all unit tests from project's root directory. python -m unittest discover python3 -m unittes...
362
95
""" CourseGrade Class """ from abc import abstractmethod from collections import OrderedDict, defaultdict from ccx_keys.locator import CCXLocator from django.conf import settings from lazy import lazy from openedx.core.lib.grade_utils import round_away_from_zero from xmodule import block_metadata_utils from .confi...
13,380
3,540
import os import feedparser import json from flask import Flask, request # Add your Slack token to the variable below. SLACK_TOKEN = "" url = "" payload = {} headers = {'content-type': 'application/json'} app = Flask(__name__) # this endpoint listens for incoming slash commands from Slack. @app.route('/horos', metho...
1,385
484
import os.path as osp PATH_TO_ROOT = osp.join(osp.dirname(osp.realpath(__file__)), '..', '..', '..') import sys sys.path.append(PATH_TO_ROOT) import pickle import time import numpy as np import torch from torch.utils.tensorboard import SummaryWriter from torch.optim.lr_scheduler import StepLR from models.pointnet.src.u...
9,507
2,483
import base64 import hashlib import json import logging from dataclasses import dataclass import boto3 log = logging.getLogger() region = "us-east-1" def handle(event: dict, context): request = event["Records"][0]["cf"]["request"] try: authenticate(request["headers"]) except Exception as e: ...
1,581
509
#Copyright (c) 2017 Ultimaker B.V. #Cura is released under the terms of the LGPLv3 or higher. import gc from UM.Job import Job from UM.Application import Application from UM.Mesh.MeshData import MeshData from UM.Preferences import Preferences from UM.View.GL.OpenGLContext import OpenGLContext from UM.Message import ...
11,674
3,264
from datasets import load_metric def compute_metrics(pred): pearson = load_metric("pearsonr").compute references = pred.label_ids predictions = pred.predictions metric = pearson(predictions=predictions, references=references) return metric
262
75
#Задача 3. Вариант 1. #Напишите программу, которая выводит имя "Иво Ливи", и запрашивает его псевдоним. Программа должна сцеплять две эти строки и выводить полученную строку, разделяя имя и псевдоним с помощью тире. name=input('Герой нашей сегодняшней программы - Иво Ливи. \nПод каким же именем мы знаем этого человека?...
442
191
import io import logging import os import pathlib from datetime import datetime from typing import List from musiquepy.data.errors import MusiquepyExistingUserError from musiquepy.data.media import get_profile_pictures_dir from musiquepy.data.model import ( Album, AlbumPhoto, Artist, MusicGenre, MusicTrack, User) ...
3,523
1,123
import random from copy import deepcopy, copy import timeit adrMask = 63 #mask to get our addr bits cmdMask = 192 #mask to get our command bits stepLim = 500 #Limited num of instructions tourFlag = int(input("Input 1 for tournament, 0 for roulette")) mixFlag = int(input("Input 1 for mixed children, 0...
7,301
2,728
import enchant ##Use our custom word list wordList = enchant.request_pwl_dict("truncListWords.txt") ##Takes our string from the stage and checks it def checkForWord(playerString) : return wordList.check(playerString)
233
79
from .widgets_base import WidgetsBase class PageWidget(WidgetsBase): def __init__(self, templates_engine, request, settings, schema={}, resource_ext=None, disabled=False, **kwargs): super(PageWidget, self).__init__(templates_engine, request, **kwargs) self.base_path = kwargs.get('base_path', "/")...
2,264
690
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, SubmitField, TextAreaField from wtforms.validators import ValidationError, DataRequired, Email, EqualTo, Length from app.models import User from flask import request class CreateChallengeForm(FlaskForm): name = StringField('...
1,000
295
# -*- coding: utf-8 -*- """ Copyright (C) 2013 TopCoder Inc., All Rights Reserved. This is the module that defines logging helper methods This module resides in Python source file logginghelper.py Thread Safety: It is thread safe because no module-level variable is used. @author: TCSASSEMBLER @version: 1.0 """ import...
1,302
355
""" Given a permutation of any length, generate the next permutation in lexicographic order. For example, this are the permutations for [1,2,3] in lexicographic order. # >>> list(it.permutations([1,2,3])) [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)] Then, your function next_permutation(t:tuple)...
2,566
861
# 魔术师 def show_magicians(magicians): for magician in magicians: print('magician\'s name is ' + magician) def make_great(magicians): i = 0 for item in magicians: magicians[i] = 'The Great ' + item i = i + 1 magicians = ['singi', 'sunjun'] make_great(magicians) show_magicians(ma...
329
129
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ """ import numpy as np import matplotlib.pyplot as plt import os import h5py import sys import time import seaborn as sns import pandas as pd sys.path.append('/home/atekawade/TomoEncoders/scratchpad/voids_paper/configs') from params import model_path, get_model_p...
4,889
1,900
from flask import Flask, jsonify, Response, request, make_response, render_template from definitions.passenger import Passenger import json,util,io,random import iris from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib.backends.backend_svg import FigureCanvasSVG from matplotlib.figure import Fi...
13,919
4,489
from unihan_db.tables import ( UnhnLocation, UnhnLocationkXHC1983, UnhnReading, kCantonese, kCCCII, kCheungBauer, kCheungBauerIndex, kCihaiT, kDaeJaweon, kDefinition, kFenn, kFennIndex, kGSR, kHanYu, kHanyuPinlu, kHanyuPinyin, kHDZRadBreak, kIICore...
10,390
3,716
import time import numpy as np from matplotlib import pyplot as plt from sylwek.similarity_measure import SimilarityMeasure from utils import mnist_reader class DataProvider: images = {} labels = {} similarity_measure = None next_id = -1 #TODO 2. Prosimy nadać każdemu obrazkowi unikalny identyfikator...
2,373
803
from __future__ import absolute_import, division, print_function import iotbx.pdb import mmtbx.model from mmtbx.building.cablam_idealization import cablam_idealization, master_phil import sys import libtbx.load_env pdb_str = """\ ATOM 2327 N GLY A 318 169.195 115.930 63.690 1.00216.32 N ATOM 23...
4,933
2,984
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.exceptions import ValidationError import unittest from erpnext.stock.doctype.batch.batch import get_batch_qty, UnableToSelect...
9,835
4,153
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed May 25 16:02:58 2022 @author: erri """ import os import numpy as np import math from morph_quantities_func_v2 import morph_quantities import matplotlib.pyplot as plt # SINGLE RUN NAME run = 'q07_1' DoD_name = 'DoD_s1-s0_filt_nozero_rst.txt' # Step betw...
35,768
13,741
#--------------------------------------------------------Import libraries import pickle import socket import struct import cv2 from stable_baselines import PPO2 import numpy as np import imageio #--------------------------------------------------------Establiosh connection s = socket.socket(socket.AF_INET,socket.SOCK_...
1,987
615
# -*- coding: utf-8 -*- import asyncio import ccxt.async_support as ccxt async def poll(tickers): i = 0 kraken = ccxt.kraken() while True: symbol = tickers[i % len(tickers)] yield (symbol, await kraken.fetch_ticker(symbol)) i += 1 await asyncio.sleep(kraken.rateLimit / 100...
502
194
# 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 may ...
3,198
848
# from django.shortcuts import render # Create your views here. from django.urls import reverse_lazy from django.views.generic import CreateView from fitbox.consultas.forms import ConsultaForm from fitbox.consultas.models import Consulta class ConsultaCreateView(CreateView): template_name = "consultas/cadastro_...
447
143
import os STATIC_FOLDERS = ( '{{cookiecutter.repo_name}}/common/static', '{{cookiecutter.repo_name}}/users/static', ) # Muffin Plugins PLUGINS = ( 'muffin_jinja2', 'muffin_peewee', 'muffin_session', ) # Plugins configurations SESSION_SECRET = 'SecretHere' SESSION_LOGIN_URL = '/users/signin/' JI...
598
241
""" NetRef - transparent network references implementation. """ import sys import inspect import types import cPickle as pickle from rpyc.core import consts _local_netref_attrs = frozenset([ '____conn__', '____oid__', '__class__', '__cmp__', '__del__', '__delattr__', '__dir__', '__doc__', '__getattr__', '__g...
6,905
2,208
# # Author    : Manuel Bernal Llinares # Project   : trackhub-creator # Timestamp : 11-09-2017 11:10 # --- # © 2017 Manuel Bernal Llinares <mbdebian@gmail.com> # All rights reserved. # """ Configuration Manager for this HPC Module """ if __name__ == '__main__': print("ERROR: This script is part of a pipeline co...
381
139
#!/usr/bin/env python """ Testscript to demonstrate functionality of pyGCluster This script imports the data of Hoehner et al. (2013) and executes pyGCluster with 250,000 iterations of resampling. pyGCluster will evoke 4 threads (if possible), which each require approx. 1.5GB RAM. Please make sure you have enough ...
3,230
1,066
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright (C) 2020 The SymbiFlow Authors. # # Use of this source code is governed by a ISC-style # license that can be found in the LICENSE file or at # https://opensource.org/licenses/ISC # # SPDX-License-Identifier: ISC """ Utilities for converting between file form...
6,767
2,188
from typing import List, Dict from sc2.ids.ability_id import AbilityId from sc2.position import Point2 from sc2.unit import Unit from sc2.units import Units from sharpy.interfaces import IZoneManager from sharpy.managers.core.roles import UnitTask from sharpy.plans.acts import ActBase from sharpy.sc2math import get_in...
3,602
1,114
# Generated by Django 2.1.3 on 2020-02-28 21:32 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('content_management', '0045_auto_20200228_1345'), ] operations = [ migrations.RemoveField( model...
621
202
import os from fnmatch import fnmatch from typing import Iterator, List, Optional, Sequence, Tuple, Union import numpy as np from typing_extensions import Literal from . import lib from .otf import TemporaryOTF from .util import PathOrArray, _kwargs_for, imread def rl_cleanup(): """Release GPU buffer and cleanu...
12,700
4,102
# coding=utf-8 import tensorflow as tf v = tf.Variable(0, dtype=tf.float32, name='v3') # 在没有声明滑动平均模型时只有一个变量v,所以下面的语句只会输出v:0 for variables in tf.global_variables(): print(variables.name) ema = tf.train.ExponentialMovingAverage(0.99) # 加入命名空间中 maintain_averages_op = ema.apply(tf.global_variables()) # 在申明滑动平均模型之后,T...
816
399
from .Sequential import Sequential
35
10
"""Nothing here, really."""
28
9
# Released under the MIT License. See LICENSE for details. # # This file was automatically generated from "rampage.ma" # pylint: disable=all points = {} # noinspection PyDictCreation boxes = {} boxes['area_of_interest_bounds'] = (0.3544110667, 5.616383286, -4.066055072) + (0.0, 0.0,...
1,748
1,171
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'e:/GIT/PyFlow/PyFlow/UI/Widgets\GraphEditor_ui.ui', # licensing of 'e:/GIT/PyFlow/PyFlow/UI/Widgets\GraphEditor_ui.ui' applies. # # Created: Sat May 4 12:25:24 2019 # by: pyside2-uic running on PySide2 5.12.0 # # WARNING! All changes ...
7,945
2,550
#!/usr/bin/env python3 import api from urllib.parse import urljoin GREEN = 'G' YELLOW = 'Y' GRAY = '.' with open('wordlist.txt') as wordlist_file: wordlist = tuple(line.strip() for line in wordlist_file) class Game: def __init__(self): response = api.start_new_game() self._game_id = respon...
995
333
""" validataclass Copyright (c) 2021, binary butterfly GmbH and contributors Use of this source code is governed by an MIT-style license that can be found in the LICENSE file. """ from datetime import date from typing import Any from .string_validator import StringValidator from validataclass.exceptions import Invali...
1,450
413
#!/usr/bin/python import sys, os, struct, array, time try: import tos except ImportError: import posix sys.path = [os.path.join(posix.environ['TOSROOT'], 'support', 'sdk', 'python')] + sys.path import tos if len(sys.argv) < 2: print "no device specified" print "example:" print " simpleAccelGyro...
1,810
691
# -*- coding: utf-8 -*- # see LICENSE.rst """Basic Astronomy Functions. .. todo:: change this to C / pyx. whatever astropy's preferred C thing is. """ __author__ = "" # __copyright__ = "Copyright 2018, " # __credits__ = [""] # __license__ = "" # __version__ = "0.0.0" # __maintainer__ = "" # __email__ = "" # __...
597
215
import numpy as np import itertools from numpy.polynomial import chebyshev as cheb """ Module for defining the class of Chebyshev polynomials, as well as various related classes and methods, including: Classes: ------- Polynomial: Superclass for MultiPower and MultiCheb. Contains methods and ...
28,922
8,502
#!/usr/bin/env python # coding: utf-8 from __future__ import print_function from __future__ import absolute_import import os import re import shutil import stat import sys import tct from os.path import exists as ospe, join as ospj from tct import deepget params = tct.readjson(sys.argv[1]) binabspath = sys.argv[2] ...
5,072
1,588
"""Base definitions for the websocket interface""" import json from abc import ABC, abstractmethod class WebsocketConnectionLost(Exception): pass class AbstractWSManager(ABC): @abstractmethod async def send(self, conn_id: str, msg: dict) -> None: # This is implemented as a separate method primar...
693
195
""" A module that provides main API for optimal (LSQ) "matching" of weighted N-dimensional image intensity data using (multivariate) polynomials. :Author: Mihai Cara (contact: help@stsci.edu) :License: :doc:`../LICENSE` """ import numpy as np from .lsq_optimizer import build_lsq_eqs, pinv_solve, rlu_solve __all__...
10,312
3,257
# -*- coding: utf-8 -*- # pylint: disable=redefined-outer-name,protected-access """Salt worker main test module.""" from __future__ import (absolute_import, division, print_function, unicode_literals, with_statement) import watchmaker.utils try: from unittest.mock import patch except Impor...
2,705
1,103
import logging import random import time import src.support.outbound_routing as ob from src.support.creds import build_cred, build_proof_request, build_schema, build_credential_proposal, build_proof_proposal import src.support.settings as config # This file containst the functions that perform transaction-specific # ...
18,256
5,743
#!/usr/bin/env python # encoding: utf-8 from .render import Render from .fraction import Fraction from .generic import first_elem, last_elem __all__ = ['post2in_fix', 'tex_render', 'txt_render'] # ------------------------ # A infix to postfix list convertor p2i_infix = {"+": "+", "-": "-", "*": "*", "/" : "/", ":":...
2,843
1,160
# # To run locally, execute: # # spark-submit --master local[2] wide_and_deep_example.py # S3_ROOT_DIR = 's3://{YOUR_S3_BUCKET}/{YOUR_S3_PATH}/' batch_size = 100 worker_count = 1 server_count = 1 import metaspore as ms spark = ms.spark.get_session(batch_size=batch_size, worker_count=wo...
1,813
631
"""The bias-variance tradeoff Often, researchers use the terms "bias" and "variance" or "bias- variance tradeoff" to describe the performance of a model—that is, you may stumble upon talks, books, or articles where people say that a model has a "high variance" or "high bias." So, what does that mea...
1,213
316
# -*- coding: UTF-8 -*- """ Pytron - Links Mark II Interface ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Links for Python :copyright: (c) 2016 by Scott Doucet / aka: traBpUkciP. :license: BSD, see LICENSE for more details. """ from .client import * __copyright__ = 'Copyright 2016 by traBpUkciP' __versi...
496
216
import pytest @pytest.mark.models( 'backends/mongo/report', 'backends/postgres/report', ) def test_update_object(model, app): app.authmodel(model, ['insert', 'patch', 'getone']) resp = app.post(f'/{model}', json={ 'status': 'ok', 'sync': { 'sync_revision': '1', ...
2,324
792
# dockerpty. # # Copyright 2014 Chris Corbyn <chris@w3style.co.uk> # # 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 ap...
1,979
565
import os from collections import Counter from django.core.exceptions import ValidationError from django.utils import timezone from django.utils.deconstruct import deconstructible from django_documents_tools.exceptions import ( BusinessEntityCreationIsNotAllowedError) from django_documents_tools.manager import se...
3,639
1,022
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import (Column, Integer, Text, DateTime) Base = declarative_base() class Report(Base): """ This class defines the tab...
2,989
873
import matplotlib import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import numpy as np import empyrical as ep from matplotlib.ticker import FuncFormatter def plot_returns(returns, live_start_date=None, ax=None): """ Plots raw returns over time. Bac...
12,712
4,071
from .routes import Bolck_Segmenter_BLUEPRINT from .routes import Bolck_Segmenter_BLUEPRINT_WF #from .documentstructure import DOCUMENTSTRUCTURE_BLUEPRINT
154
54
# # PySNMP MIB module HPN-ICF-8021PAE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-8021PAE-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:24:57 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
9,672
4,538
import numpy as np from astroquery.hitran import Hitran from astropy import units as un from astropy.constants import c, k_B, h, u def calc_solid_angle(radius,distance): ''' Convenience function to calculate solid angle from radius and distance, assuming a disk shape. Parameters ---------- radius ...
5,978
2,736
# coding: utf-8 from __future__ import unicode_literals from django.contrib.auth.models import User from django.test import TestCase from voting.models import Vote from test_app.models import Item # Basic voting ############################################################### class BasicVotingTests(TestCase): ...
6,513
2,266
# Lint as: python3 # Copyright 2020 The Abseil Authors. # # 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 l...
1,040
308
# -*- coding: utf-8 -*- """ Created on Sat Feb 8 11:20:09 2020 @author: Donovan """ class ImagePreprocessing: """@package ImagePreprocessing This class extracts a number of features from the images and saves them in a CSV to be used by the machine learning class. """ import cv2 #conda in...
10,149
3,475
import json import os def main(): features = { "type": "FeatureCollection", "features": [] } directory = "poly/" for file in os.listdir(directory): if file.endswith(".poly"): name = os.path.basename(file).split(".")[0] with open(os.path.join(directory, f...
1,349
366
from optparse import OptionParser kafkabroker = "" kafkatopic = "" rssfile = "" helpstring = """Usage: newsreader.py [OPTIONS]... -f <RSS_FILE> <KAFKA_BROKER> <KAFKA_TOPIC> Read news articles from XML rss feeds specified in <RSS_FILE> Feeds must be separated by newlines Feeds to be ignored can be prefixed with # Ma...
881
286
from random import shuffle#自带洗牌方法 from copy import deepcopy class Solution(object): def __init__(self, nums): """ :type nums: List[int] :type size: int """ self.nums=nums def reset(self): """ Resets the array to its original configurati...
636
222
# Copyright (c) Facebook, Inc. and its affiliates. import numpy as np from termcolor import colored import logging import torch.nn as nn import torch.utils.data log = logging.getLogger(__name__) import torch import numpy as np import math class Dataset(torch.utils.data.Dataset): def __init__(self, x, y): ...
11,319
3,745
from . import config def write_to_css(css): f = open( f"output/{'b' if config.bmethod else 'p'}/{config.filename}.css", "w") f.write(css) f.close() def write_to_HTML(html): f = open( f"output/{'b' if config.bmethod else 'p'}/{config.filename}.html", "w") f.write(html) f.close...
323
128
import marshal o = [-1, 1.23456789, complex(1.2, 3.4)] o += [True, False, None] o += ["Hello World!", u"Hello World!"] o += [{ "Key" : "Value" }, set(["Set"]), frozenset(["FrozenSet"]), (1, 2, 3), [1, 2, 3]] for i in o: s = marshal.dumps(i) r = marshal.loads(s) print "Dumping:", i, "Loaded", r
307
150
import unittest import os import sys import argparse import numpy as np import audacity as aud print('Module file:') print(aud.__file__) SCRIPT_DIR = os.path.split(os.path.realpath(__file__))[0] PACKAGE_DIR = os.path.realpath(os.path.join(SCRIPT_DIR,'..')) DATA_DIR = os.path.join(PACKAGE_DIR, 'data') TEST_FILE_1 = ...
1,956
691
import argparse import sys from pathlib import Path import matplotlib.pyplot as plt import torch import torchvision.transforms as transforms from model import ResNet from PIL import Image if __name__ == '__main__': # Arguments parser = argparse.ArgumentParser(description='Training arguments') parser.add_a...
1,715
579
import unittest from lightcurator import lightcurve as lc class TestLightcuratorMethods(unittest.TestCase): def test_matchcat(self): cc = lc.matchcat(23) self.assertEqual(cc, 1) if __name__ == '__main__': unittest.main()
248
87
# -*- coding: utf-8 -*- """ # @Time : 24/10/18 2:40 PM # @Author : ZHIMIN HOU # @FileName: plot_result.py # @Software: PyCharm # @Github : https://github.com/hzm2016 """ import collections import matplotlib.pyplot as plt import numpy as np import pickle import copy as cp from baselines.deepq.assembly.src.value_f...
17,756
7,378
from repacolors import ColorScale from .colorbrewer import PALETTES as CBPALETTES PALETTES = { "ryb": ["#fe2713", "#fd5307", "#fb9900", "#fabc00", "#fefe34", "#d1e92c", "#66b032", "#0492ce", "#0347fe", "#3e01a4", "#8600af", "#a7194b"], "rybw3": ["#FE2712", "#FC600A", "#FB9902", "#FCCC1A", "#FEFE33", "#B2D732"...
895
416
# Copyright (c) 2019 Guilherme Borges <guilhermerosasborges@gmail.com> # See the COPYRIGHT file for more information import subprocess import time def ping(guest_ip): out = subprocess.run(['ping', '-c 1', guest_ip], capture_output=True) return out.returncode == 0 def nmap_ssh(guest_ip): out = subproces...
765
303
# -*- coding: utf-8 -*- ## Developed by Uriah Bojorquez from PyQt5.QtWidgets import QMainWindow, QApplication, QFileDialog, QMessageBox, QSizePolicy, QDialog from PyQt5.QtGui import QColor, QPalette from PyQt5 import QtCore from qt_iron_skillet_ui import Ui_Dialog as IRONSKILLET from qt_config_ui_panorama import Ui_Dia...
65,125
19,203
""" Tests find_lcs_optimized function """ import timeit import unittest from memory_profiler import memory_usage from lab_2.main import find_lcs_length_optimized, tokenize_big_file class FindLcsOptimizedTest(unittest.TestCase): """ Checks for find_lcs_optimized function """ def test_find_lcs_length_...
3,173
1,005
from flask import Flask, jsonify, render_template import requests app = Flask(__name__) @app.route('/') def intro(): url = "http://backend-service:6002/" response = requests.get(url) info = response.json()["info"] return render_template('index.html', data=info, title='Hello!') @app.route('/info') d...
754
265
import autokernel.kconfig import autokernel.config import autokernel.lkddb import autokernel.node_detector import autokernel.symbol_tracking from autokernel import __version__ from autokernel import log from autokernel import util from autokernel.symbol_tracking import set_value_detect_conflicts import argparse import...
56,257
16,943
from Enemy.bosses import * from Enemy.desert_enemies import * from Enemy.field_enemies import * from Enemy.graveyard_enemies import * from Enemy.magic_enemies import * from Enemy.moon_enemies import * from Enemy.winter_enemies import * from Enemy.fire_enemies import * from menu import VerticalMenu from Buildings.archer...
19,007
7,215
import json from urllib.parse import urljoin from django.conf import settings import requests def get_ticket_endpoint(): return urljoin(settings.ZENDESK_BASE_URL, '/api/v2/tickets.json') def zendesk_auth(): return ( '{username}/token'.format(username=settings.ZENDESK_API_USERNAME), settings...
1,177
378
# # THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS # FOR A PARTICULAR PURPOSE. THIS CODE AND INFORMATION ARE NOT SUPPORTED BY XEBIALABS. # import sys, string, time import c...
2,208
736
"""Initial Migration7 Revision ID: 5f810254fdd4 Revises: c0a6d11f2e37 Create Date: 2018-09-17 20:20:59.265902 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '5f810254fdd4' down_revision = 'c0a6d11f2e37' branch_labels = None depends_on = None def upgrade(): ...
1,238
481
from django.conf import settings from rest_framework.routers import DefaultRouter, SimpleRouter from message_service.mailing.api.views import ( ClientsViewSet, MailingViewSet, MessageViewSet, ) from message_service.users.api.views import UserViewSet if settings.DEBUG: router = DefaultRouter() else: ...
625
186
from fts.backends.base import InvalidFtsBackendError raise InvalidFtsBackendError("Xapian FTS backend not yet implemented")
126
38
import random secret_num = random.randrange(1, 11, 1) player_num = int(input("Guess a number from 1 to 10: ")) list_of_player_nums = [player_num] while player_num != secret_num: if player_num > secret_num: print("Too high!") elif player_num < secret_num: print("Too low!") pl...
525
208
#! /usr/bin/env python from math import factorial import numpy as np # test passed def generate_poly(max_exponent,max_diff,symbol): f=np.zeros((max_diff+1, max_exponent+1), dtype=float) for k in range(max_diff+1): for i in range(max_exponent+1): if (i - k) >= 0: f[k,i] = factorial(i)*symbol**(i-k)/facto...
363
170
# --- # jupyter: # jupytext: # formats: ipynb,py:light # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.11.0 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import torch def train...
3,389
1,063