text
string
size
int64
token_count
int64
import dataclasses import random import re from typing import Callable, Set, Dict, Any, List from mappi.utils import get_expression_variables @dataclasses.dataclass(frozen=True) class MappiFunction: name: str expr: str func: Callable variables: Set[str] @classmethod def parse(cls, name: str,...
1,917
591
from argparse import ArgumentParser import torch import torch.nn as nn import pytorch_lightning as pl class Attention1D(nn.Module): """Attention mechanism. Parameters ---------- dim : int The input and out dimension of per token features. n_heads : int Number of attention heads. ...
6,657
2,381
from tkinter.filedialog import * import tkinter as tk def saveFile(): new_file = asksaveasfile(mode = 'w', filetype = [('text files', '.txt')]) if new_file is None: return text = str(entry.get(1.0, END)) new_file.write(text) new_file.close() def openFile(): file = askopenfile(mode...
1,084
404
"""empty message Revision ID: 215a632cdf23 Revises: f5f69376d382 Create Date: 2017-07-09 17:04:22.228617 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '215a632cdf23' down_revision = 'f5f69376d382' branch_labels = None depends_on = None def upgrade(): # ...
681
272
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Sep 1 18:04:35 2019 @author: charleshen @usage:graph descriptors http://rdkit.org/docs/source/rdkit.Chem.rdmolops.html https://www.rdkit.org/docs/source/rdkit.Chem.GraphDescriptors.html#rdkit.Chem.GraphDescriptors.Chi0 Subgraphs are potentially bran...
4,476
1,625
import statistics # This code demonstrates that we have a mode value. values = [8, 11, 9, 14, 9, 15, 18, 6, 9, 10] mode = statistics.mode(values) print(mode) # This code demonstrates that we cannot calculate mode value because there # are more then one mode. values = [8, 9, 10, 10, 10, 11, 11, 11, 12, 13] mod...
360
148
# pip install ciscoconfparse from ciscoconfparse import CiscoConfParse cisco_cfg = CiscoConfParse("cisco.txt") # load configuration from cisco.txt to variable intf = cisco_cfg.find_objects(r"interface") # find pattern interface # # print(intf) # print lines including 'interface' in a HTML-like format print("\n\n") fo...
1,208
423
"""Common count snippets.""" from spacy import registry from traiter import util as t_util from traiter.actions import REJECT_MATCH from traiter.const import CROSS from traiter.const import SLASH from traiter.patterns.matcher_patterns import MatcherPatterns from ..pylib import const NOT_COUNT_WORDS = CROSS + SLASH + ...
2,651
960
from django.urls import path from . import views app_name = 'account' urlpatterns = [ path('home/', views.index, name='index'), path('', views.Login.as_view(), name='login'), path('newAccount', views.CreateAccount.as_view(), name='account'), # path('newAccount/create', views.CreateAccount, name='crea...
326
102
import sys from pyspark import SparkContext, SparkConf, HiveContext, SQLContext if __name__ == '__main__': conf = SparkConf().setAppName("Plotly Exports") sc = SparkContext(conf=conf) hive_context = HiveContext(sc) print '=== Creating Database ===' hive_context.sql('CREATE DATABASE PLOTLY') hiv...
928
322
# -*- coding: utf-8 -*- # Copyright (c) 2020, Lintec Tecnología and contributors # For license information, please see license.txt from __future__ import unicode_literals from . import fetch import frappe from frappe import _ from frappe.utils import now_datetime import collections import json from frappe.model.docum...
11,955
3,269
from eztools import converters def test_to_int(): assert converters.to_int(123) == 123
93
37
""" Copyright (c) 2020-present, Facebook, Inc. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. """ import unittest import warni...
6,160
1,952
from typing import List class Solution: def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool: return not (rec1[2] <= rec2[0] or rec1[3] <= rec2[1] or rec1[0] >= rec2[2] or rec1[1] >= rec2[3]) if __name__ == "__main__": s =...
412
161
#!/usr/bin/env python3 ''' Given a common phrase, return False if any individual word in the phrase contains duplicate letters. Return True otherwise. ''' def no_duplicate_letters(phrase): val = [phrase] nlst = ' '.join(val).split() st = [len(i) for i in nlst] ev = [len(set(i)) for i in nlst] return st == ev #A...
535
197
''' ''' import os from keras import backend as K import numpy as np from PIL import Image from yolo import YOLO from yolo3.utils import letterbox_image from vvc.config import model_folder class YOLOV3(object): ''' classdocs ''' def __init__(self, model_name, body_name): ''' Construc...
2,957
966
import arcade def on_draw(delta_time): """ Use this function to draw everything to the screen. """ # Start the render. This must happen before any drawing # commands. We do NOT need an stop render command. arcade.start_render() # Draw shapes on_draw.rectangle.draw() on_draw.oval.draw() ...
3,192
1,478
def self(): # ok pass self = 1 # ok class A: def foo(self, a): (self, (a, b)) = 1, ((22, 23)) if 1: a = {} self = 23 for (self, a) in []: pass def boo(): self = 1 def moo(self): def inner_moo(): self =1 def self(): pass class self: ...
510
203
from pathlib import Path from ..base_classes.base_json_sprite_merger import BaseJsonSpriteMerger from ..monsters.pets import Pets from ..journal_mons import JournalMonsterSheet class MontySpriteMerger(BaseJsonSpriteMerger): _target_sprite_sheet_path = Path("Data/Textures/Entities/Pets/monty.png") _grid_hint_...
1,070
438
import datetime import os import pathlib import shutil from random import randint, randrange from typing import Any, List from faker import Faker from django.conf import settings from django.contrib.auth import get_user_model from django.db import IntegrityError, transaction from django.utils import timezone from po...
8,955
2,780
# 1. uzdevums # Dotas divas taisnstūra malas 4, 7 aprēķināt taisnstūra laukumu. mala_A = 4 mala_B = 7 laukums = (mala_A * mala_B) print("Taisnstūra laukums ir: ",laukums) # 2. uzdevums # Dota temperatūra Celsija grādos 21, cik tas būs Fārenheiti? celsius = 27 fahrenheit = (celsius * 9/5) + 32 print("Fārenheiti:", fa...
495
266
import pandas as pd import datetime from sklearn.ensemble import RandomForestRegressor from sklearn.externals import joblib import json import getpass from db import getconfig from sqlalchemy import create_engine class model(): def __init__(self,from_data=False, from_pikl=False): if from_data == True:...
8,638
2,636
import numpy as np import gym_electric_motor as gem import gem_controllers as gc class CurrentController(gc.GemController): def control(self, state, reference): raise NotImplementedError def tune(self, env, env_id, **kwargs): raise NotImplementedError @property def voltage_referenc...
459
143
## IMPORT # You always put the ForeignKey in the table which contains only one of those many items ## ONE parent TO MANY children relationships: class Parent(db.Model): id = db.Column(db.Integer, primary_key=True) children = db.relationship("Child", backref="parent") class Child(db.Model): id = db.Colum...
2,152
749
import hashlib import json from typing import Optional, Any, Dict, Iterable from cached_property import cached_property from entrypoints import EntryPoint, BadEntryPoint from .exceptions import TaskMisconfigured class Task: """ A class for defining tasks the run in the repositories. The task is defined by an en...
3,377
925
import numpy import pytest from scipy.spatial import Delaunay import helpers import optimesh from meshes import pacman, simple1 @pytest.mark.parametrize( "mesh, ref1, ref2, refi", [ (simple1, 4.9863354526224510, 2.1181412069258942, 1.0), (pacman, 1.9378501813564521e03, 7.5989359705818785e01, ...
4,154
1,994
import unittest class NumbersTest(unittest.TestCase): def test_multiply(self): self.assertEqual(2 * 2, 4) def test_divide(self): self.assertEqual(7 // 2, 3) def test_equal(self): self.assertEqual(1 + 1, 2) if __name__ == '__main__': unittest.main()
296
116
from unittest import TestCase from laboratorio_7.Cuenta import Cuenta class TestCuenta(TestCase): def test_deposito(self): c=Cuenta() self.assertLess(c.deposito(1000), 600) def test_retiro(self): c=Cuenta() self.assertEqual(c.retiro(1000), 500)
300
127
from .common.MapGrid import * from .localisation.ParticleFilter import *
89
22
# -*- coding:utf-8 -*- # TODO: rollback # TODO: Melhor forma de lidar com settings import os from fabric.api import run, env, cd, put, sudo from fabric.contrib.files import upload_template, exists from fabric.context_managers import prefix, settings from provyfile import servers def uptime(): run("uptime") de...
2,697
871
# Generated by Django 3.2.4 on 2021-07-02 21:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('listings', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='listing', name='bathroom', ...
519
164
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys from setuptools import setup name = 'drf_mixin_tools' package = 'drf_mixin_tools' description = 'Collection of helpfull tools for drf' url = 'https://github.com/nabakirov/drf_mixin_tools' author = 'Nursultan Abakirov' author_email = 'nabakirov@gmail.c...
1,534
515
from os import getenv from dotenv import load_dotenv load_dotenv() API_KEY = getenv("API_KEY") API_SECRET_KEY = getenv("API_SECRET_KEY") ACCESS_TOKEN = getenv("ACCESS_TOKEN") ACCESS_TOKEN_SECRET = getenv("ACCESS_TOKEN_SECRET") TWITTER_CREDENTIALS = (API_KEY, API_SECRET_KEY, ACCESS_TOKEN, ACCESS_TOKEN_SECRET) HOME2_...
390
203
import nomad import pytest import tests.common as common @pytest.fixture def nomad_setup(): n = nomad.Nomad(host=common.IP, port=common.NOMAD_PORT, verify=False, token=common.NOMAD_TOKEN) return n @pytest.fixture def nomad_setup_with_namespace(): n = nomad.Nomad(host=common.IP, port=common.NOMAD_PORT, ver...
824
333
import json import math from django.shortcuts import render, redirect from django.conf import settings as ccsettings from django.contrib.auth.decorators import login_required from django.contrib.auth import views from django.utils.translation import ugettext as _ from django.views.generic.edit import FormView from cont...
5,948
1,667
import logging import os from pathlib import Path from typing import Optional, Union import numpy as np import pandas as pd import merlin.io # Get dataframe library - cuDF or pandas from merlin.core.dispatch import get_lib from merlin.core.utils import download_file from merlin.datasets import BASE_PATH from merlin....
14,608
5,062
from pydantic import ValidationError from . import errors from . import models def validate_profileinput(profile_raw): """Validate ProfileInput user input data.""" profile, errs = None, [] try: profile = models.ProfileInput(**profile_raw).dict() except ValidationError as e: errs = e.e...
530
160
"""Types and classes for typing Notify calls We want to be able to use static typing on email_engine so that coding mistakes can be caught before run time. Also, we create some classes to help with saving a notification to a file and reading it back into memory in a human readable fashion. """ from ast import litera...
3,250
811
from django.contrib import messages from django.forms import formset_factory from django.http import HttpResponse from django.shortcuts import render from django.views import View from django_dynamic_formsets.example_files.forms import ExampleForm1, ExampleForm2 from django_dynamic_formsets.users.models import Example...
2,321
690
import cv2 import sys import math import numpy as np ROI_THRESHOLD=[10, 100, 200] def flatten(img): r, g, b = cv2.split(img) r_filter = (r == np.maximum(np.maximum(r, g), b)) & (r >= 120) & (g < 150) & (b < 150) g_filter = (g == np.maximum(np.maximum(r, g), b)) & (g >= 120) & (r < 150) & (b < 150) b_f...
5,283
2,497
class DetailedAlignment: """ This class represents a detailed alignment """ def __init__(self, aln): self.aln = aln # this will be dropped in the feature, so that memory does not blow up self.number_of_S = 0 self.split_event_list = list() self.regions_set = set() self....
350
105
import torch.nn as nn from dl_toolbox_cwm.model.utils.core.registry import Registry, build_from_cfg __all__ = [ 'build_backbone', 'build_head', 'build_neck', 'build_loss', 'build_classifier' ] BACKBONES = Registry('backbone') CLASSIFIERS = Registry('classifier') HEADS = Registry('head') NECKS = Registry('neck') ...
914
339
from django.http import HttpResponse, HttpResponseRedirect from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.shortcuts import get_object_or_404, render, render_to_response from django.urls import reverse from .forms import CommentForm from blog.models import Category, Post, Comment, ...
3,897
1,179
import urllib import ssl # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE html=urlopen('https://www.oanda.com/fx-for-business/historical-rates?utm_source=average_rates', context=ctx).read() print(html) for line in html:
299
107
#!/usr/bin/python3 -*- coding: utf-8 -*- ##### IMPORTS ##### import termios import datetime import tty import sys import os import picamera import time ##### VARIABLES ##### today = datetime.date.today() folderPath = "/home/pi/timelapse" timeNow = "" dateNow = "" fileName = "" intervalT...
2,522
875
import logging import math import ee import pytest import openet.disalexi.tseb_utils as tseb_utils import openet.disalexi.utils as utils from .idl_values import ne1, ne2, ne3 # AmeriFlux sites adjusted to nearest Landsat cell centroid # ne1_xy = [-96.47672812080845, 41.16506126041818] # ne2_xy = [-96.46994024736414...
24,998
13,934
# -*- coding: utf-8 -*- # The MIT License (MIT) # # Copyright © 2014 Tim Bielawa <timbielawa@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 with...
4,061
1,342
## 1. Overview ## f = open("movie_metadata.csv", "r") movies = f.read() split_movies = movies.split("\n") movie_data = [] for each in split_movies: movie_data.append(each.split(",")) print(movie_data[0:5]) ## 3. Writing Our Own Functions ## def first_elts(input_lst): elts = [] for each in input_lst: ...
2,691
984
""" image_retrieval.py (author: Anson Wong / git: ankonzoid) We perform image retrieval using transfer learning on a pre-trained VGG image classifier. We plot the k=5 most similar images to our query images, as well as the t-SNE visualizations. """ import os import numpy as np import tensorflow as tf from sklea...
6,470
2,191
import geopandas import pandas import ogr import os import numpy import gdal from tqdm import tqdm from pygeos import from_wkb def query_b(geoType,keyCol,**valConstraint): """ This function builds an SQL query from the values passed to the retrieve() function. Arguments: *geoType* : Type of geome...
5,434
1,598
""" Plot the 10-year US Treasury/Euro area AAA govvie spread in 4 -- count'em, 4 -- lines of code. (Couldn't find a daily bund series...) """ from econ_platform.start import fetch, quick_plot ust10 = fetch('F@DGS10') euro_AAA_10 = fetch('D@Eurostat/irt_euryld_d/D.EA.PYC_RT.Y10.CGB_EA_AAA') quick_plot(ust10-euro_AAA_...
375
174
import pytest from seleniumbase import BaseCase from qa327_test.conftest import base_url from unittest.mock import patch from qa327.models import db, User from werkzeug.security import generate_password_hash, check_password_hash """ This file defines all unit tests for the frontend homepage. The tests will only test...
8,077
2,556
import matplotlib.pyplot as plt import numpy as np import numpy.fft as fft plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签 plt.rcParams['axes.unicode_minus'] = False # 用来正常显示符号 Fs = 1000 # 采样频率 T = 1 / Fs # 采样周期 L = 1000 # 信号长度 t = [i * T for i in range(L)] t = np.array(t) S = 0.2 + 0.7*np.cos(2*np.pi*...
397
247
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jun 18 11:28:59 2020 @author: jlee """ import time start_time = time.time() import numpy as np import glob, os, copy import fsps # sp.libraries = (b'mist', b'miles') import init_hstacs_mist_test as ini # ----- Obtaining magnitudes ----- # for i in ...
1,479
763
from unittest import TestCase, mock from chargebee_byte.client import Client class TestBase(TestCase): def setUp(self): self.chargebee_client = Client('my_site', 'my_api_key') def set_up_patch(self, topatch, themock=None, **kwargs): """ Patch a function or class :param topatc...
641
195
#stats.py class Stats(): def __init__(self): self = self def total(self, list_obj): total = 0 n = len(list_obj) for i in range(n): total += list_obj[i] return total def mean(self, list_obj): n = len(list_obj) mean = self...
5,933
2,101
import os from base64 import b64decode, b64encode from datetime import date from ghapi.actions import github_token from ghapi.all import GhApi from IPython.display import Markdown OWNER = "Quansight-Labs" REPO = "jupyter-a11y-mgmt" # ------------------------------------------------------------------ # On GitHub Act...
1,966
627
""" Computes equilibrium price and quantities, take 2. """ from numpy import exp from scipy.optimize import bisect def supply(price, b): return exp(b * price) - 1 def demand(price, a, epsilon): return a * price**(-epsilon) def compute_equilibrium(a, b, epsilon): plow = 0.1 phigh = 10.0 def excess_s...
678
252
"""Helper functions for dealing with the pyproject file.""" from __future__ import annotations from pathlib import Path from typing import Sequence def get_pyproject(config_name: Path | str = "pyproject.toml") -> Path: """Get the location of pyproject.toml in the first parent diretory.""" cwd = Path.cwd().ab...
874
261
# -*- encoding: utf-8 -*- try: from setuptools import setup, Extension except ImportError: from distutils.core import setup, Extension setup( name='SecureString', version='0.2', description='Clears the contents of strings containing cryptographic material', author=u'András Veres-Szentkirályi, ...
531
177
# © 2019 Nokia # Licensed under the BSD 3 Clause license # SPDX-License-Identifier: BSD-3-Clause import os import jinja2 import yaml from radish_ext import get_radish_ext_etc_dir from radish_ext.sdk.l import Logging from radish_ext.sdk.config import Config class CfgComponentException(Exception): pass class ...
2,666
879
# Write functions for sending email here. from core.models import Bibtex from django.contrib.auth.decorators import login_required from django.core.mail import send_mail from django.template.loader import get_template from notification.const import address @login_required def send_email_test(): # 件名 subject =...
2,660
833
# Copyright (c) 2021 by Don Deel. All rights reserved. """ Handle mockup I/O for fishem. """ # Standard library module imports import json # JSON handling import os # File I/O handling # Third party module imports import xmltodict # XML handling for mockups #...
6,713
1,801
from django.contrib import admin from .models import Movement, Account # Register your models here. admin.site.register(Movement) admin.site.register(Account)
160
45
""" Django settings for mysite project. Generated by 'django-admin startproject' using Django 2.1.1. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # ...
4,222
1,461
from dataclasses import dataclass import numpy as np import zarr from dask import array as da from scipy.spatial.transform import Rotation as R from create_data import CreateData from utils.cli import read_args from utils.logger import logger from utils.timer import timer @dataclass class LinearSearch: data: za...
3,783
1,129
# yto YouTube object import os from yt_concate.settings import CAPTIONS_DIR, VIDEOS_DIR class YTO: def __init__(self, url): self.url = url self.v_id = self.get_video_id_from_url(url) self.caption_filepath = self.get_caption_filepath() self.video_filepath = self.get_video_filepath()...
770
294
# Copyright (c) 2019 Horizon Robotics. 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 applicab...
35,559
10,411
import sys import re DEBUG = False INTENT_WEIGHTS = { #portable budget workstation gaming fast storage touchscreen screenquality "photography": [7.0, 3.0, 6.0, 2.0, 6.0, 10.0, 1.0, 10.0], "gaming": [2.0, 2.0, 7.0, 8.0, 8.0, ...
3,273
1,165
from numpy import random from ..interval_algebra import ( converse, meets, before, starts, during, finishes, equals, overlaps, negate, get_intervals_relations ) from ..regions import Region from copy import deepcopy def app(x, z, first, second, elements): elements.remove(x) elements.remove(z) ...
8,681
3,206
#!/bin/python import argparse import json import logging import re import os.path from urllib.parse import urlparse from google.cloud import storage """ Summary: Find GCS paths for specified workflow file outputs for multiple workflows at once without downloading metadata. Caveats: Assumes cromwell file structure. ...
13,011
3,605
import os from config import INPUT_DIRECTORY from config import OUTPUT_DIRECTORY def get_best_score(): best_scores = {} for output_filename in os.listdir(OUTPUT_DIRECTORY): if output_filename.startswith('.'): continue current_score = 0 input_filename = get_input_from_ou...
861
274
import sys import os from perper.model import StreamFlags from perper.model import State from perper.model import Context from perper.services import Serializer from perper.services import FabricService from perper.services import PerperConfig from perper.cache import PerperInstanceData from perper.utils import PerperT...
2,676
779
import numpy as np from object_detection.utils.np_box_list import BoxList from object_detection.utils.np_box_list_ops import ( prune_non_overlapping_boxes, clip_to_window, concatenate, non_max_suppression) from rastervision.core.box import Box from rastervision.core.labels import Labels class ObjectDetectio...
6,624
1,900
""" author: ouyangtianxiong date: 2019/12/23 des: implements attention-based emotion recognition Based on code from https://github.com/KaihuaTang/VQA2.0-Recent-Approachs-2018.pytorch """ import sys sys.path.append('../') __author__ = 'ouyangtianxiong.bupt.edu.cn' from sklearn.metrics import classification_report, confu...
36,348
12,244
def greet(name: str) -> str: """Greet in Spanish""" return f"¡Hola, {name}!"
86
36
# -*- coding: utf-8 -*- # Generated by Django 1.11.14 on 2020-06-29 11:12 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mophealth', '0002_scanlog_taskurl'), ] operations = [ migrations.AlterFiel...
480
176
import json from tests.routes.test_helpers.route_test_case import RouteTestCase from server.database.models import Recipe, User def create_recipe_ingredients(): ingredients = [{ "name": "test", "unit": "kg", "quantity": 4 }] * 100 return json.dumps(ingredients) def create_recipe...
1,362
701
#!/usr/bin/env python from __future__ import division import os, sys, argparse import datetime import gzip import model import neural import scorer import numpy as np from sklearn.feature_extraction import DictVectorizer from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_spli...
11,582
4,177
# # Copyright 2022 DMetaSoul # # 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 writin...
2,377
767
# -*- coding: utf-8 -*- """Text manipulation and processing.""" # Part of Clockwork MUD Server (https://github.com/whutch/cwmud) # :copyright: (c) 2008 - 2017 Will Hutcheson # :license: MIT (https://github.com/whutch/cwmud/blob/master/LICENSE.txt) # TODO: should every character after a caret be considered a code? CAR...
861
342
## Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. ## Example: ## Given array nums = [-1, 2, 1, -4], and target = 1. ## The sum that is close...
1,173
343
"""Appends XML elements specifying optional dependencies to a plugin XML file. """ import argparse import sys from xml.dom.minidom import parse # pylint: disable=g-importing-member try: from itertools import izip # pylint: disable=g-importing-member,g-import-not-at-top except ImportError: # Python 3.x already h...
1,659
548
import multiprocessing as mp import queue import time from typing import Callable, Iterable, Iterator, List, Optional from .handler import BaseTaskHandler from .logger import log from .metrics.timer import timeit from .task import BaseTask, StopTask def batches( elements: Iterable, batch_size: int, ...
5,079
1,427
#!/usr/bin/python # -*- coding: utf-8 -*- import json import os.path import yaml def load_yaml_file_as_dict(yaml_path): with open(yaml_path, "r") as yaml_file: data = yaml.load(yaml_file, Loader=yaml.FullLoader) return data def fetch_json_file_as_dict(filepath): with open(filepath) as userData: data = json....
651
261
""" Pipeline object class for Property (http://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-object-property.html) """ from ..config import Config from ..s3 import S3LogPath from ..utils import constants as const from ..utils.exceptions import ETLInputError from .pipeline_object import PipelineObject from ....
656
183
from django.db import models from django.contrib import admin import os class DescriptionP(models.Model): id = models.AutoField(primary_key=True) content = models.TextField() def __str__(self): return self.content class DescriptionPAdmin(admin.ModelAdmin): list_display = ['id', 'content'] ...
1,024
315
# coding=utf-8 # Copyright 2016-2018 Emre Ahmetick # # 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 ...
73,483
22,788
from math import sqrt from math import pow from threading import Lock from operator import itemgetter import logging logger = logging.getLogger("logger") class AntGraph: def __init__(self, coord_mat, delta_mat=None, tau_mat=None): self.lock = Lock() self.build_nodes_mat(coord_mat) self.b...
3,663
1,261
import mysql.connector mydb = mysql.connector.connect( user="zman", password="Sai.k123089" ) print(mydb) mycorsor = mydb.cursor() mycorsor.execute("use zman") #mycorsor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))") sql = "INSERT INTO customers (name, address) VALUES (%s, %s)" val = [...
553
223
""" Problem: You come across a dictionary of sorted words in a language you've never seen before. Write a program that returns the correct order of letters in this language. For example, given ['xww', 'wxyz', 'wxyw', 'ywx', 'ywz'], you should return ['x', 'z', 'w', 'y']. """ from typing import Dict, List, Optional, ...
2,109
683
from django.urls import path from pdf_rendering_service.documents.views import ( DocumentPageView, DocumentUploadView, DocumentView, ) app_name = "documents" urlpatterns = [ path("documents", DocumentUploadView.as_view(), name="documents"), path("documents/<int:pk>", DocumentView.as_view(), name=...
598
187
from random import randint """ Заполнить список из 20 целых чисел случайными значениями из диапазона от –2 до 12. Преобразовать его таким образом, чтобы сначала шли отрицательные значения в порядке их появления в исходном списке, а затем нулевые, и, наконец, положительные значения """ array = [randint(-2, 12) for _...
470
194
""" *f64* """ import jax.numpy as jnp from .._datatype import Datatype from ._float import Float __all__ = ["f64"] class f64( jnp.float64, Float, Datatype, ): def __init__( self, value: int, ): super(f64, self).__init__( self, value, ...
323
124
import os import numpy as np import pandas as pd from PIL import Image import torch from torch.utils import data import torchvision.transforms as transforms class CustomDataset(data.Dataset): def __init__(self, root, phase='train', transform=None): self.root = root self.phase = phase self....
3,948
1,233
import numpy as np import matplotlib.pyplot as plt from scipy.io import loadmat from sklearn.svm import SVC from svm import * from process_email import * from get_vocab_dict import * import codecs def main(): # DATA PREPROCESSING vocab_dick = getVocabDict() dick_size = len(vocab_dick) validationPerce...
3,994
1,526
""" Module conataining the Conversation class. This class is used to create a conversation flow to the bot """ from .exception.Exceptions import * from telegram.ext import Filters,ConversationHandler class Conversation(): #static value to represent the end of a conversation END = ConversationHandler.END def __i...
8,533
2,644
from flask import Flask from flask.ext.script import Manager app = Flask(__name__) manager = Manager(app) @app.route('/') def index(): return '<h1>Hello World!</h1>' @app.route('/user/<name>') def user(name): return '<h1>Hello, %s!</h1>' % name if __name__ == '__main__': # app.run(debug=True) manage...
327
124
import numpy as np import sys import argparse # Parse command line arguments parser = argparse.ArgumentParser() #parser.add_argument('-I', help='Input file with raw coverage data') parser.add_argument('--input_one', help='', type=str) parser.add_argument('--input_two', help='', type=str) parser.add_argument('--inpu...
3,552
1,568
import os import sys import types from io import BytesIO from signal import SIGINT, SIGTERM from invoke.vendor.six import StringIO, b from spec import ( Spec, trap, eq_, skip, ok_, raises, assert_contains, assert_not_contains ) from mock import patch, Mock, call from invoke.vendor import six from invoke import ...
36,173
10,791