text
string
size
int64
token_count
int64
"""All Modules""" from .nft import NftModule as NftModuleV2 from .nft_v1 import * from .nft_types import * from .currency import * from .market import * from .pack import * from .collection import CollectionModule from .bundle import *
236
73
"""Tests of parsing GLNs.""" import pytest from biip import ParseError from biip.gln import Gln from biip.gs1 import GS1Prefix def test_parse() -> None: gln = Gln.parse("1234567890128") assert gln == Gln( value="1234567890128", prefix=GS1Prefix(value="123", usage="GS1 US"), payload=...
1,394
616
from django.shortcuts import render from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.views.decorators.csrf import csrf_exempt import json from django.core import serializers # Create your views here. from django.http import HttpResponse from django.http.response import JsonResponse ...
3,523
1,259
import torch from torch.utils.data import Dataset class PCAMDataset(Dataset): def __init__(self, root, phase, voxel_size, num_points): super(PCAMDataset, self).__init__() self.root = root self.phase = phase self.voxel_size = voxel_size self.num_points = num_points def __le...
362
124
from selenipupser import element query = element('[name=q]')
62
22
"""! @brief Integration-test runner for tests of oscillatory and neural networks. @authors Andrei Novikov (pyclustering@yandex.ru) @date 2014-2020 @copyright BSD-3-Clause """ import unittest from pyclustering.tests.suite_holder import suite_holder # Generate images without having a window appear. i...
2,017
649
from records_mover.utils import beta, BetaWarning import unittest from unittest.mock import patch @patch('records_mover.utils.warnings') class TestBeta(unittest.TestCase): def test_beta(self, mock_warnings): @beta def my_crazy_function(): return 123 out = my_crazy_function() ...
658
176
import graphene from graphql import GraphQLError from graphql_relay import from_global_id from django.contrib.auth import get_user_model from creator.organizations.models import Organization from creator.organizations.queries import OrganizationNode from creator.events.models import Event User = get_user_model() c...
8,444
2,155
""" Mag Square #always do Detective work nm what UNDERSTAND -nxn matrix of distinctive pos INT from 1 to n^2 -Sum of any row, column, or diagonal of length n is always equal to the same number: "Mag" constant -Given: 3x3 matrix s of integers in the inclusive range [1,9] we can convert any digit a to any othe...
4,835
2,417
import re def parse_genome_id(genome): genome_id = re.search("GCA_[0-9]*.[0-9]", genome).group() return genome_id def rm_duplicates(seq): """Remove duplicate strings during renaming """ seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))] def clean...
1,371
507
"""Sample Fetch script from DuneAnalytics""" from __future__ import annotations from dataclasses import dataclass from datetime import datetime from src.duneapi.api import DuneAPI from src.duneapi.types import Network, QueryParameter, DuneQuery from src.duneapi.util import open_query @dataclass class Record: ""...
1,598
498
from typing import Optional from bottle import request, route, run import uvicorn from arnold import config from arnold.output.speaker import Speaker API_CONFIG = config.API # Module class instances, rather than init everytime speaker = Speaker() # TODO (qoda): Make this super generic @route('/health') def hea...
696
220
#!/usr/bin/env python """ Process a sample tweet fetched using streaming API. Usage: $ ipython -i FILENAME >>> data = main() >>> data.keys() # Then explore the `data` object in ipython. ['contributors', 'truncated', 'text', 'is_quote_status', 'in_reply_to_status_id', 'id', 'favorite_count', 'source...
27,430
11,751
i = 0 vsota = 0 while i < 1000: if i % 3 == 0: vsota += i elif i % 5 == 0: vsota += i i += 1 print(vsota)
144
78
"""Regex pattern constants""" import re URL_PATTERN = re.compile(r'(http[s]?://(?:[a-zA-Z]|[0-9]|[$-;?-_=@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)') NUMBER_PATTERN = re.compile(r'(\.\d+|\d[,\d]*(?:\.\d+)?)') UNIT_PATTERN_TUPLE = [ # [length] ('inch', re.compile(r' *("|inch|inches|ins?)(?!\w)')), ('f...
1,886
1,024
from apis.resources.users import user
38
11
import os import textwrap from pprint import pprint #import cloudmesh.pi.cluster from cloudmesh.pi.cluster.Installer import Installer from cloudmesh.pi.cluster.Installer import Script from cloudmesh.common.Host import Host from cloudmesh.common.Printer import Printer from cloudmesh.common.console import Console from c...
11,873
3,399
#!/usr/bin/py # -*- coding: utf-8 -*- """ @author: Cem Rıfkı Aydın Constant parameters to be leveraged across the program. """ import os COMMAND = "cross_validate" # Dimension size of embeddings EMBEDDING_SIZE = 100 #Language can be either "turkish" or "english" LANG = "turkish" DATASET_PATH = os.path.join("inpu...
1,321
467
from mathy_core import ExpressionParser expression = ExpressionParser().parse("4 + 2") assert expression.evaluate() == 6
122
34
# Setup file for package overlapping_namespace from setuptools import setup setup(name="overlapping_namespace", version="0.1.0", install_requires=["wheel", "quark==0.0.1", "org_example_foo==0.1.0"], setup_requires=["wheel"], py_modules=[], packages=['org', 'org.example', 'org.example.bar...
352
125
""" This file contains function to separate out video and audio using ffmpeg. It consists of two functions to split and merge video and audio using ffmpeg. """ import os from torpido.config.constants import (CACHE_DIR, CACHE_NAME, IN_AUDIO_FILE, OUT_AUDIO_FILE, ...
9,285
2,494
# Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.plugins.callback import CallbackBase from ansible.utils.color import stringc class CallbackModule(CallbackBase): CALLBACK_VERSION = 2.0 CALLBACK_TYPE = 'stdout' CALLBACK_NAM...
2,108
634
import planetClass def createSomePlanets(): aPlanet=planetClass.Planet("Zorks",2000,30000,100000,5) bPlanet=planetClass.Planet("Zapps",1000,20000,200000,17) print(aPlanet.getName() + " has a radius of " + str(aPlanet.getRadius())) planetList=[aPlanet,bPlanet] for planet in planetList: print...
605
234
import json f = open('Thesis_v3/scripts/fastapi/web/static/data/escuelas.json') data = json.load(f)
101
42
import numpy as np from systemrl.agents.q_learning import QLearning import matplotlib.pyplot as plt from helper import decaying_epsilon, evaluate_interventions from tqdm import tqdm #This is not converging def mincost(env, human_policy, min_performance, agent, num_episodes=1000, max_steps=1000): print("mincost") ...
1,410
406
"""All algorithms used by geoio-server""" import math import functools import geojson def angle(point_1, point_2): """calculates the angle between two points in radians""" return math.atan2(point_2[1] - point_1[1], point_2[0] - point_1[0]) def convex_hull(collection): """Calculates the convex hull of an ...
2,076
708
import numpy as np def modified_bisection(f, a, b, eps=5e-6): """ Function that finds a root using modified Bisection method for a given function f(x). On each iteration instead of the middle of the interval, a random number is chosen as the next guess for the root. The function fi...
2,495
667
# -*- coding: utf-8 -*- from __future__ import unicode_literals import json from collections import OrderedDict from django.core.urlresolvers import reverse from django.db import models from django.db.transaction import atomic from django.template.defaultfilters import slugify from django.utils.crypto import get_rand...
8,454
2,458
#!/usr/bin/python import sys import os import string #print sys.argv frontend = "../cparser/parser.exe" flags = "-fprint-results" pta_cmd = "%s %s" % (frontend, flags) prefix = "" prefix_size = int(sys.argv[1]) for x in sys.argv[2:(2+prefix_size)]: prefix = " %s %s" % (prefix, x) filelist = "" for x in sys.ar...
1,215
442
"""Create views using Pumpwood pattern.""" import os import pandas as pd import simplejson as json from io import BytesIO from django.conf import settings from django.http import HttpResponse from rest_framework.parsers import JSONParser from rest_framework import viewsets, status from rest_framework.response import Re...
29,178
7,709
from .base import Base class Heavy(Base): def complete_init(self): super().complete_init() self.force_regroup = True if self.unit.use_ammo: self.smart_range_retarget = True def process(self, dt): super().process(dt)
273
88
import shutil import unittest import tempfile import pandas as pd from kgtk.cli_entry import cli_entry from kgtk.exceptions import KGTKException class TestKGTKImportConceptNet(unittest.TestCase): def setUp(self) -> None: self.temp_dir=tempfile.mkdtemp() def tearDown(self) -> None: shutil.rmtre...
899
321
from .scrape import Scrape from .helper import Helper
53
17
# Written by Will Cromar # Python 3.6 from collections import deque # DX/DY array. In order of precedence, we'll move # left, right, up, and down DX = [-1, 1, 0, 0] DY = [0, 0, -1, 1] # Constants for types of spaces EMPTY = '.' LADDER = '#' CHUTE = '*' START = 'S' EXIT = 'E' # Primary business fu...
4,030
1,396
import fitsio import fsfits from argparse import ArgumentParser import json import numpy ap = ArgumentParser() ap.add_argument('--check', action='store_true', default=False, help="Test if output contains identical information to input") ap.add_argument('input') ap.add_argument('output') ns = ap.parse_args(...
1,789
506
from tkinter import Entry, Listbox, StringVar import sys, tkinter, subprocess from window_switcher.aux import get_windows class Window: FONT = ('Monospace', 11) ITEM_HEIGHT = 22 MAX_FOUND = 10 BG_COLOR = '#202b3a' FG_COLOR = '#ced0db' def resize(self, items): if self.resized: ...
4,086
1,350
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: imu_samples.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _r...
5,292
2,165
"""This module contains the general information for BiosVfSgxLePubKeyHash ManagedObject.""" from ...imcmo import ManagedObject from ...imccoremeta import MoPropertyMeta, MoMeta from ...imcmeta import VersionMeta class BiosVfSgxLePubKeyHashConsts: VP_SGX_LE_PUB_KEY_HASH0_PLATFORM_DEFAULT = "platform-default" ...
3,394
1,377
from configparser import ConfigParser import boto3 class S3Client: @staticmethod def get_client(config: ConfigParser): return boto3.Session( profile_name=config.get('S3', 'profile', fallback='default') ).client('s3')
256
77
import os import sys from setuptools import find_packages, setup from setuptools.command.test import test as TestCommand class PyTest(TestCommand): user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")] def initialize_options(self): TestCommand.initialize_options(self) ...
1,791
568
# -*- coding: utf-8 -*- from PyQt5 import QtCore, QtGui, QtWidgets class Ui_DockWidgetPluginBase(object): def setupUi(self, DockWidgetPluginBase): DockWidgetPluginBase.setObjectName("DockWidgetPluginBase") DockWidgetPluginBase.resize(232, 141) self.dockWidgetContents = QtWidgets.QWidget() ...
1,194
375
# -*- coding: utf-8 -*- from setuptools import setup, find_packages with open('README.md') as f: readme = f.read() with open('LICENSE') as f: license = f.read() setup( name='attention-memory-task', version='0.1.0', description='Attention and Memory Experiment', long_description='This reposi...
684
207
from numpy import * import matplotlib.pyplot as plt import time from LogReg import trainLogRegres, showLogRegres, predicTestData # from sklearn.datasets import make_circles # from sklearn.model_selection import train_test_split # from sklearn.metrics import accuracy_score import csv def loadTrainData(): train_x =...
3,659
1,317
import pyautogui as pg # 间隔2秒钟将鼠标移动到坐标为100,100的位置 pg.FAILSAFE = False #关掉保护措施,不设置会报下面附录的错误 pg.moveTo(x=100, y=100, duration=2) pg.click() #鼠标左键点击一次, 这个函数有很多参数,参见以下,可以玩看看 #pg.click(x=None, y=None, clicks=1, interval=0.0, button='left', duration=0.0, tween=pg.linear) ''' 第一次执行的时候报了这个错误,搜了一下貌似要关掉 Excepti...
1,303
827
import os import naming as n reload(n) import maya.cmds as mc import System.utils as utils reload(utils) CLASS_NAME = 'ModuleA' TITLE = 'Module A' DESCRIPTION = 'Test desc for module A' ICON = os.environ['RIGGING_TOOL_ROOT'] + '/Icons/_hand.xpm' #cNamer = n.Name(type='blueprint', mod=CLASS_NAME) clas...
9,683
3,594
from unittest import TestCase from mock import Mock from ingest.exporter.metadata import MetadataResource, MetadataService, MetadataParseException, MetadataProvenance class MetadataResourceTest(TestCase): def test_provenance_from_dict(self): # given: uuid_value = '3f3212da-d5d0-4e55-b31d-83243f...
7,652
2,483
import torch as th import torch.nn as nn import torch.nn.functional as F import torchvision as tv import matplotlib.pyplot as plt import cv2 from torch.utils.tensorboard import SummaryWriter import time from collections import deque import random import copy from utils import xsobel, ysobel class Cell(nn.Module): ...
919
327
""" Prototype Delivery Workflow. """ import os import sys import glob import logging import ska_sdp_config import dask import distributed from google.oauth2 import service_account from google.cloud import storage # Initialise logging logging.basicConfig() LOG = logging.getLogger("delivery") LOG.setLevel(logging.INF...
5,708
1,843
from RLUtilities.LinearAlgebra import vec3 from RLUtilities.Maneuvers import Drive class UtilitySystem: def __init__(self, choices, prev_bias=0.15): self.choices = choices self.current_best_index = -1 self.prev_bias = prev_bias def evaluate(self, bot): best_index = -1 ...
1,527
488
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ # Meta-info Author: Nelson Brochado Created: 01/07/2015 Updated: 06/04/2018 # Description Contains the abstract class BinaryHeap. # References - Slides by prof. A. Carzaniga - Chapter 13 of Introduction to Algorithms (3rd ed.) - http://www.math.clemson.edu/~war...
7,516
2,433
from .views import API from django.urls import path urlpatterns = [ path('', API.as_view()), ]
106
37
# -*- coding: utf-8 -*- from trytond.pool import PoolMeta from trytond.model import fields from trytond.pyson import Eval, Bool, Not __all__ = ['Product'] __metaclass__ = PoolMeta class Product: "Product" __name__ = 'product.product' country_of_origin = fields.Many2One( 'country.country', 'Cou...
2,190
664
from ParadoxTrading.Chart import Wizard from ParadoxTrading.Fetch.ChineseFutures import FetchDominantIndex from ParadoxTrading.Indicator import RSI fetcher = FetchDominantIndex() market = fetcher.fetchDayData('20100701', '20170101', 'rb') rsi = RSI(14).addMany(market).getAllData() wizard = Wizard() price_view = wiz...
523
203
import fractions from pprint import pprint lcm_limit = 32 octave_limit = 4 candidates = [(x, y) for x in range(1, lcm_limit + 1) for y in range(1, lcm_limit + 1)] candidates = [c for c in candidates if fractions.gcd(c[0], c[1]) == 1 and c[0] * c[1] <= lcm_limit and 1 / octave_limit <= c[0] / c[1] <= octave_limit] ...
406
185
# # @lc app=leetcode id=24 lang=python3 # # [24] Swap Nodes in Pairs # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def swapPairs(self, head: ListNode) -> ListNode: curr = dummyHead =...
573
205
####################################################### # # CEOControl.py # Python implementation of the Class CEOControl # Generated by Enterprise Architect # Created on: 16-5��-2019 12:06:10 # Original author: ���� # ####################################################### from Models.Statement import Statement...
1,593
526
import abc import pathlib from importlib import util as importlib_util from typing import Optional, Protocol from plugins.models import MPlugin class TopNavProtocol(Protocol): @property def public_has_top_nav(self) -> bool: """Does this plugin have public facing top nav?""" return False cla...
2,104
570
# Запросите у пользователя значения выручки и издержек фирмы. Определите, с каким финансовым результатом работает фирма # (прибыль — выручка больше издержек, или убыток — издержки больше выручки). Выведите соответствующее сообщение. Если # фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибы...
1,102
422
import os from abc import ABCMeta, abstractmethod from types import MappingProxyType import dask.dataframe import pandas as pd class AbstractDataFrameFormat: """ Provides helper functions to serialize and deserialize pandas and dask dataframes. Instances of such classes can define their own default ...
5,825
1,555
print("This program calculates the area of a trapezoid.") height = float(input("Enter height of trapezoid:")) top_base_length = float(input("Enter top length of trapezoid:")) bottom_base_length = float(input("Enter bottom length of trapezoid:")) area_of_trapezoid = .5 * (top_base_length + bottom_base_length) * height p...
378
125
"""Define actions decorator.""" import inspect import pandas as pd from typing import cast from datetime import date, datetime from typing import Callable from pumpwood_communication.exceptions import PumpWoodActionArgsException class Action: """Define a Action class to be used in decorator action.""" def _...
5,498
1,395
# A binary linear classifier for MNIST digits. # # Poses a binary classification problem - is this image showing digit D (for # some D, for example "4"); trains a linear classifier to solve the problem. # # Eli Bendersky (http://eli.thegreenplace.net) # This code is in the public domain from __future__ import print_fun...
5,426
1,673
from views import displayUserProfile
37
8
#!/usr/bin/python # -*- coding: utf-8 -*- """ (https://www.kaggle.com/c/ashrae-energy-prediction). Train shape:(590540,394),identity(144233,41)--isFraud 3.5% Test shape:(506691,393),identity(141907,41) ############### TF Version: 1.13.1/Python Version: 3.7 ############### """ import os import math import random impo...
5,409
2,190
import matplotlib.pyplot as plt from base.base_trainer import BaseTrainer from base.base_dataset import BaseADDataset from base.base_net import BaseNet import seaborn as sns from torch.utils.data.dataloader import DataLoader from sklearn.metrics import roc_auc_score, confusion_matrix, average_precision_score, roc_curve...
8,774
2,864
from .load_image import load_image from .normalize_image import normalize_image from .remove_artefacts import remove_artefacts, fill_small_white_blobs, fill_small_black_blobs from .padding import trim_padding, add_padding from .inpaint import inpaint from .darken import darken from .difference_of_gaussians_pyramid impo...
1,430
501
#!/usr/bin/env python # coding:utf8 # @Date : 2018/8/27 # @Author : Koon # @Link : chenzeping.com # When I wrote this, only God and I understood what I was doing. Now, God only knows. class Subject(object): def request(self): print("Subject instance has been created") class RealSubject(Subject): ...
625
197
from .base import BaseTest from authors.apps.articles.models import Article from rest_framework.views import status import json class CommentsLikeDislikeTestCase(BaseTest): """test class for liking and disliking comments """ def create_article(self, token, article): """ Method to create an article"""...
4,680
1,371
import socket import numpy import cv2 import threading import os BUFFER_SIZE = 4096*10 currentPort = 50001 buf = b'' class capture(): def __init__(self,port): self.port = port def recive(self): global buf with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: while T...
1,577
481
""" Forum signal receivers ====================== This module defines signal receivers. """ from django.db.models import F from django.dispatch import receiver from machina.apps.forum.signals import forum_viewed @receiver(forum_viewed) def update_forum_redirects_counter(sender, forum, user, request, r...
565
162
for t in range(int(input())): r,c,k = map(int , input().split()) circuit_board = [] for i in range(r): circuit_board.append(list(map(int,input().split())))
185
66
# Copyright (C) 2018 Verizon. All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
1,978
548
def TravelThrewTreeNodes(currentTreeNode, leftDirections, encodedSign): # Überprüfung, ob die letzte Stelle erreicht wurde. Sollte dies nicht der Fall sein so wird weiter durch den # Baum navigiert if not len(leftDirections) == 1: # Speicherung der nächsten Richtung nextDirection = left...
2,213
611
skills_list = [ "actionscript", "ado.net", "ajax", "akka", "algorithm", "amazon-ec2", "amazon-s3", "amazon-web-services", "android", "angular", "angularjs", "ansible", "ant", "apache", "apache-camel", "apache-kafka", "apache-poi", "apache-spark", ...
5,633
2,260
# handler module centralize the control
40
9
def escape_team_names(mystr): """ temporary fix for solving ? characters in bad team names encoding from LFP's ICS calendar """ mystr = mystr.replace('N?MES','NÎMES') mystr = mystr.replace('SAINT-?TIENNE','SAINT-ÉTIENNE') mystr = mystr.replace('H?RAULT', 'HÉRAULT') return mystr
313
116
def grid_scan_xpcs(): folder = "301000_Chen34" xs = np.linspace(-9350, -9150, 2) ys = np.linspace(1220, 1420, 2) names=['PSBMA5_200um_grid'] energies = [2450, 2472, 2476, 2490] x_off = [0, 60, 0, 60] y_off = [0, 0, 60, 60] xxs, yys = np.meshgrid(xs, ys)...
6,054
2,687
"""Plotting support""" def source_attribution(ax, text ): ax.text(0, -.05, text, fontsize=14, horizontalalignment='left', verticalalignment='top', transform=ax.transAxes)
199
65
import sublime import sublime_plugin import re import webbrowser from .lib.hl7Event import * from .lib.hl7Segment import * from .lib.hl7TextUtils import * hl7EventList = hl7Event("","") hl7EventList = hl7EventList.loadEventList() hl7SegmentList = hl7Segment("","") hl7SegmentList = hl7SegmentList.loadSegmentList() S...
9,298
3,954
# https://leetcode.com/problems/sort-items-by-groups-respecting-dependencies/ # graph, dfs class Solution: def sortItems(self, n: int, m: int, group: List[int], beforeItems: List[List[int]]) -> List[int]:
218
76
#!/usr/bin/python3 import argparse import time import cv2 import glob import sys from pathlib import Path import numpy as np import pandas as pd import yaml from multiprocessing.dummy import Pool as ThreadPool sys.path.append(Path(__file__).resolve().parent.parent.as_posix()) # repo path sys.path.append(Path(__file...
8,220
2,869
#!/usr/bin/python # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
3,004
1,066
import os from cryptography.fernet import Fernet def encrypt_password(password: str, key): f = Fernet(key) return str(f.encrypt(bytes(password, 'utf-8')), 'utf-8') def decrypt_password(password: str, key): f = Fernet(key) return str(f.decrypt(bytes(password, 'utf-8')), 'utf-8') KEY = os.environ.ge...
337
128
# This empty file makes the sphinxcontrib namespace package work. # It is the only file included in the 'sphinxcontrib' conda package. # Conda packages which use the sphinxcontrib namespace do not include # this file, but depend on the 'sphinxcontrib' conda package instead.
275
72
import boto3 import os import requests class ApiTestClient(): api_endpoint: str some_metadata = { 'timestamp': '123123', 'command_id': '456346234', 'issued_by': 'test@test.com' } some_events = [ { "type": "init", "foo": "bar" }, { "type": "update", "foo": ...
2,941
878
import eventlet import json import rest_lib import urllib import logging as log from openstack_dashboard.dashboards.project.connections import bsn_api eventlet.monkey_patch() URL_TEST_PATH = ('applications/bcf/test/path/controller-view' '[src-tenant=\"%(src-tenant)s\"]' '[src-segment...
4,076
1,101
# # PySNMP MIB module ROHC-MIB (http://pysnmp.sf.net) # ASN.1 source http://mibs.snmplabs.com:80/asn1/ROHC-MIB # Produced by pysmi-0.0.7 at Sun Feb 14 00:27:00 2016 # On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose # Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52) # ( Integer, O...
40,407
13,431
from autogluon.features.generators import DatetimeFeatureGenerator def test_datetime_feature_generator(generator_helper, data_helper): # Given input_data = data_helper.generate_multi_feature_full() generator_1 = DatetimeFeatureGenerator() generator_2 = DatetimeFeatureGenerator(features = ['hour']) ...
3,085
1,101
#!/usr/bin/env python import os os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"]="0" import common as cm import tensorflow as tf import numpy as np import math from scipy import stats from Bio.Seq import Seq half_size = 500 batch_size = 128 scan_step = 1 seq_len = 1001 out = [] os.chdi...
2,785
1,096
from strong_but_simple_passwords import views def test_index_http_ok(client): response = client.get("/") assert response.status_code == 200 def test_empty_post(monkeypatch, client): a_random_sentence = "A random sentence." monkeypatch.setattr(views, "get_random_sentence", lambda: a_random_sentence) ...
740
235
#!/usr/bin/env python3 import sys def search(query, data): query = query.replace('-',' ') words = set(query.upper().split()) for code, char, name in data: name = name.replace('-',' ') if words <= set(name.split()): yield f'{code}\t{char}\t{name}' def reader(): with open('U...
865
293
import json from django.shortcuts import render, redirect, HttpResponse # Create your views here. from django.urls import reverse from app01 import models from app01.models import Book, Publish, Author, AuthorDetail def books(request): book_list = Book.objects.all() publish_list = Publish.objects.all() ...
6,154
1,916
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Talk with a model using a Slack channel. # Examples ```shell parlai interactive_slack --token xoxb-... --task blend...
3,642
1,147
''' Includes content from another template. If you assign any keyword arguments, those will be available in the scope of that template. ''' import os from plywood import Plywood from plywood.values import PlywoodValue from plywood.exceptions import InvalidArguments from plywood.env import PlywoodEnv @PlywoodEnv.reg...
2,542
718
"""Handle M3U files generation""" import os import logging def generate(software, out_dir, suffix, dry_run): """Generate M3U file for the given software into out_dir""" m3u_filename = software.name + (suffix if suffix else '') + '.m3u' if not dry_run: m3u_fd = open(os.path.join(out_dir, m3u_file...
1,178
402
class Solution(object): def XXXUnique(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ if not nums: return [] nums.sort() n = len(nums) visited = [0] * n res = [] def helper1(temp_list, length): # if length == n and temp_list not in res: ...
860
400
import os import sys import shutil import io # if you got module not found errors, uncomment these. PyCharm IDE does not need it. # get the abs version of . and .. and append them to this process's path. sys.path.append(os.path.abspath('..')) sys.path.append(os.path.abspath('.')) #print sys.path import unittest ...
7,635
2,515
segundos_str = int(input("Por favor, entre com o número de segundos que deseja converter:")) dias=segundos_str//86400 segs_restantes1=segundos_str%86400 horas=segs_restantes1//3600 segs_restantes2=segs_restantes1%3600 minutos=segs_restantes2//60 segs_restantes_final=segs_restantes2%60 print(dias,"dias,",hora...
388
179
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Dec 2 15:37:10 2020 Copyright 2020 by Hadrien Montanelli. """ # %% Imports. # Standard library imports: import numpy as np # Chebpy imports: from chebpy.cheb import chebpts, coeffs2vals, vals2coeffs # %% Transforms (1D) on [-1,1]. f = lambda x: np....
1,323
693
import urllib import StringIO import gzip from difflib import Differ from binascii import unhexlify import Image src = urllib.urlopen('http://huge:file@www.pythonchallenge.com/pc/return/deltas.gz').read() file = gzip.GzipFile(fileobj=StringIO.StringIO(src)) left = [] right = [] for line in file.readlines(): left.ap...
870
348