text
string
size
int64
token_count
int64
import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler import torchvision from torchvision import datasets, transforms from torch.utils.data import DataLoader import hawtorch import hawtorch.io as io from hawtorch import Trainer from hawtorch.metrics import ClassificationM...
3,234
1,027
""" Example of how to make a Scatterplot with a time component """ import slayer as sly import pandas as pd DATA_URL = 'https://raw.githubusercontent.com/ajduberstein/sf_growth/master/public/data/business.csv' businesses = pd.read_csv(DATA_URL) FUCHSIA_RGBA = [255, 0, 255, 140] color_scale = sly.ColorScale( pal...
718
284
import dictondisk import random import pytest import os remove_keys = {0, (33, 12.23), "c", "中国"} vanilla_dict = { 0: 1337, 1: 3.14, 2: 2.71, 3: 1.61, "a": "Ą", "b": "✈!", "c": "東京", "中国": "共産", (1, .5): "lorem", (33, 12.23): "ipsum", -1: ["one", "two", "three"] } def test_contains_update(): t = ...
3,699
1,539
from src.extentions import db from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash import datetime as dt # https://help.twitter.com/en/managing-your-account/twitter-username-rules # https://office-hack.com/gmail/password/ class User(UserMixin, db.Model): __ta...
1,904
597
import copy import enum from typing import * import numpy as np from shapely.geometry import MultiPolygon as ShapelyMultiPolygon from shapely.geometry import Point as ShapelyPoint from shapely.geometry import Polygon as ShapelyPolygon from shapely.strtree import STRtree import commonroad.geometry.transform from commo...
76,496
22,521
from django.urls import path from . import views urlpatterns = [ path("test/", views.index, name = "index"), path('completed/',views.show_completed,name= "completed"), path('<int:action_id>/', views.show_action, name='action'), path('update/', views.update_status, name="update_status"), path('new/...
363
121
import ast from typing import List, Optional, cast import pytest from dataframe_expressions import ( Column, DataFrame, ast_Callable, ast_Column, ast_DataFrame, define_alias) from .utils_for_testing import reset_var_counter # NOQA # numpy math functions (??) # Advanced math operators # (https://docs.python....
14,673
5,537
#!/usr/bin/env python # -*- coding: utf-8 -*- import redis rc = redis.StrictRedis(host='localhost', port=6379, db=0) def fifo_push(q, data): rc.lpush(q, data) def fifo_pop(q): return rc.rpop(q) def filo_push(q, data): rc.lpush(q, data) def filo_pop(q): return rc.lpop(q) def safe_fifo_push(q,...
520
239
# import encode import eel import cv2 import io import numpy as np import base64 import os import time import face_recognition import pickle import imutils import datetime from multiprocessing.pool import ThreadPool import random import shutil from database import * from camera import VideoCamera fro...
12,660
4,174
# -*- coding: utf-8 -*- __author__ = 'Huang, Hua' from models.object import JsonSerializableObj class CubeJobStatus: NEW = 'NEW' PENDING = 'PENDING' RUNNING = 'RUNNING' ERROR = 'ERROR' FINISHED = 'FINISHED' DISCARDED = 'DISCARDED' class JobInstance(JsonSerializableObj): def __init__(sel...
3,713
1,217
#!/usr/bin/python # -*- coding: utf-8 -*- import logging, sys from django.contrib.auth.decorators import login_required from django.shortcuts import render from walletgui.controller.global_constants import * from walletgui.controller.crypto_utils import CryptoUtility from walletgui.controller.walletmanager import Wal...
1,770
623
import numpy as np import networkx as nx # For illustration purpose only [easy to understand the process] # ----------------------------- def pure_cascade_virality(G): '''G is a directed graph(tree)''' if not nx.is_weakly_connected(G): # return None return nodes = [k for (k,v) in G....
1,643
562
import pyjira.api as _api import json as _json def get_issues(id, limit=50): """Return 50 issues for a project. Parameters: - id: id of a project. - limit: max number of results to be returned. """ return _api.rest("/search?jql=project=" + str(id) + "&maxResults=" + str(limit)) def get_issue...
1,492
480
import importlib from argparse import ArgumentParser from wsgiref.simple_server import make_server p = ArgumentParser( prog="gongish serve", description="Serve a WSGI application" ) p.add_argument( "module", nargs="?", help="Module and application name (e.g: myapp:app)", type=str, ) p.add_argument...
963
336
import unittest import redis import random class TestTrieCmd(unittest.TestCase): rr = redis.Redis("localhost", 6000) def tearDown(self): self.rr.execute_command("del trie") def test_basic_cmds(self): self.rr.execute_command("rset trie ape 1") self.rr.execute_command("rset trie ap...
2,248
772
#Secret Messages. New position alphabet = 'abcdefghijklmnopqrstuvwxyz' key = 3 character = input('Please enter a character ') position = alphabet.find(character) print('Position of a character ', character, ' is ', position) newPosition = position + key print('New position of a character ', character, ' is ', newPosit...
325
92
from examples.example_imports import * from manim_express.eager import PlotObj scene = EagerModeScene(screen_size=Size.bigger) graph = Line().scale(0.2) # t0 = time.time() # # delta_t = 0.5 # for a in np.linspace(3, 12, 3): # graph2 = ParametricCurve(lambda t: [t, # 0.8 * n...
1,376
559
#!/usr/bin/env python # Note that this is python3 only import argparse import requests parser = argparse.ArgumentParser( "Get an observation from a FHIR server with authentication") parser.add_argument( "id", help="The observation id to retrieve") parser.add_argument( "auth", default="Admin", help="The...
785
262
# # MythBox for XBMC - http://mythbox.googlecode.com # Copyright (C) 2010 analogue@yahoo.com # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at yo...
14,331
5,182
""" script to post-process training images by using OpenCV face detection and normalization MIT License Copyright (c) 2019 JinJie Chen 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 re...
3,989
1,240
import flask from flask import render_template from flask import request from flask import url_for import json import logging ### # Globals ### app = flask.Flask(__name__) import CONFIG ### # Pages ### @app.route("/") @app.route("/index") @app.route("/map") def index(): app.logger.debug("Main page entry") if '...
1,816
593
import xarray as xr import numpy as np from pathlib import Path from tcvx21.grillix_post.components import FieldlineTracer from tcvx21.grillix_post.lineouts import Lineout xr.set_options(keep_attrs=True) def initialise_lineout_for_parallel_gradient( lineout, grid, equi, norm, npol, stored_trace: Path = None ): ...
3,717
1,174
def test_import(): import skypy.galaxy import skypy.galaxy.ellipticity import skypy.galaxy.luminosity import skypy.galaxy.redshift import skypy.galaxy.size import skypy.galaxy.spectrum import skypy.galaxy.stellar_mass
246
92
# Test cases for HT operations with hostapd # Copyright (c) 2013-2014, Jouni Malinen <j@w1.fi> # # This software may be distributed under the terms of the BSD license. # See README for more details. import time import logging logger = logging.getLogger() import struct import subprocess import hostapd def clear_scan_...
22,466
7,874
# coding: utf-8 # author: Haydara https://www.youtube.com/haydara import pickle with open('vocabs.pkl', 'rb') as pickle_load: voc_list = pickle.load(pickle_load) allowed_chars = ['ذ', 'ض', 'ص', 'ث', 'ق', 'ف', 'غ', 'ع', 'ه', 'خ', 'ح', 'ج', 'د', 'ش', 'س', 'ي', 'ب', 'ل', 'ا', 'أ', 'ت', 'ن', '...
1,039
454
import facade import pytest import schemas @pytest.fixture(autouse=True) def configure_db_session(db_session): facade.db_session = db_session def test_get_item_list__empty(): assert facade.get_item_list() == [] def test_get_item_list__with_item(item_1): assert facade.get_item_list() == [item_1] def ...
6,513
2,681
import pandas import numpy as np from .reference_histogram_outlier import HistOutlier from typing import Union, Tuple class DOOTS(object): def __init__(self, data: pandas.DataFrame, weighting: bool = False, jaccard: bool = False): """ Params: data (DataFrame) - pandas DataFrame with c...
17,667
4,700
import numpy as np import fast_functions as ff import time def DSC_computation(label, pred): pred_sum = pred.sum() label_sum = label.sum() inter_sum = (pred & label).sum() return 2 * float(inter_sum) / (pred_sum + label_sum), inter_sum, pred_sum, label_sum def post_processing(F, S, threshold, top2): F_sum = F....
3,405
1,763
# -*- coding: utf-8 -*- # @Time : 2019/5/25 16:09 # @Author : Alan # @Email : xiezhengwen2013@163.com # @File : data_preprocess2.py # @Software: PyCharm # 自己写一个生成词表的函数 def read(stopword_file, in_file): pass
221
122
#!/usr/bin/env python # coding:utf-8 import pymysql default_config = { 'host': '139.196.96.149', 'port': 13306, 'user': 'dataway-rw', 'password': 'QqHVMhmN*8', 'db': 'jumei', 'charset': 'utf8mb4' } apollo_config = { 'host': '127.0.0.1', 'port': 11306, 'user': 'apollo-rw', 'passw...
1,160
568
import pyximport pyximport.install() from aoc24 import do_it do_it()
70
29
from opensimplex import OpenSimplex import torch, time def opensimplex_test(device: str): generator = torch.Generator(device=device) start = time.time() os = OpenSimplex(generator=generator) end = time.time() return os.noise2(10,10), device, end-start print(opensimplex_test('cuda')) pri...
358
125
from .levenshtein_distance import levenshtein_distance from .bk_tree import BKTree
83
30
import torch import torch.nn as nn from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence from collections import namedtuple from ELMo.modules.char_embedding import CharEmbedding class ELMo(nn.Module): """Implement the Embeddings from Language Models (ELMo) as described in "Deep contextualized w...
10,731
3,110
import datetime as dt import cx_Oracle from src.app.externalOutages.getReasonId import getReasonId def createRealTimeOutage(pwcDbConnStr: str, elemTypeId: int, elementId: int, outageDt: dt.datetime, outageTypeId: int, reason: str, elementName: str, sdReqId: int, outageTagId: int) -> int: ...
3,106
1,083
"""Utils for jitsi""" from datetime import timedelta from django.conf import settings from django.utils import timezone import jwt def create_payload(room, moderator=True): """Create the payload so that it contains each information jitsi requires""" token_payload = { "exp": timezone.now() + ...
918
295
from hashtable import Hashtable def test_create(): hashtable = Hashtable() assert hashtable def test_predictable_hash(): hashtable = Hashtable() initial = hashtable._hash('spam') secondary = hashtable._hash('spam') assert initial == secondary def test_in_range_hash(): hashtable = Hashtab...
1,356
447
import os, pickle, re import GlobalConstants as GC import configuration as cf # Custom Imports import MenuFunctions import Utility, Image_Modification, Engine, InputManager import logging logger = logging.getLogger(__name__) # === Simple Finite State Machine Object =============================== class...
65,879
21,267
import pytest from bloodsword.characters.sage import Sage from bloodsword.characters.warrior import Warrior from bloodsword.descriptors.armour import Armour @pytest.fixture def warrior(): return Warrior("Warrior", rank=2) @pytest.fixture def sage(): return Sage("Sage", rank=2) def test_character_initializ...
1,707
634
def nod(x,y): if y != 0: return nod(y, x % y) else: return x n1 = int(input("Введите n1: ")) n2 = int(input("Введите n2: ")) print("НОД = ", nod(n1,n2)) print("НОK = ", int((n1*n2)/nod(n1,n2)))
201
114
from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HContract03_IsolatedLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HContract03_IsolatedLHS """ # Flag this instance as compiled now self.is_compiled = True ...
2,417
1,035
# -*- coding: utf-8 -*- # Local imports from cpenv import mappings from cpenv.compat import platform def test_platform_values(): '''join_dicts with platform values''' tests = { 'implicit_set': { 'osx': 'osx', 'linux': 'linux', 'win': 'win', }, 'imp...
7,359
2,777
"""Database class.""" from flask_sqlalchemy import SQLAlchemy # type: ignore db = SQLAlchemy()
98
35
''' https://github.com/Adeon18/logical_puzzle ''' # There are now proper commits in this repository becouse I # created 1 repo for 2 tasks and then had to move import math def check_rows(board: list) -> bool: ''' Check for row correction in board. >>> check_rows(["**** ****", "***1 ****", "** 3****", "...
3,313
1,106
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
1,528
466
import tempfile import unittest from symplectic import jsonformat class JSONFormatTest(unittest.TestCase): def test_parse(self): with tempfile.NamedTemporaryFile() as fp: fp.write(""" { "title": "things", "slug": "stuff", "date": "2017-09-14 22...
587
186
import shutil import tempfile from django import forms from django.test import Client, TestCase from django.urls import reverse from posts.forms import PostForm from posts.models import Group, Post, User from django.conf import settings TEMP_MEDIA_ROOT = tempfile.mkdtemp(dir=settings.BASE_DIR) class StaticURLTes...
2,285
714
# -*- coding: utf-8 -*- # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2020 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTI...
8,460
3,629
# Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.com/) # # 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...
2,964
854
nominalization_list=["Buddhism", "Catholicity", "Catholicism", "Doppler", "evangelicality", "Frenchness", "Gaussianity", "Gothicness", "Indianness", "Irishness", "Jewishness", "Malthusianism", "mosaicity", "Nordicness", "northernness", "Polishness", "Protestantism", "regency", "Welshness", "abandonment", "abasement", "...
243,870
96,464
#!/usr/bin/env python # =============================================================================== # Copyright 2015 Geoscience Australia # # 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 ...
2,029
612
import unittest import numpy as np import El import skylark.nla as sl_nla from .. import utils class NLATestCase(unittest.TestCase): """Tests nla functions.""" def test_approximate_svd(self): """Compute the SVD of **A** such that **SVD(A) = U S V^T**.""" n = 100 # Generate random m...
2,516
1,007
import numpy as np import cv2 from matplotlib import pyplot as plt img = cv2.imread("images/watter.jpeg") img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) kernel = np.ones((5,5),np.float32)/25 dst1 = cv2.filter2D(img,-1,kernel) blur = cv2.blur(img,(5,5)) g_blur = cv2.GaussianBlur(img,(5,5),0) median_blur = cv2.medianBlur...
563
264
from django.http import HttpResponseRedirect class HttpResponseUriRedirect(HttpResponseRedirect): def __init__(self, redirect_to, allowed_schemes, *args, **kwargs): self.allowed_schemes = allowed_schemes super(HttpResponseUriRedirect, self).__init__(redirect_to, *args, **kwargs)
302
83
import time from datetime import timedelta from random import choice from typing import List, Optional from fastapi import Depends, FastAPI, File, UploadFile from fastapi.staticfiles import StaticFiles from passlib.context import CryptContext from pydantic import BaseModel from sqlalchemy.orm import Session from conf...
8,587
3,342
#! /usr/bin/env python # coding=utf-8 # ================================================================ # # Author : miemie2013 # Created date: 2020-10-15 14:50:03 # Description : pytorch_ppyolo # # ================================================================ import torch import torch.nn as nn import to...
7,665
3,076
from django.contrib.auth import get_user_model from .models import Account from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm User = get_user_model() class CustomCreateUser(UserCreationForm): class Meta: model = Account fields = ('username',)
312
85
from .ui_image import UIImage from .ui_button import UIButton from .ui_horizontal_slider import UIHorizontalSlider from .ui_vertical_scroll_bar import UIVerticalScrollBar from .ui_label import UILabel from .ui_screen_space_health_bar import UIScreenSpaceHealthBar from .ui_tool_tip import UITooltip from .ui_drop_down_me...
489
152
import imdb def movie(name): ia = imdb.IMDb() movie_obj = ia.search_movie(name) el = ia.get_movie(movie_obj[0].movieID) title = str(el.get('title')) year = str(el.get('year')) plot = str(el.get('plot')[0]) ty = False if str(el.get('kind')) == 'tv series': ty = True return(ti...
337
132
# -*- coding: utf-8 -*- """Project Packages Module.""" import shutil from pathlib import Path from typing import Any, Union from boltons import fileutils from micropy import utils from micropy.packages import (LocalDependencySource, PackageDependencySource, create_dependency_source) fr...
7,249
2,105
from .foreground import make_foreground from .point_sources import make_ptsrc_background, \ make_point_sources_file, make_point_source_list from .instrument import make_instrument_background from .spectra import BackgroundSpectrum, \ ConvolvedBackgroundSpectrum from .events import add_background_from_file from ...
361
99
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'endofsessiondialog.ui' # # Created by: PyQt4 UI code generator 4.11.1 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fro...
3,945
1,110
import ramda as R from ramda.shared import eq from .common import get_arity import pytest try: from collections.abc import Callable except ImportError: from collections import Callable @pytest.fixture def odd(): return lambda n: n % 2 != 0 @pytest.fixture def lt20(): return lambda n: n < 20 @pytes...
8,679
3,513
"""The dash-tab with forecast data.""" from typing import List import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html import plotly.graph_objects as go from dash.dependencies import Input, Output import covid19.forecast from covid19.data import DAY_ZERO_START f...
7,168
1,831
x = int(input()) y = int(input()) if x > y: x, y = y, x soma = 0 for i in range(x, y + 1): if i%13 != 0: soma += i print(soma)
145
74
from .schema import ( # noqa Config, SQSReceiver, LogReceiver, Receiver )
91
33
# Solution by : Tameem Alaa El-Deen Sayed n = int(input()) c= 0 while n >= 1 : if n % 2 == 0 : n = n /2 else: n = n -1 n = n / 2 c = c + 1 print (c)
193
91
import plotly.express as px import plotly.graph_objects as go import pandas as pd import json import os from vaccine_dataprep_Swedentots import ( df_vacc_lan, # data on 1st 2 doses third_vacc_dose_lan, # data on 3rd dose # df_vacc_ålders_lan, # a switch to age data for 1st and second doses? SCB_popu...
11,877
4,936
# Copyright (c) 2017-2021, Lawrence Livermore National Security, LLC and # other Shroud Project Developers. # See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (BSD-3-Clause) # ######################################################################## """ Generate a module for classes using PyBi...
1,520
495
""" File: blur.py ------------------------------- This file shows the original image(smiley-face.png) first, and then its blurred image. The blur algorithm uses the average RGB values of a pixel's nearest neighbors. """ from simpleimage import SimpleImage BLURRED_SCALE = 9 def blur(old_img): """ :param old_...
9,995
3,894
# -*- coding: utf-8 -*- ''' Docer ~~~~~~ A document viewing platform. :copyright: (c) 2015 by Docer.Org. :license: MIT, see LICENSE for more details. ''' from flask import Flask from flask.ext.mongoengine import MongoEngine from app.frontend import frontend as frontend_blueprint from app.backend import backend a...
650
225
from typing import List from sys import argv from tqdm import tqdm from time import sleep from random import uniform from bs4 import BeautifulSoup import requests from get_pages_urls import get_list_pages from get_urls import get_urls_per_page from write_poem import write_poem def main(root_url: str, poet_...
953
349
# SPDX-FileCopyrightText: NOI Techpark <info@noi.bz.it> # # SPDX-License-Identifier: Apache-2.0 import logging from typing import List, Dict, TypeVar, Optional from copy import deepcopy from deepdiff import DeepDiff from .base import BaseModel, DictModel, ModelError from aliens4friends.commons.utils import sha1sum_...
12,597
5,079
# przykład wykorzystania biblioteki requests import requests params = { 'format': 'j1', } api_result = requests.get('https://wttr.in/Varsavia', params) api_response = api_result.json() for elem in api_response: print(f"Klucz: {elem} ma wartość {api_response[elem]}")
276
100
class Libro(): #Creamos el constructor def __init__(self, titulo,autor,editorial,precioBase, genero, nPaginas): self.titulo = titulo self.autor= autor self.editorial= editorial self.precioBase= precioBase self.genero= genero self.nPaginas= nPaginas #Metodos...
1,327
464
import os import sys import argparse import os import re import shlex import subprocess import signal import gc import param is_pypy = '__pypy__' in sys.builtin_module_names def PypyGCCollect(signum, frame): gc.collect() signal.alarm(60) cigarRe = r"(\d+)([MIDNSHP=X])" base2num = dict(zip("ACGT", (0,1,2,3)))...
12,938
4,193
#!/usr/bin/env python """ MultiQC_NGI is a plugin for MultiQC, providing additional tools which are specific to the National Genomics Infrastructure at the Science for Life Laboratory in Stockholm, Sweden. For more information about NGI, see http://www.scilifelab.se/platforms/ngi/ For more information about MultiQC, s...
2,405
783
import re import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart domain = "127.0.0.1" def send_email(to, subject, text): fromaddr = "homeworksmailbot@gmail.com" toaddr = to msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject']...
3,106
1,058
def sumall(*args): count = 0 for arg in args: count += arg return count print(sumall(1,2,3,4,4,5,6,7)) print(sumall(1,2,34)) numbers = 1,2,3,4,5,6,6,7,8,9 print(sumall(*numbers))
200
97
class Bet(): def __init__(self, amount, outcome, player=None): self.amount = amount self.outcome = outcome self.player = player def setOutcome(self, outcome): """ Sets the Outcome for this bet. This has the effect of moving the bet to another Outcom...
2,369
684
from django.contrib import admin from .models import Color, Pet, Publication class PublicationAdmin(admin.ModelAdmin): fields = ['title', 'description', 'pet', 'member'] search_fields = ['title', 'breed'] list_display = ('title', 'description', 'pet', 'date') list_filter = ['date'] class PetAdmin(...
866
275
from copy import deepcopy from bs4 import BeautifulSoup from .abstract_extractor import AbstractExtractor from ..article_candidate import ArticleCandidate class ReadabilityExtractor(AbstractExtractor): """This class implements Readability as an article extractor. Readability is a subclass of Extractors and ...
1,781
495
# -*- coding: utf-8 -*- from hearthstone.entities import Entity from entity.spell_entity import SpellEntity class LETL_306(SpellEntity): """ 冰风暴5 随机对3个敌方佣兵造成$6点伤害,并使其下回合的速度值减慢(2)点。0随机对3个敌方佣兵造成$7点伤害,并使其下回合的速度值减慢(2)点。0随机对3个敌方佣兵造成$8点伤害,并使其下回合的速度值减慢(2)点。0随机对3个敌方佣兵造成$9点伤害,并使其下回合的速度值减慢(2)点。0随机对3个敌方佣兵造成...
853
484
def findDecision(obj): #obj[0]: Passanger, obj[1]: Time, obj[2]: Coupon, obj[3]: Gender, obj[4]: Age, obj[5]: Education, obj[6]: Occupation, obj[7]: Bar, obj[8]: Coffeehouse, obj[9]: Restaurant20to50, obj[10]: Direction_same, obj[11]: Distance # {"feature": "Restaurant20to50", "instances": 51, "metric_value": 0.9526, ...
2,546
1,334
# -*- coding: utf-8 -*- __description__ = 'Python driver and logging app ' +\ 'for Gravity infrared CO2 sensor' __long_description__ = 'Python driver and logging app ' +\ 'for Gravity infrared CO2 sensor' __author__ = 'osoken' __email__ = 'osoken.devel@outlook.jp' __version__ = '0.0.0' __package_name__ = '...
346
128
import os import time from src.models.model1 import CBD from src.utils.train_utils import TrainGenerator from tensorflow.keras import losses, optimizers, callbacks train_data = TrainGenerator('train') val_data = TrainGenerator('val') epochs = 10 model_dir = 'models/' log_dir = 'logs/' cbd = CBD('models/', 'logs/'...
1,414
518
import torch.nn as nn from models.PSim_alexnet import PSim_Alexnet import torch from utils import utils class PSimNet(nn.Module): """Pre-trained network with all channels equally weighted by default (cosine similarity)""" def __init__(self, device=torch.device("cuda:0")): super(PSimNet, self).__init_...
1,142
369
from . import conf_reader
26
8
n = float(raw_input()) v = map(int, raw_input().strip().split()) pos = float(len(filter(lambda x: x > 0, v))) / n neg = float(len(filter(lambda x: x < 0, v))) /n zer = float(len(filter(lambda x: x == 0, v))) / n print "%.3f" % pos print "%.3f" % neg print "%.3f" % zer
271
118
import os from dotenv import load_dotenv load_dotenv() basedir = os.path.abspath(os.path.dirname(__file__)) class Config: DEBUG = False TESTING = False UPLOAD_FOLDER = f'{basedir}/uploads' class DevConfig(Config): DEBUG = True class TestConfig(Config): TESTING = True
297
109
import requests import json from ..Config.config_handler import read_config class ProcessBusDelays: def __init__(self): self.config_vals = read_config("Bus_API") # Get the live data of Buses(Arrival Time, Departure Time, Delay) from API and returns. def get_data_from_bus_api(self): ur...
2,219
625
# -* coding: utf-8 -* """ This module generate the Julia interface declaration for the functions it finds in a C header. It only handle edge cases for the chemfiles.h header. """ from generate.julia.constants import BEGINING from generate.julia.convert import type_to_julia from generate import CHFL_TYPES TYPE_TEMPLA...
3,576
1,260
from tensorflow.python.framework import ops from tensorflow.python.ops import math_ops from .utils import get_xmodule xmodule = get_xmodule() xgemm = xmodule.xgemm @ops.RegisterGradient("XGEMM") def _xgemm_grad(op, grad): """ Gradient computation for the XGEMM :param op: XGEMM operation that is differen...
648
224
# 第5章: 係り受け解析 import re class Morph: def __init__(self, surface, base, pos, pos1): self.surface = surface self.base = base self.pos = pos self.pos1 = pos1 def print(self): print([self.surface, self.base, self.pos, self.pos1]) def analyze(): article = [] sentenc...
1,004
311
import os import shutil import unittest from tools.Utils import root_path, output_fields, create_folder_if_not_exists, results_folder class TestUtils(unittest.TestCase): def test_output_fields(self): output_fields_needed = ['Date', 'Time', 'Result', 'Phase'] self.assertEqual(output_fields_needed...
1,096
338
#! /usr/bin/python import hashlib, getpass import sys if len(sys.argv) > 1 and sys.argv[1] == '-s': sha = True else: sha = False while True: try: passhash = hashlib.sha1(getpass.getpass()).hexdigest().upper() if sha: print passhash except EOFError: print br...
650
202
################################################################################ """ `electricpy` Package - `conversions` Module. >>> from electricpy import conversions Filled with simple conversion functions to help manage unit conversions and the like, this module is very helpful to electrical engineers. Built to ...
14,728
4,881
import html from .models import Post, Session TEMPLATE_BASE = '''<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>noname</title> <link rel="stylesheet" href="/static/app.css"> </head> <body> %s </body> </html> ''' TEMPLATE_FORM = ''' <form action="...
1,713
568
""" https://github.com/SACGF/variantgrid/issues/1601 Need to trigger reloads of bad metrics, so we die properly """ import logging from django.core.management.base import BaseCommand from seqauto.models import IlluminaFlowcellQC from snpdb.models import DataState class Command(BaseCommand): def hand...
761
258
# Generated by Django 2.0.2 on 2018-03-08 12:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('base', '0004_event_group'), ('ssig_site_auth', '0002_user_interest_groups'), ] operations = [ migrations.AddField( model...
446
156