text
string
size
int64
token_count
int64
# For Time Logging import time from contextlib import contextmanager import logging @contextmanager # Timing Function def time_usage(name=""): """ log the time usage in a code block """ # print ("In time_usage runID = {}".format(runID)) start = time.time() yield end = time.time() elaps...
436
139
import os import shutil path = './ALL/' outpath = "./rename/" outb = "./b/" outc = "./c/" for f in os.listdir(path): print(f) name,ext = os.path.splitext(f) a,ext2 = name.split('_') if ext2.endswith('b'): print(outb+f) shutil.copy(path+f,outb+f) elif ext2.endswith('c'): prin...
416
182
import socket import threading import concurrent.futures from colorama import Fore, Style def port_scanner(): print_lock = threading.Lock() print('') ip = input(Fore.CYAN + "[PORT_SCANNER]" + Style.RESET_ALL + "[>] Target: ") port_range = input(Fore.CYAN + "[PORT_SCANNER]" + Style.RESET_ALL + "[>] Sca...
970
334
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'untitled.ui' # # Created by: PyQt5 UI code generator 5.12.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWi...
3,720
1,314
#!/usr/bin/env python # coding=utf-8 from pyecharts.chart import Chart from pyecharts.option import get_all_options class Scatter(Chart): """ <<< 散点图 >>> 直角坐标系上的散点图可以用来展现数据的 x,y 之间的关系,如果数据项有多个维度, 可以用颜色来表现,利用 geo 组件。 """ def __init__(self, title="", subtitle="", **kwargs): super(Scatt...
2,056
848
import json class AliceRequest(object): def __init__(self, request_dict): self._request_dict = request_dict @property def version(self): return self._request_dict['version'] @property def session(self): return self._request_dict['session'] @property def user_id(s...
1,799
525
import yfinance as yf import pandas as pd import Utils from Utils import scrape_utils def qtrlabels(tick,date,comp='plain'): stock = yf.Ticker(tick.upper()) hist = stock.history(interval="1d",start=scrape_utils.dashdate(scrape_utils.fixdate(date)),end=scrape_utils.qenddate(date)) stkchg = hist.iloc[-1].Close/hi...
869
334
# This file is part of the pyMOR project (http://www.pymor.org). # Copyright 2013-2016 pyMOR developers and contributors. All rights reserved. # License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) import numpy as np from pymor.core.interfaces import ImmutableInterface from pymor.core.logger im...
8,014
2,574
# -*- coding: utf-8 -*- # Copyright (c) 2019, Frappe Technologies and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest from frappe.utils import get_datetime from frappe.core.doctype.scheduled_job_type.scheduled_job_type import sync_jobs class TestScheduledJobType(u...
3,050
1,374
# menu_text.py # # simple python menu # https://stackoverflow.com/questions/19964603/creating-a-menu-in-python # city_menu = { '1': 'Chicago', '2': 'New York', '3': 'Washington', 'x': 'Exit'} month_menu = {'0': 'All', '1': 'January', '2': 'February...
1,750
531
from src.books.models import Book from src.books.schema import BookOut from ninja import Router router = Router() @router.get("/", response=list[BookOut]) def get_books(request): return Book.objects.all()
213
68
from getratings.models.ratings import Ratings class NA_Khazix_Sup_Aatrox(Ratings): pass class NA_Khazix_Sup_Ahri(Ratings): pass class NA_Khazix_Sup_Akali(Ratings): pass class NA_Khazix_Sup_Alistar(Ratings): pass class NA_Khazix_Sup_Amumu(Ratings): pass class NA_Khazix_Sup_Anivia(Ratings): ...
6,545
3,733
# generated by datamodel-codegen: # filename: Organization.schema.json # timestamp: 1985-10-26T08:21:00+00:00 from __future__ import annotations from pydantic import BaseModel, Field class Schema(BaseModel): __root__: str = Field(..., description='Identifier string of this object.')
297
105
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from tablo import GEOM_FIELD_NAME, WEB_MERCATOR_SRID forward_sql = """ DO $$ DECLARE table_name name; BEGIN FOR table_name IN SELECT tablo_featureservicelayer.table FROM tablo_...
776
279
import torch import torch.nn as nn from torch.autograd import Variable import torch.functional as F from torch.nn.init import xavier_normal_ import os import sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) import numpy as np from numpy.random import RandomState f...
23,755
8,482
# -*- coding: utf-8 -*- import pytest from six import iteritems def test_security_definition_property_extraction(security_dict, security_spec): security_definitions = security_dict['securityDefinitions'] for security_name, security_spec_dict in iteritems(security_definitions): security_object = securi...
1,265
384
def willYou(young, beautiful, loved): return loved != (young and beautiful)
79
23
import json from typing import Union, Optional, Tuple, List import numpy as np from sklearn.feature_extraction import DictVectorizer from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer, TfidfTransformer from sklearn.model_selection import train_test_split from sklearn.preprocessing import Stan...
3,555
1,109
#!/usr/bin/python #Sorts based on top 50 CMetric, all callPaths - CMetric #, all call paths - call path count and all samples from __future__ import print_function from bcc import BPF, PerfType, PerfSWConfig from bcc import BPF import sys import ctypes as ct # For mapping the 'C' structure to Python import argparse #...
31,868
10,326
# -*- coding: utf-8 -*- import random import numpy as np import scipy import pandas as pd import pandas import numpy import json def resizeFeature(inputData,newSize): # inputX: (temporal_length,feature_dimension) # originalSize=len(inputData) #print originalSize if originalSize==1: inputData=...
4,484
1,666
from cloudevents.sdk.event import v03 import json from ferris_cli.ferris_cli import CloudEventsAPI import uuid import os import consul from ferris_cli.ferris_cli import ApplicationConfigurator from datetime import datetime def send_direct_loading_event(hdfs_path): data = {"file_location": hdfs_path } event =...
1,622
567
''' GERADOR DE RELATÓRIO DOS SERVIDORES (DASHBOARD SERVIDORES) ''' from SQL import sqlpandas from MENSAGEM import mensagemInformacao, mensagemErro from AUXILIAR import salvarPandas def dashboardServidores(): ''' FUNÇÃO PARA CRIAR OS DASHDOARD ENTRA ENTRA NULL SAI PLANILHA COM OS DADOS...
2,355
963
from pyroombaadapter.pyroombaadapter import PyRoombaAdapter
60
18
from __future__ import print_function from __future__ import division import torch import torch.nn as nn from torch.nn import Parameter import math from torchkit.util.utils import l2_norm from torchkit.head.localfc.common import calc_logits class CurricularFace(nn.Module): """ Implement of CurricularFace (https:/...
2,189
709
from core.views import BaseViewSet from .models import Cash from .serializers import CashSerializer class CashViewSet(BaseViewSet): """ - Vybirame jen typ 4 coz jsou platby z Banky - Setridime nenovejsim datem na zacatek """ queryset = Cash.objects.all().filter(type=4).order_by('-time') serial...
390
131
import atexit import sqlite3 import traceback ################# import sys sys.path.append('/app') from helper import * settings_dict = load_yaml_dict(read_file("/Settings.yaml")) conn = sqlite3.connect(f"/database/{settings_dict['db_name']}", isolation_level=None, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_C...
3,730
953
#!/usr/bin/env python3 """ example.py Example of using pypahdb to decompose an astronomical PAH spectrum. """ import pkg_resources from pypahdb.decomposer import Decomposer from pypahdb.observation import Observation if __name__ == '__main__': # The sample data (IPAC table). file_path = 'resources/sample_...
809
297
""" Mapping registries for Zigbee Home Automation. For more details about this component, please refer to the documentation at https://home-assistant.io/components/zha/ """ from .const import ( DEVICE_CLASS, SINGLE_INPUT_CLUSTER_DEVICE_CLASS, SINGLE_OUTPUT_CLUSTER_DEVICE_CLASS, COMPONENT_CLUSTERS, HUMIDITY, ...
10,448
3,778
import random import pickle import cv2 import numpy as np import paddle import paddleseg.transforms as T from .points_sampler import MultiPointSampler def get_unique_labels(x, exclude_zero=False): obj_sizes = np.bincount(x.flatten()) labels = np.nonzero(obj_sizes)[0].tolist() if exclude_zero: la...
3,292
1,021
#!/usr/bin/env python3 """ Created on Wed Feb 17 08:32:55 2021 Deface anatomical image(s) @author: dlevitas """ import os, sys import nibabel as nib import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.style.use('dark_background') from math import floor os.environ[ 'MPLCONFIGDIR' ] = '/tmp...
1,008
403
"""Infrastructure for registering and firing callbacks on application events. Unlike :mod:`IPython.core.hooks`, which lets end users set single functions to be called at specific times, or a collection of alternative methods to try, callbacks are designed to be used by extension authors. A number of callbacks can be r...
4,511
1,163
from app import app from services import TopicServices from flask import jsonify, request @app.route('/topic/terms', methods=['GET']) def getTerms(): numOfTerms = request.args.get("numOfTerms") results = TopicServices.getTerms(numOfTerms) return jsonify({ 'results': results })
290
89
#!/usr/bin/env python3 # Copyright (c) 2021 The Bitcoin developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the -uaclientname and -uaclientversion option.""" import re from test_framework.test_framework import Bitc...
4,602
1,438
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import annotations import unittest import numpy as np import numpy.testing as npt import pandas as pd from riip.material import RiiMaterial class KnownValues(unittest.TestCase): known_values = [ (1, [0.0 for _ in range(17)], 1.0, 1.0), ...
5,619
2,325
# Copyright (c) 2017 Fujitsu Limited # 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 requi...
3,832
1,224
""" Unit Tests for Service Patch """ # Copyright (c) 2021 ipyradiant contributors. # Distributed under the terms of the Modified BSD License. import ipyradiant import rdflib LINKEDDATA_QUERY = """ SELECT DISTINCT ?s ?p ?o WHERE { SERVICE <http://linkeddata.uriburner.com/sparql> { ...
942
338
import subprocess from collections import OrderedDict import pytest from connect.cli.plugins.project import git @pytest.mark.parametrize( ('str', 'result'), ( ('0.0.0', True), ('0.0.4', True), ('1.0.0', True), ('1.2.0', True), ('1.2.3', True), ('0.0', True), ...
6,552
2,600
# Created by Kelvin_Clark on 3/5/2022, 6:37 PM from typing import Optional from src.models.entities.user import User from src import database as db class UserDao: @staticmethod def get_user_by_email(email: str) -> Optional[User]: return User.query.filter_by(email=email).first() @staticmethod ...
737
235
# Problem ID: dmpg18g1 # By Alexander Cai 2019-12-09 # Solved import sys FILLED = -1 EMPTY = 0 data = sys.stdin.read().split('\n') n, k = map(int, data[0].split()) chairs = [FILLED for _ in range(n)] for j in map(int, data[1].split()): chairs[j-1] = EMPTY for i, j in enumerate(map(int, data[2].split())): i...
839
357
# -*- coding: utf-8 -*- import unittest import trafaret as t from collections import Mapping as AbcMapping from trafaret import extract_error, ignore, DataError from trafaret.extras import KeysSubset class TestAnyTrafaret(unittest.TestCase): def test_any(self): self.assertEqual( (t.Any() >> ig...
25,884
9,514
# coding: utf-8 # This file is part of libdesktop # The MIT License (MIT) # # Copyright (c) 2016 Bharadwaj Raju # # 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, includ...
6,107
2,169
import os import cv2 import keras import numpy as np import albumentations as A import tensorflow as tf from keras import backend as K def jaccard_distance(y_true, y_pred, smooth=100): intersection = K.sum(K.abs(y_true * y_pred), axis=-1) sum_ = K.sum(K.abs(y_true) + K.abs(y_pred), axis=-1) jac = (intersec...
2,887
1,046
#!/usr/bin/env python # # A minimal Python language binding for the OpsRamp REST API. # # monitoring.py # Classes related to monitoring templates and similar things. # # (c) Copyright 2019-2021 Hewlett Packard Enterprise Development LP # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not us...
1,119
339
from client import exceptions as ex from client.sources import doctest from client.sources.doctest import models import mock import unittest import os.path class LoadTest(unittest.TestCase): VALID_FILE = 'valid.py' VALID_MODULE = os.path.splitext(VALID_FILE)[0] INVALID_FILE = 'invalid.ext' FUNCTION = ...
5,045
1,584
#!/usr/bin/python # # Copyright (c) 2019 Zim Kalinowski, (@zikalino) # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
19,585
4,965
from rdflib import Graph import json import glob books = {} rdf_files = glob.glob("gutindex/cache/epub/*/*.rdf") i = 1 for rdf_file in rdf_files: g = Graph() g.parse(rdf_file) for s,p,o in g: if 'title' in p: books[str(o)] = str(s) print(i, str(o)) i+=1 with open("g...
382
160
## _____ _____ ## | __ \| __ \ AUTHOR: Pedro Rivero ## | |__) | |__) | --------------------------------- ## | ___/| _ / DATE: May 18, 2021 ## | | | | \ \ --------------------------------- ## |_| |_| \_\ https://github.com/pedrorrivero ## ## Copyright 2021 Pedro Rivero ## ## Licen...
3,188
870
""" Log multiple instances to same file. """ def log(msg): f = open('error.log', 'a') f.write(msg+'\n') f.close() def clear(): f = open('error.log', 'w') f.write('') f.close()
203
85
from Stream.Stream import Stream class TransportStream(Stream): """ 传输层流对象 代表一个传输层流,包含这个流中的所有数据包以及流的基本信息 protocol: 传输层的具体协议,UDP或TCP side_a: A端IP地址(流的第一条报文的src) side_b: B端IP地址(流的第一条报文的dst) port_a: A端端口号 port_b: B端端口号 packets:流的报文列表 stream_id: wireshark内的stream index direct: ...
3,959
1,290
""" This tool compares measured data (observed) with model outputs (predicted), used in procedures of calibration and validation """ from __future__ import division from __future__ import print_function import os from math import sqrt import pandas as pd from sklearn.metrics import mean_squared_error as calc_mean_squar...
9,775
3,011
try: from public_config import * except ImportError: pass HOST = '0.0.0.0' PORT = 9038 SERVICE_NAME = 'jobs' SERVER_ENV = 'prod' SQLALCHEMY_POOL_SIZE = 10 SQLALCHEMY_POOL_RECYCLE = 3600 JOBS = [ { # 任务 信用积分每日检查, 每周一到每周五 早上 10:30 分运行 # 检查每个设备的借用日期是否超时 :发送提醒邮件,扣除信用分 1分 'id': 'credit-check...
1,337
732
import pyautogui, pygetwindow, time screen = pygetwindow.getWindowsWithTitle('Old School RuneScape')[0] centerRatio = (2.8,2.8) def move(direction,spaces): vel = [0,0] if direction == "up": vel[1] = 0.32; if direction == "down": vel[1] = -0.32; if direction == "left": vel[0] = 0.3; if direct...
918
368
#!/usr/bin/python ''' Produces POSIX commands to setup the environment variables for Geant4. Required command line arguments: 1: Location of geant4.sh script. 2: Version of Geant4. ''' import os import sys import re import subprocess as subp from codecs import encode,decode geant4_sh, geant4_version = sys.argv[1:] ...
2,251
793
#! /usr/bin/env python from __future__ import absolute_import import os import sys PROJECT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) sys.path.append(PROJECT_DIR) sys.path.append(os.path.abspath(os.path.join(PROJECT_DIR, "app"))) if __name__ == "__main__": from app.main import Mai...
454
178
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # -------------------------------------------------------------------------------------------- # - Generated by tools/entrypoint_co...
4,906
1,301
# # @lc app=leetcode.cn id=17 lang=python3 # # [17] 电话号码的字母组合 # # https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/description/ # # algorithms # Medium (47.70%) # Total Accepted: 18K # Total Submissions: 37.5K # Testcase Example: '"23"' # # 给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。 # # 给出数字到字母的映射如下(与...
2,019
965
import random import argparse from ast import Global from dis import dis from glob import glob from itertools import count from math import dist from logger import * import json import gym from matplotlib.pyplot import axis import scipy.optimize import pdb import torch from torch.autograd import Variable from jax_rl....
15,031
5,780
#!/usr/bin/env python # # tpycl.py is the python support code to allow calling of python-wrapped # vtk code from tcl scripts # # the main class is tpycl, and scripts can # import sys import os import Tkinter from __main__ import slicer import qt class tpycl(object): def __init__(self): self.verbose = False ...
7,500
2,461
hex_strings = [ "FF 81 BD A5 A5 BD 81 FF", "AA 55 AA 55 AA 55 AA 55", "3E 7F FC F8 F8 FC 7F 3E", "93 93 93 F3 F3 93 93 93", ] def hex_data_to_image(hex_data): for hex_pair in hex_data: for divisor in reversed(range(len(hex_data))): print("X" if (int(hex_pair, 16) >> divisor & 1) == 1 else " ", end=...
473
231
import click from kryptos.scripts import build_strategy, stress_worker, kill_strat @click.group(name="strat") def cli(): pass cli.add_command(build_strategy.run, "build") cli.add_command(stress_worker.run, "stress") cli.add_command(kill_strat.run, "kill")
264
99
#!/usr/bin/env python3 """Radio scheduling program. Usage: album_times.py [--host=HOST] PORT Options: --host=HOST Hostname of MPD [default: localhost] -h --help Show this text Prints out the last scheduling time of every album. """ from datetime import datetime from docopt import docopt from mpd import M...
2,334
733
#!/usr/bin/env python3 # # Copyright (c) 2020 Raspberry Pi (Trading) Ltd. # # SPDX-License-Identifier: BSD-3-Clause # # sudo pip3 install pyusb import usb.core import usb.util # find our device dev = usb.core.find(idVendor=0x0000, idProduct=0x0001) # was it found? if dev is None: raise ValueE...
1,116
437
import ipywidgets as ipw import traitlets from IPython.display import clear_output class SummaryWidget(ipw.VBox): """output the convergence summary""" selected_pseudos = traitlets.Dict(allow_none=True) def __init__(self): # Delta mesure self.output = ipw.Output() super().__init_...
1,426
456
# -*- coding: utf-8 -*- # # This file is part of the SKA PST LMC project # # Distributed under the terms of the BSD 3-clause new license. # See LICENSE for more info. """This module implements the PstManagement device.""" from __future__ import annotations from typing import Optional from ska_tango_base.csp.control...
2,846
829
import sys,os import argparse as arg import nmap import urllib2 parser = arg.ArgumentParser() parser.add_argument("-a", "--address", help="IP address", required=True) parser.add_argument("-i", "--interface", help="Interface", required=True) argument = parser.parse_args() def scan_(ip): dict_ = [] scan = nmap.PortS...
1,469
606
import argparse from cartografo import DEFAULT_OBJECT, DEFAULT_TARGET def __get_argparser(): __parser.add_argument('--k8s-object', help='Output Kubernetes objet: secrets or configmap') __parser.add_argument('--target', help='Target file. If it exists, it will be modified') __parser.add_argument('files_fo...
713
213
L = ['michael', 'sarah', 'tracy', 'bob', 'jack'] # 取前N个元素 r = [] n = 3 for i in range(n): r.append(L[i]) print(r) # python提供slice操作符简化. m = 0 print(L[m:n], L[:n], L[-n:-1]) L = list(range(100)) print(L[:10], '\r', L[-10:], '\r', L[10:20], '\r', L[:10:2], '\r', L[::5]) print((0, 1, 2, 3, 4, 5)[:3]) print('ABCDEFG'[:3...
343
211
''' Created on Feb 17, 2014 @author: magus0219 ''' import unittest,datetime from util.dateutil import DateUtil from core.timematcher import TimeMatcher from core.timepattern import TimePattern class TimeMatcherTest(unittest.TestCase): @unittest.expectedFailure def testUnvaidValueNotInt(self): TimeMat...
3,330
1,076
from django.conf.urls import url from api import views urlpatterns = [ url(r'^pets/$', views.ListPets.as_view(), name='list_pets'), url(r'^cities/$', views.CityList.as_view(), name='city-list'), url(r'^states/$', views.StateList.as_view(), name='state-list'), ]
276
104
#!/usr/bin/env python # This is not an officially supported Google product, though support # will be provided on a best-effort basis. # Copyright 2018 Google LLC # Licensed under the Apache License, Version 2.0 (the "License"); you # may not use this file except in compliance with the License. # You may obtain a co...
1,503
516
#!/usr/bin/env python # -*- coding: UTF-8 -*- """================================================= @Author :蒋虎成 @Date :2021/9/22 17:04 @Desc :主接口 ==================================================""" from colors import ColorMultiImage import settings from model import training import csv if __name__ == '__main__': ...
1,131
403
#! /usr/bin/env python """ usage: demoselsim.py outfilename popn h pct """ import numpy import sys def pnext(AC, N, Nout, h, s): AC = float(AC); N = float(N); h = float(h); s = float(s) p = AC/(2*N) w11 = 1+s; w12 = 1+h*s; w22 = 1 wbar = ((p**2) * w11) + (2*p*(1-p)*w12) + (((1-p)**2) * w22) pdet = p*(p*w11 + (1...
3,345
1,756
import math import torch import numpy as np import torch.nn as nn class PositionalEncoding(nn.Module): def __init__(self, d_model, seq_len) -> None: super(PositionalEncoding, self).__init__() self.d_model = d_model pe = torch.zeros(seq_len, d_model) for pos in range(seq_len): ...
4,692
1,682
""" Common CLI options for invoke command """ import click from samcli.commands._utils.options import template_click_option, docker_click_options, parameter_override_click_option try: from pathlib import Path except ImportError: from pathlib2 import Path def get_application_dir(): """ Returns -...
4,350
1,101
import threading def merge_sort(arr): def _merge(arr1, arr2): i, j = 0, 0 l1, l2 = len(arr1), len(arr2) arr_sorted = [0] * (l1 + l2) idx = 0 while i < l1 and j < l2: if arr1[i] < arr2[j]: arr_sorted[idx] = arr1[i] i += 1 ...
3,083
1,066
""" Deploy NodeJs application https://github.com/react-boilerplate/react-boilerplate """ from py_mina import * from py_mina.subtasks import git_clone, create_shared_paths, link_shared_paths, rollback_release # Settings - shared set('verbose', True) set('shared_dirs', ['node_modules', 'tmp']) set('shared_files', ...
830
308
import abc import json from typing import Any, Dict, IO, Iterable, List, Optional, Union import altair as alt from altair_saver.types import Mimebundle, MimebundleContent, JSONDict from altair_saver._utils import ( extract_format, fmt_to_mimetype, infer_mode_from_spec, maybe_open, ) class Saver(meta...
4,653
1,349
# Import our project so that our custom logging gets setup early enough from __future__ import annotations import mcookbook # noqa: F401 # pylint: disable=unused-import
172
50
from .exceptions import AccessDenied class AccessControlMixin(object): def user_can_edit(self, user): return (user.is_superuser or self.user == user) def check_write_privileges(self, user): if not self.user_can_edit(user): raise AccessDenied() def check_read_privileges(self, ...
401
126
import os from bs4 import BeautifulSoup import html2text import pandas data_dir = 'co2-coalition' data_text_dir = os.path.join(data_dir, 'text') data_file_name = 'co2-coalition.csv' def make_file_name(index): return f'{index:02d}' def save_text(data_dir, file_path, content): f = open(os.path.join(data_dir, file...
1,976
779
import random def rand_proc(num_proc): procesos = [] for j in range(0,num_proc): t_0 = random.randint(1,10+1) t =random.randint(1,10+1) procesos.append([j,t_0,t]) return procesos
218
90
"""Test functions for FOOOF analysis.""" import numpy as np from fooof.analysis import * ################################################################################################### ################################################################################################### def test_get_band_peak_fm(t...
1,753
775
import math # The code is based on from http://www.cs.cmu.edu/~ckingsf/class/02713-s13/src/mst.py # Heap item class HeapItem(object): """Represents an item in the heap""" def __init__(self, key, value): self.key = key self.pos = None self.value = value # d-ary Heap cl...
2,677
892
#!/usr/bin/env python # coding: utf-8 # In[5]: import cv2 import numpy as np imagen = cv2.imread('wheel.png') gray = cv2.cvtColor(imagen,cv2.COLOR_BGR2GRAY) _,th = cv2.threshold(gray,100,255,cv2.THRESH_BINARY) #Para versiones OpenCV3: img1,contornos1,hierarchy1 = cv2.findContours(th, cv2.RETR_EXTERNAL,cv2.CHAIN_AP...
679
344
# -*- coding: utf-8 -*- ############################################################# # Copyright (c) 2020-2021 Maurice Karrenbrock # # # # This software is open-source and is distributed under the # # BSD 3-Clause "New" or "Revised" License ...
2,014
623
import torch import torch.nn as nn import torch.nn.functional as F import os import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(BASE_DIR) import pointnet2_utils import pytorch_utils as pt_utils from typing import List class PointSpatioTemporalCorrelation(nn.Module): def __init__( ...
8,622
3,199
from django import forms class URLForm(forms.Form): siteUrl = forms.CharField(label='Website Address', max_length=100,required=True) ''' javascriptChoices = ((2,"Keep Javascript",),(1,"Remove Some Javascript"),(0,"Remove All Javascript")) keepJavascript = forms.ChoiceField(choices=javascriptChoices,label="...
347
98
from flexmeasures.app import create as create_app application = create_app()
78
22
from ctypes import Structure, Union, c_int, c_byte, c_char_p # Inner union class MBusAddressInternal(Union): _fields_ = [ ('primary', c_int), ('secondary', c_char_p), ] class MBusAddress(Structure): _fields_ = [ ('is_primary', c_byte), ('_address', ...
839
263
# -*- coding: utf-8 -*- # Copy this file and renamed it settings.py and change the values for your own project # The csv file containing the information about the member. # There is three columns: The name, the email and the member type: 0 regular, 1 life time CSV_FILE = "path to csv file" # The svg file for regular...
1,162
364
"""the names of companies which filed fields with certain words in them""" from df_wrappers import facts_stringquery def main(): """example code lives in one function""" # this one is easier in the script language query_string = """ filingsource:"Korea FSS" AND fieldname:(hedge OR (foreign AND ex...
633
192
DEBUG = False from typing import List, Tuple class LRU: _values:List _lastIndex:int def __init__(self, ways): #values = 3,2,1,0, so the cache will use 0 as the first self._values = list(range(ways-1,-1,-1)) self._lastIndex = ways -1 def getLeastRecentlyUsed(self): ret...
2,413
778
""" db_triggers.py ~~~~~~~~~~~~~~ :aciklama: Veritabanina veri girisi ve gerekli triggerlar icin :yazar: github.com/serong """ import sqlite3 import db as saydb class SayisalDBT(object): def __init__(self, week, the_date, numbers): self.db_name = "sayisal.db" self.weeks...
4,015
1,231
import contextlib import os import pickle import numpy as np from itertools import product, starmap import multiprocessing import tqdm import sys if sys.platform.startswith("linux"): is_linux = True import tempfile else: is_linux = False import mmap # import pyina.launchers # from pyina.ez_map import e...
17,088
5,350
from .result import Result import numpy as np import pandas as pd class DiffAbunRes(Result): def __init__(self, otu_table, transform_pipe=None, percent=False, **kwargs): super().__init__() self.pre_vs_skin = diff_rel_abun(otu_table, compare='pre_vs_skin', transform_pipe=transform_pipe, ...
4,706
1,521
i = 0 while (i<119): print(i) i+=10
49
31
import numpy as np import unittest import coremltools.models.datatypes as datatypes from coremltools.models import neural_network as neural_network from coremltools.models import MLModel from coremltools.models.neural_network.printer import print_network_spec from coremltools.converters.nnssa.coreml.graph_pass.mlmodel_...
15,783
4,828
# Generated by Django 2.1.7 on 2019-04-03 11:56 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('accounting_tech', '0017_auto_20190403_1434'), ] operations = [ migrations.AlterField( model_nam...
575
208
from puretabix import get_bgzip_lines_parallel class TestBlockGZip: def test_get_lines(self, vcf_filename, vcf_gz): lines = tuple(sorted(map(bytes.decode, vcf_gz.readlines()))) lines_parsed = tuple(sorted(get_bgzip_lines_parallel(vcf_filename))) for line_in, line_out in zip(lines, lines_p...
500
170
from setuptools import find_packages, setup setup( name="datapool_client", version="1.0", description="Designed to access the datapool software developed by ETH Zurich - SIS and Eawag. " "Find out more under https://datapool.readthedocs.io/en/latest/.", author="Christian Foerster", ...
887
289