text
string
size
int64
token_count
int64
"""Linguistic data for statistical pre-processing. Frequency statistics, as seen in data/, are provided by: a) Mark Mayzner, 1965: ------------------------------------------------------------------------------ METHODOLOGY: Starting at a random place in a given newspapers/magazines/book, record three- to seven-letter...
1,316
402
from keras import backend as K import numpy as np def Active_Contour_Loss(y_true, y_pred): """ lenth term """ x = y_pred[:,:,1:,:] - y_pred[:,:,:-1,:] # horizontal and vertical directions y = y_pred[:,:,:,1:] - y_pred[:,:,:,:-1] delta_x = x[:,:,1:,:-2]**2 delta_y = y[:,:,:-2,1:]**2 delta_u = K.abs(delta...
846
428
# -*- coding: utf-8 -*- # Imports import pandas as pd from .pd_utils import load_csv_or_excel from .pd_utils import load_experiment_results from .pd_utils import to_torch from .math_utils import standard # Objective function class class objective: """Objective funciton data container and operations. N...
7,584
1,960
import osmnx as ox import networkx as nx def gdf_to_nx(gdf_network): # generate graph from GeoDataFrame of LineStrings net = nx.Graph() net.graph['crs'] = gdf_network.crs fields = list(gdf_network.columns) for _, row in gdf_network.iterrows(): first = row.geometry.coords[0] last = ...
1,983
688
#!/usr/bin/env python3 from time import time def fib_sum(limit): prev2 = 1 prev1 = 2 fib_sum = 0 while prev2 < limit: # There is probably a more clever solution that skips the calculation # of every 1st and 3rd element. # For now, we will just cherry-pick the even values. ...
664
231
from tkinter import filedialog, ttk, messagebox from tkinter import * import traceback import requests import zipfile import json import os from source.Game import Game, RomAlreadyPatched, InvalidGamePath, InvalidFormat, in_thread, VERSION_FILE_URL from source.Option import Option from source.definition import get_ver...
15,221
4,430
import FWCore.ParameterSet.Config as cms def modify_hltL3TrajSeedOIHit(_hltL3TrajSeedOIHit): _iterativeTSG = _hltL3TrajSeedOIHit.TkSeedGenerator.iterativeTSG _iterativeTSG.ComponentName = cms.string('FastTSGFromPropagation') _iterativeTSG.HitProducer = cms.InputTag("fastMatchedTrackerRecHitCombinations") ...
1,236
505
import os, sys, re, transaction, base64, zlib from sqlalchemy import engine_from_config from pyramid.paster import ( get_appsettings, setup_logging, ) from .models import ( DBSession, CIA, Entry, User, Group, Base, ) from .security import hash_password def usage(argv): cmd = os....
1,612
570
from sklearn.ensemble import RandomForestClassifier import xgboost as xgb from sklearn.model_selection import cross_val_score from sklearn.pipeline import Pipeline import numpy as np # ============================================================= # Modeling tools for cross validation # Reference: https://github.com/fm...
3,297
898
# MIT License # # Copyright (c) 2020 Oli Wright <oli.wright.github@gmail.com> # # 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 # ...
4,089
1,318
#reads in the protocol requirements and stores the information in a class import yaml import logging logger = logging.getLogger(__name__) def loadYamlFile(filename): #open up the filename logger.debug("Opening file {}".format(filename)) try: fObject = open(filename, 'r') except Fi...
1,201
346
# # PySNMP MIB module CADANT-CMTS-NOTIFICATION-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CADANT-CMTS-NOTIFICATION-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:45:14 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python vers...
9,225
3,665
n1 = int(input('Digite o primeiro termo da PA: ')) n2 = int(input('Digite a razão da PA: ')) for c in range(1, 11): o = n1 + (c - 1)*n2 print(o, end=' - ') print('ACABOU')
179
81
import requests import sys import os import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) requests.adapters.DEFAULT_RETRIES = 10 def exploit_post_code(data, token): main_url = 'https://openapiv51.ketangpai.com/AttenceApi/checkin' headers = { "User-Agent": "Mozilla/5.0 (M...
1,729
711
import logging import io from asyncio import Queue from sse_starlette.sse import ( EventSourceResponse as _EventSourceResponse, AppStatus, ServerSentEvent, ) from .endec import Encode logger = logging.getLogger("app_server") class EventSourceResponse(_EventSourceResponse): """Override original `Event...
2,087
602
#! /usr/bin/env python3 """ Packet Commands """ COMMAND_CPU_WRITE = 1 COMMAND_CPU_READ = 2 COMMAND_DAQ_WRITE = 3 COMMAND_DAQ_READ = 4 """ RAM ADDRESSES """ RAM0_BASE_ADDRESS = 0x90000000 RAM1_BASE_ADDRESS = 0x90002000 RAM2_BASE_ADDRESS = 0x90004000 RAM3_BASE_ADDRESS = 0x90006000 """ GPIO """ GPIO_BASE_ADDRESS = 0x40...
2,088
1,267
from .figure import Figure from .subplot import Subplot from .subplot_time import SubplotTime from .csv_reader import CsvReader, matchCsv from .excel_reader import ExcelReader from .get_path import getFileList, PathList from .save_plot import actionSavePNG
257
73
import os def get_file_list(root, key=None): files = os.listdir(root) if key is not None: files.sort(key=key) return files def get_config_file(name): return os.path.join(os.path.dirname(__file__), ".." , "resource", name)
249
91
# Generated by Django 2.2.6 on 2019-10-22 08:11 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='motifs', fields=[ ('id', models.BigAutoFiel...
648
189
def conv(user): import requests import json import xmltodict url = 'https://api.github.com/users/' + user s = requests.get(url) # Converter json para dict x = {} x['wg'] = json.loads(s.text) y = xmltodict.unparse(x, pretty=True) return y
280
100
from .app import create_app # APP = create_app() # python commands: # in app dir #FLASKAPP=twitoff flask run # in root dir # FLASK_APP=twitoff flask shell ''' Notes for setup: in root, FLASK_APP=twitoff flask shell import create_app init create_app() import DB DB.create_all() creates tables ''' ''' Other commands...
404
156
# Copyright 2015 TellApart, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
1,945
574
import numpy as np import pandas as pd from rail.creation.engines import Engine from typing import Callable class Creator: """Object that supplies mock data for redshift estimation experiments. The mock data is drawn from a probability distribution defined by the generator, with an optional degrader appl...
4,394
1,150
#!/usr/bin/python3 # Perform the unit tests on SV import subprocess import os import pathlib import traceback import pipetestutils def main(): r1 = -1 try: pathlib.Path("build/reports").mkdir(parents=True, exist_ok=True) os.chdir("src/test") except Exception as e: print("Problem ch...
834
275
from . import base from . import mixins from datetime import date class TransformedRecord( mixins.GenericCompensationMixin, mixins.GenericDepartmentMixin, mixins.GenericIdentifierMixin, mixins.GenericJobTitleMixin, mixins.GenericPersonMixin, mixins.MembershipMixin, mixins.OrganizationM...
2,439
813
from django.db.models import Count, Sum from django.http import HttpResponseRedirect from django.shortcuts import render, get_object_or_404 # Create your views here. from django.views import generic from accountingsubject.forms import AccountingSubjectForm from accountingsubject.models import AccountingSubject from c...
2,912
842
class AttributedDict(dict): def __dir__(self): directory = dir(super()) directory.extend([str(key.replace(" ", "_")) for key in self]) return directory def __getattr__(self, attr): _dir_dict = dict() [_dir_dict.update({key.replace(" ", "_"): key}) for key in self] ...
762
223
def duree(debut, fin): d = debut[0] * 60 + debut[1] f = fin[0] * 60 + fin[1] e = f - d h = e // 60 m = e - h * 60 if h < 0: h = 24 - abs(h) return (h, m) print(duree ((14, 39), (18, 45))) print(duree ((6, 0), (5, 15)))
258
146
""" General Utilities file. """ import sys import os ############################ NON-TF UTILS ########################## from skimage.util import img_as_float import numpy as np import cv2 import pickle from PIL import Image from io import BytesIO import math import tqdm import scipy import json import matplo...
31,392
12,965
import queue import multiprocessing import itertools import sys __all__ = ["QConnect", "CConnect"] pulse_length_default = 10 * 10 ** -12 # 10 ps photon pulse length signal_speed = 2.998 * 10 ** 5 #speed of light in km/s fiber_length_default = 0.0 class QConnect: def __init__(self, *args, transit_devices=[]): ...
8,389
2,328
import typing as T from pqcli.mechanic import Player, StatType from pqcli.ui.curses.widgets import Focusable from .progress_bar_window import DataTableProgressBarWindow class CharacterSheetWindow(Focusable, DataTableProgressBarWindow): def __init__( self, player: Player, parent: T.Any, h: int, w: int, y...
2,035
643
import yaml import pathlib import json import math class Planet(object): def __init__(self, config): self.GMS = 0 # mass self.M = 0. self.name = "unknown" # period self.T = 1. # eccentricity self.e = 0. # semi major axis self.a = 1. ...
1,668
568
import unittest from tests.unit.test_account import TestAccount from tests.unit.test_application import TestApplication from tests.unit.test_usages import TestUsages from tests.unit.test_conferences import TestConferences from tests.unit.test_mms_messages import TestMmsMessages from tests.unit.test_sms_messages import ...
2,479
760
def _get_square(list): l1 = [x*x for x in range(0, len(list), 2) if x % 3 != 0] return l1 print(_get_square([1, 2, 3, 4, 5])) def get_square(list): l1 = [x*x for x in list if x % 3 != 0 and x % 2 == 0] return l1 print(get_square([1, 2, 3, 4, 5]))
262
137
import json def main(file_path, out_len): with open(file_path, 'r') as f: data = json.loads(f.read()) print(len(data['data'])) data['data'] = data['data'][:out_len] with open(file_path, 'w') as f: print(len(data['data'])) json.dump(data, f) if __name__ == "__main__": ...
391
156
"""Provides ability to run jobs locally or on HPC.""" from collections import OrderedDict import datetime import fileinput import importlib import logging import os import shutil import jade from jade.common import ( CONFIG_FILE, JOBS_OUTPUT_DIR, OUTPUT_DIR, RESULTS_FILE, HPC_CONFIG_FILE, ) from j...
15,289
4,332
import os import pytest from starkware.starknet.compiler.compile import ( compile_starknet_files) from starkware.starknet.testing.starknet import Starknet from starkware.starknet.testing.contract import StarknetContract # The path to the contract source code. CONTRACT_FILE = os.path.join( os.path.dirname(__fi...
1,364
458
__version__ = '0.1.12' from ._useragent import UserAgentMiddleware from ._markdown import MarkdownPipeline from ._cookies import FirefoxCookiesMiddleware from ._mongodb import MongoDBPipeline from ._redis import RedisDupeFilter
230
72
# Copyright Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompan...
1,930
640
import torch.optim from numpy import ndarray def get_optim(optim, params, init_lr, steps=1, wd=0, gamma=1, momentum=0.9, max_epochs=120): if optim == 'sgd': optimizer = torch.optim.SGD( params, lr=init_lr, momentum=momentum, weight_decay=wd) elif optim == 'sgd_nomem': ...
1,146
395
from celery import Celery, Task from microengine_utils import errors from microengine_utils.datadog import configure_metrics from microengine_utils.constants import SCAN_FAIL, SCAN_SUCCESS, SCAN_TIME, SCAN_VERDICT from microengineclamav.models import Bounty, ScanResult, Verdict, Assertion, Phase from microengineclamav...
1,941
620
import datetime import os, sys, six, base64, copy from jinja2 import Environment, FileSystemLoader, Template from google.auth.transport import requests from google.cloud import datastore from google.cloud import storage from google.cloud import bigquery import google.oauth2.id_token from flask import Flask, render_t...
18,835
5,835
NotaParcial1 = int(input("Nota primer Parcial: ")) NotaParcial2 = int(input("Nota segundo Parcial: ")) NotaTaller = int(input("Nota del Taller: ")) NotaProyecto = int(input("Nota del Proyecto: ")) Parcial1 = NotaParcial1*(25/100) Parcial2 = NotaParcial2*(25/100) Taller = NotaTaller*(20/100) Proyecto = NotaPr...
982
426
#!/usr/bin/env python3 """ This script checksums, signs, and compresses malvarma-<version>.img, and creates malvarma-<version>.tar.bz2. The author's GPG signature is hardcoded below. """ import os import shutil import sys import subprocess if __name__ == "__main__": if len(sys.argv) == 1: print("Usage: ...
1,395
500
import os import time from signal import signal, SIGINT from TauLidarCommon.frame import FrameType from TauLidarCamera.camera import Camera outputDir = './samples' runLoop = True def setup(): camera = None ports = Camera.scan() ## Scan for available Tau Camera devices if len(ports)...
1,955
611
import sys from collections import deque def bfs(x): q = deque([x]) dist = [0] * (N + 1) check = [False] * (N + 1) cnt = -1 check[x] = True while q: size = len(q) cnt += 1 for _ in range(size): x = q.popleft() for y in a[x]: if dist...
1,038
373
import json from twisted.logger import Logger from twisted.internet.defer import inlineCallbacks from autobahn.twisted.wamp import ApplicationSession from autobahn.twisted.wamp import ApplicationRunner from bokeh.client import push_session from bokeh.plotting import figure, curdoc from bokeh.models.widgets import Pan...
5,235
1,877
from pathlib import Path import sys from unittest.mock import patch from nornir import InitNornir import nornsible from nornsible import InitNornsible, nornsible_delegate, nornsible_task NORNSIBLE_DIR = nornsible.__file__ TEST_DIR = f"{Path(NORNSIBLE_DIR).parents[1]}/tests/" @nornsible_task def custom_task_exampl...
5,875
1,780
## Web File def insertWeb(filetype, json, cursor, conn, uid): if (filetype == 'web'): web_page_node(json,uid,cursor,conn) # [pages] / [pageNode] web_entry_node(json, uid, cursor, conn) # [pages] / [entriesNode] def web_entry_response(json_entries_node, uid, cursor, conn, parentid): tblName = 'lab_web_entries...
8,338
3,430
# Lint as: python3 # Copyright 2018 The TensorFlow Authors. 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 ...
21,541
8,511
def ddm(T, x0, xinfty, lam, sig): t = np.arange(0, T, 1.) x = np.zeros_like(t) x[0] = x0 for k in range(len(t)-1): x[k+1] = xinfty + lam * (x[k] - xinfty) + sig * np.random.standard_normal(size=1) return t, x # computes equilibrium variance of ddm # returns variance def ddm_eq_var(T, x0, ...
1,148
461
__version__ = '0.0.11b' from .base import * from .context import * from .task import * from .env import * from .parse import *
129
47
from tkinter import * from tkinter.font import BOLD from algoritmos.vrc import * from algoritmos.noise_1_bits import * ###################################################################################################### # Pagina 1 def tab1(root, common_img, bits_normales, bits_desglosados): pagina1 = Toplevel(...
2,829
1,120
from unittest.mock import patch import numpy as np from auxein.population.dna_builders import UniformRandomDnaBuilder, NormalRandomDnaBuilder def test_uniform_random_dna_builder_instantiation(): builder = UniformRandomDnaBuilder(interval=(-5, 0)) assert builder.get_distribution() == 'uniform' assert len(...
889
318
# Written by Yunfei LIU # Sep 23, 2020 # Please obey the license GPLv3 # This allows to input four integers with space between them number1,number2,number3,number4 = map(int,input().split()) # Add them up sum = number1 + number2 + number3 + number4 # Get the unit digit result = sum%10 # Output the result print(result...
322
111
#!/usr/bin/env python # https://en.wikipedia.org/wiki/Champernowne_constant # sequences below are related to these constants # counts how many numbers between two 10**n and 10**(n-1) def A0(n): return (10**n - 10**(n-1))*n # http://oeis.org/A033714 # This sequence also gives the total count of digits of n below 10^...
445
203
from model import * from config import * from utils import * if __name__ == "__main__": ''' GPU(s) ''' gpus = tf.config.experimental.list_physical_devices('GPU') GPU_N = 3 if gpus: try: tf.config.experimental.set_visible_devices(gpus[GPU_N:], 'GPU') logical_gpus = tf.config.experimental.list_logical_devi...
5,393
2,382
# https://leetcode.com/problems/reverse-integer/ # Runtime: 32 ms, faster than 96.20% of Python3 online submissions for Reverse Integer. # Runtime: 36 ms, faster than 84.28% of Python3 online submissions for Reverse Integer. # Runtime: 44 ms, faster than 22.92% of Python3 online submissions for Reverse Integer. class ...
1,862
635
""" A hodge-podge of convenience functions for luci """
57
20
testcases = int(input()) for _ in range(testcases): main_details = list(map(int, input().split())) coin_details = list(map(lambda x: int(x)%main_details[-1], input().split())) print(sum(coin_details)%main_details[-1])
235
85
########################################################################## # If not stated otherwise in this file or this component's Licenses.txt # file the following copyright and licenses apply: # # Copyright 2021 RDK Management # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use th...
16,347
4,675
import geopandas as gp import pytest from shapely.geometry import Polygon import maup CRS = "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs" @pytest.fixture def crs(): return CRS @pytest.fixture def four_square_grid(): """ b d a c """ a = Polygon([(0, 0), (0, 1), (1, 1), (1, 0)]) b = ...
2,409
1,147
""" Plot results of benchmark. Need to run benchmark.py first to generate the file benchmark_results.json. """ import json from collections import defaultdict import matplotlib.pyplot as plt def groupby(values, keyfunc): """Group values by key returned by keyfunc.""" groups = defaultdict(list) for value ...
1,389
418
from edgesets import UEdge, DEdge def test_repr(): e1 = DEdge(7, 8) text = repr(e1) assert text == "DEdge(7, 8, weight=1)" e2 = eval(text) assert type(e1) == type(e1) assert e1 == e2 def test_if_directions_are_differents_with_same_nodes(): d1 = DEdge(10, 15) d2 = DEdge(15...
872
383
import argparse from pathlib import Path import numpy as np import scipy import keras from keras.models import load_model from moviepy.editor import VideoFileClip, concatenate_videoclips from tqdm import tqdm def main(): # yapf: disable parser = argparse.ArgumentParser(description='Video Highlight') pa...
1,889
709
from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.utils import timezone from django.db.models import Count, Q from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.contrib.auth import login, authenticate, log...
4,389
1,409
# coding=utf-8 import tensorflow as tf class DataSetLoader(object): def __init__(self, config, generators, default_set_name='train'): self.config = config self.generators = generators self.data_sets = dict() self.data_set_init_ops = dict() with tf.variable_scope("data"): ...
1,408
415
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # imports. from ssht00ls.classes.config import * from ssht00ls.classes import utils # the ssh connections object class. class Connections(Traceback): def __init__(self): # docs. DOCS = { "module":"ssht00ls.connections", "initialized":True, "description"...
1,323
549
data = np.arange(0, 20, 2) result = pd.Series(data) # Alternative Solution # s = pd.Series(range(0, 20, 2)) # Alternative Solution # s = pd.Series([x for x in range(0, 20) if x % 2 == 0])
193
91
#!/usr/bin/env python # encoding: utf-8 from contextlib import contextmanager import mock __author__ = 'Liu Yicong' __email__ = 'imyikong@gmail.com' @contextmanager def mock_patches(*patches, **named_patches): """ A context manager to help create mock patches. >>> with mock_patches("package.module.cls"...
907
315
# -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-03-11 12:37 from __future__ import absolute_import from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('data_interfaces', '0015_automaticupdaterule_locked_f...
558
185
# -*- coding:utf-8 -*- """ console.py ~~~~~~~~ 数据发布插件 - 输出到控制台 :author: Fufu, 2021/6/7 """ from . import OutputPlugin from ..libs.metric import Metric class Console(OutputPlugin): """数据发布 - 输出到控制台""" name = 'console' async def write(self, metric: Metric) -> None: """写入数据""" ...
353
156
import json import unittest from slack_sdk.web import WebClient from tests.slack_sdk.web.mock_web_api_server import ( setup_mock_web_api_server, cleanup_mock_web_api_server, ) class TestWebClient_Issue_1049(unittest.TestCase): def setUp(self): setup_mock_web_api_server(self) def tearDown(sel...
699
239
from netforce.model import Model, fields, get_model, clear_cache from netforce.database import get_connection from datetime import * import time from netforce import access class TaskList(Model): _name = "task.list" _string = "Task List" _fields = { "name": fields.Char("Name",required=True), ...
734
228
#!/usr/bin/python3 import paramiko,time #using as ssh client client=paramiko.SSHClient() #auto adjut host kue verification with yes or no client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #time to connect to remote Cisco IOS addr=input("Enter your Router IP :") u='root' p='cisco' #connected with SSh sessio...
696
232
#!/usr/bin/env python3 import sys, os import arsdkparser #=============================================================================== class Writer(object): def __init__(self, fileobj): self.fileobj = fileobj def write(self, fmt, *args): if args: self.fileobj.write(fmt % (args)...
16,830
5,598
import numpy import pygame import random from pygame import gfxdraw pygame.init() config_instance = open('settings.txt', 'r', encoding = 'utf-8') class Settings: def __init__(self, settings: dict): def str_to_rgb(sequence): r, g, b = sequence.split(' ') r, g, b = int(r), int(g), int(b) if (any([r not in r...
4,998
2,133
import time import random def parse(input): tokens = input.split(" ") parsedTokens = [] time.sleep(5) for i in range(200000): test = random.randint(1, 8) + random.randint(-4, 90) for token in tokens: if token == "": continue parsedTokens.append({ "text": token, "lemma": token, ...
484
168
# -*- coding: utf-8 -*- """ Created on Mon Jan 6 10:07:13 2020 @author: sjliu.me@gmail.com """ import torch import torch.nn as nn import torch.nn.functional as F class wcrn(nn.Module): def __init__(self, num_classes=9): super(wcrn, self).__init__() self.conv1a = nn.Conv2d(103,64,...
2,961
1,380
__all__ = ['templatetags']
27
13
# Copyright 2020 DeepMind Technologies Limited. # # 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 ag...
12,491
4,755
import hawkey import logging from rpmreq import graph from rpmreq import query log = logging.getLogger(__name__) def build_requires(specs, repos, base_repos=None, out_data=None, out_image=None, cache_ttl=3600): dep_graph = graph.build_requires_graph( specs=specs, r...
1,012
336
from mlflow.tracking import MlflowClient from urllib.parse import urlparse def get_prod_path_mlflow_model_mlflow_query(model_name, version, new_bucket, new_path): client = MlflowClient() artifact_path_original = None for mv in client.search_model_versions(f"name='{model_name}'"): if mv.version == ...
1,033
355
#!/usr/bin/python # -*- coding: utf-8 -*- from datetime import datetime, timedelta from iso8601 import parse_date from pytz import timezone import urllib import json import os def convert_time(date): date = datetime.strptime(date, "%d/%m/%Y %H:%M:%S") return timezone('Europe/Kiev').localize(date).strftime('%...
5,350
1,981
EMAIL_ADDRESS = 'domfigarobarbearia@gmail.com' EMAIL_PASSWORD = 'barbeariadomfigaro' HEROKU_PASSWORD = "Barbeariadomfigaro!"
125
57
''' Created on 15/03/2018 @author: pelejaf '''
47
27
# coding: utf-8 from config.base import * DEBUG = False SERVER_PORT = 8899
76
30
from __future__ import print_function NUM_ROWS = 7 NUM_COLS = 7 DIRECTIONS = ('E', 'W', 'N', 'S') MOVEMENT_DIFFS = { 'N': (0, -1), 'S': (0, 1), 'E': (1, 0), 'W': (-1, 0) } X_MOVEMENT_DIFFS = { 'N': 0, 'S': 0, 'E': 1, 'W': -1 } Y_MOVEMENT_DIFFS = { 'N': -1, 'S': 1, 'E': 0, ...
6,574
2,134
from dataclasses import dataclass from typing import Dict from dataclasses_jsonschema import JsonSchemaMixin @dataclass class DatabaseStatsBreakdown(JsonSchemaMixin): """Database stats broken down by tier""" breakdown: Dict[str, int] total: int @dataclass class DatabaseStatsSchema(JsonSchemaMixin): ...
419
124
import numpy as np import pandas as pd import unittest from pyampute.ampute import MultivariateAmputation from pyampute.exploration.md_patterns import mdPatterns class TestMapping(unittest.TestCase): ''' This class tests the example code in the blogpost "A mapping from R-function ampute to pyampute" ''' ...
3,781
1,389
from __future__ import absolute_import from __future__ import print_function import numpy as np import random import cv2 from keras.utils import to_categorical from keras.models import Model from keras.layers import Dropout, Lambda, Dense, Conv2D, Flatten, Input, MaxPooling2D from keras.optimizers import RMSprop from ...
1,560
551
import sys if sys.version_info < (3, 5): print("Python 3.5 is required for this package") sys.exit(1) from setuptools import setup setup(name = "simplesvnbrowser", version = "0.0.1", description = "A simple subversion repository browser application", url = "https://github.com/holtrop/simple-...
596
195
# -*- coding: utf-8 -*- """ Created on Wed Oct 30 10:02:36 2019 @author: abibeka Purpose: Batch update synchro volumes """ # 0.0 Housekeeping. Clear variable space #****************************************************************************************** from IPython import get_ipython #run magic commands ipython =...
2,092
822
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Creates the multiline text charts Given the unique nature of multiline text charts, we use a separate method to construct them. ----- """ # Built-in Modules import pickle import sys import textwrap import traceback # Third-party Modules # Note the order and structu...
5,695
1,708
# -*- coding: utf-8 -*- """ * TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-蓝鲸 PaaS 平台(BlueKing-PaaS) available. * Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except in co...
1,814
548
from pylie.common import * from pylie import SO3 def test_to_rotation_matrix_results_in_valid_rotation(): # Test 2x2 matrix. A = np.random.rand(2, 2) R = to_rotation_matrix(A) np.testing.assert_almost_equal(R @ R.T, np.identity(2), 14) np.testing.assert_almost_equal(np.linalg.det(R), 1, 14) #...
1,342
552
import pytz from datetime import timedelta from dateutil import parser from django.utils.text import Truncator from django.db import IntegrityError from core.models import Data class HoursDataSource(object): def __init__(self, start_date, end_date): self.entries = [] self.start_date = start_date ...
1,409
427
from django.db.models.signals import post_save from django.dispatch import receiver from roadmaps.models import RoadmapNode from roadmaps.services.progress import ProgressPropagator @receiver(post_save, sender=RoadmapNode) def propagate_completion_to_descendant_nodes(sender, **kwargs): roadmap: RoadmapNode = kwa...
398
119
import numpy as np import pytest from numpy.testing import assert_array_equal from ReconstructOrder.datastructures.intensity_data import IntensityData # ==== test basic construction ===== def test_basic_constructor_nparray(): """ test assignment using numpy arrays """ int_data = IntensityData() ...
7,725
3,072
import torch class MarioConfig: def __init__(self): # hyper config self.max_num_gpus = 1 self.num_workers = 32 self.discount = 0.999 self.observation_space = (84, 84, 3) self.action_space = 256 + 20 + 8 import os import datetime self.results...
1,722
564