text
string
size
int64
token_count
int64
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
4,049
1,181
from behave import given @given("we have processed PDS data") def step_impl(context): pass
97
31
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals import sys import argparse import os import re import sqlite3 import requests import bs4 from termcolor import colored # Python2 compatibility if sys.version_info[0] == 2: reload(sys) sys.setdefaultencoding('utf-8') # Default data...
19,208
6,343
def groups_for_user(environ, user): if user == 'feng': return ['secret-agents'] return ['']
108
36
#!/usr/bin/env python # -*- coding: utf-8 -*- """Title: GCN models Description: The original Graph convolutional network model and GCN layer. Refer to: https://arxiv.org/abs/1609.02907 """ # ======================================= # @author Zhibin.Lu # @email zhibin.lu@umontreal.ca # ==============================...
4,925
1,538
SOLIDITY_TO_BQ_TYPES = { 'address': 'STRING', } table_description = '' def abi_to_table_definitions_for_solana( abi, dataset_name, contract_name, contract_address=None, include_functions=False ): result = {} for a in abi.get('events') if abi.get('events') else []: ...
2,513
758
#Method-1 guess the number game import random number = random.randint(1,10) guess = 0 count = 0 print("You can exit the game anytime. Just enter 'exit'.") while guess != number and guess != "exit": guess = input("Guess a number between 1 to 10 :- ") if guess == "exit": print("Closing the game...") ...
587
191
"""Solvates a host, inserts guest(s) into solvated host, equilibrates """ import os import time import tempfile import numpy as np from rdkit import Chem from md import builders, minimizer from fe import pdb_writer, free_energy from ff import Forcefield from ff.handlers.deserialize import deserialize_handlers from t...
10,014
3,333
#!python import string # Hint: Use these string constants to encode/decode hexadecimal digits and more # string.digits is '0123456789' # string.hexdigits is '0123456789abcdefABCDEF' # string.ascii_lowercase is 'abcdefghijklmnopqrstuvwxyz' # string.ascii_uppercase is 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # string.ascii_letters ...
5,552
2,073
# -*- coding: utf-8 -*- from ecl.provider_connectivity import provider_connectivity_service from ecl import resource2 from ecl.network.v2 import network from ecl.network.v2 import subnet import hashlib class AddressAssignment(resource2.Resource): resources_key = "address_assignments" resource_key = "address_...
3,667
1,041
import unittest from unittest import TestCase from src.gifGenerator import GifGenerator class TestGifGenerator(TestCase): def setUp(self) -> None: self.gg = GifGenerator() def test_set_text_position(self): position = (50, 90) self.gg.setTextPosition(position) self.assertEqua...
675
223
""" TestCases for checking dbShelve objects. """ import sys, os, string import tempfile, random from pprint import pprint from types import * import unittest try: # For Pythons w/distutils pybsddb from bsddb3 import db, dbshelve except ImportError: # For Python 2.3 from bsddb import db, dbshelve from...
9,915
3,280
""" pyexcel.sources.file ~~~~~~~~~~~~~~~~~~~ Representation of file sources :copyright: (c) 2015-2016 by Onni Software Ltd. :license: New BSD License """ from pyexcel import params from pyexcel.factory import FileSource from pyexcel.sources.rendererfactory import RendererFactory from...
2,940
931
import pathlib from setuptools import setup, find_packages HERE = pathlib.Path(__file__).parent VERSION = '0.1.0' PACKAGE_NAME = 'MDF_DALEC_GRASS' AUTHOR = 'Vasilis Myrgiotis' AUTHOR_EMAIL = 'v.myrgioti@ed.ac.uk' URL = 'https://github.com/vmyrgiotis/MDF_DALEC_GRASS' LICENSE = 'MIT' DESCRIPTION = 'A Bayesian model-da...
920
382
import setuptools from croo import croo_args with open('README.md', 'r') as fh: long_description = fh.read() setuptools.setup( name='croo', version=croo_args.__version__, scripts=['bin/croo'], python_requires='>3.4.1', author='Jin Lee', author_email='leepc12@gmail.com', description='CR...
752
258
from typing import Dict import numpy as np from ..envs.env import StructuralModel from ..utils.lik_func import * from ..utils.useful_class import ParameterGrid class Estimator(ABC): """An Estimator takes in a (trained) solver and relevant params and outputs estimated structural params """ def __...
5,142
1,642
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. # Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. # # 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 Licen...
1,269
411
from django.db import models from django.contrib.auth.models import User class Link(models.Model): url = models.URLField() title = models.CharField(max_length=255) reporter = models.ForeignKey( User, on_delete=models.SET_NULL, related_name='reported_links', null=True, ...
1,371
433
import torch import torch.nn.functional as F from typing import Optional from collections import namedtuple import hpc_rl_utils # hpc version only support cuda hpc_ppo_loss = namedtuple('hpc_ppo_loss', ['policy_loss', 'value_loss', 'entropy_loss']) hpc_ppo_info = namedtuple('hpc_ppo_info', ['approx_kl', 'clipfrac']) ...
7,106
2,377
from prometheus_client import Counter from raiden.utils.typing import TokenAmount from raiden_libs.metrics import ( # noqa: F401, pylint: disable=unused-import ERRORS_LOGGED, EVENTS_EXCEPTIONS_RAISED, EVENTS_PROCESSING_TIME, MESSAGES_EXCEPTIONS_RAISED, MESSAGES_PROCESSING_TIME, REGISTRY, E...
1,069
416
# modified from TikNib/tiknib/ida/fetch_funcdata_v7.5.py import os import sys import string from hashlib import sha1 from collections import defaultdict import time import pprint as pp import idautils import idc import idaapi import ida_pro import ida_nalt import ida_bytes sys.path.append(os.path....
9,774
3,354
# # Autogenerated by Thrift Compiler (0.9.2) # # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING # # options string: py # from thrift.Thrift import TType, TMessageType, TException, TApplicationException from ttypes import * from thrift.Thrift import TProcessor from thrift.transport import TTransport ...
20,109
6,978
#!/usr/bin/env python # -*- coding: utf-8 -*- """ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * 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...
10,382
2,835
# -*- coding: utf-8 -*- """ clint.textui.core ~~~~~~~~~~~~~~~~~ Core TextUI functionality for Puts/Indent/Writer. """ from __future__ import absolute_import import sys from contextlib import contextmanager from .formatters import max_width, min_width, _get_max_width_context from .cols import columns from ..util...
2,095
712
#!/usr/bin/env python from distutils.core import setup import setuptools setup(name='McComplex', version='1.0', description="""This program reconstructs macrocomplexes of protein-protein and protein-(DNA/RNA) from a list of files of binary interactions of its chains""", author='Maria Lucía Romero, Ferran Pegena...
636
234
"""Metadata presets for commonly used keywords.""" presets = { chest : {"Anatomical Region": {"ID": "0001443", "Name": "chest", "Ontology Acronym": "UBERON", "Ontology Name": "Uber Anatomy Ontology", "Resource URL": "http://pur...
1,277
442
from bs4 import BeautifulSoup import json source = open('html-source.html', encoding="utf8").read() soup = BeautifulSoup(source, 'html.parser') # Prittified to look and understand the structure of Code # prittified = soup.prettify().encode("utf-8") # open('prettified.html', 'wb').write(prittified) color_sets = [] ...
901
301
# 데이터를 가져온다. # 학습 직전의 데이터를 가공하는 역할을 맡는다. import numpy as np import os import options as opt import datetime from sklearn.model_selection import train_test_split from sklearn.preprocessing import Normalizer import joblib def date_to_number(date): # 글자로 표현된 날짜를 숫자로 바꾼다. # ex) 'Dec/1' -> '12/1' ...
2,005
992
''' illuminants.py - Definitions of some standard illuminants. Description: Illuminants are spectrums, normalized so that Y = 1.0. Spectrums are 2D numpy arrays, with one row for each wavelength, with the first column holding the wavelength in nm, and the second column the intensity. The spectrums have a wavelength...
20,168
12,868
import numpy import pandas import hts.hierarchy from hts.functions import ( _create_bl_str_col, get_agg_series, get_hierarchichal_df, to_sum_mat, ) def test_sum_mat_uv(uv_tree): mat, sum_mat_labels = to_sum_mat(uv_tree) assert isinstance(mat, numpy.ndarray) shp = mat.shape assert shp[...
10,046
5,032
import os import warnings warnings.simplefilter('always') test_dir = os.path.dirname(os.path.abspath(__file__)) DATABASES = { 'default': { 'NAME': os.path.join(test_dir, 'db.sqlite'), 'ENGINE': 'django.db.backends.sqlite3', }, } USE_I18N = True USE_L10N = True INSTALLED_APPS = [ 'django....
644
267
""" https://leetcode.com/problems/insert-delete-getrandom-o1/ Implement the RandomizedSet class: bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise. bool remove(int val) Removes an item val from the set if present. Returns true if the item w...
3,101
917
#!/usr/bin/env python #============================================================================================== # Copyright (c) 2009 Kotys LLC. Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) # Author: Ciceron...
851
272
import smartsheet # from smartsheet.smartsheet import fresh_operation from .__smartools import SmartoolsObject, access_levels, RequirementError from .typed_list import SmartoolsTypedList smart = smartsheet.Smartsheet("INIT") smart.Sheets class SmartoolsSheets(smartsheet.sheets.Sheets): def smartools(self): return ...
7,491
2,722
# -*- coding: utf-8 -*- # Infra from modules.shared.infrastructure.log import LoggerDecorator, PyLoggerService # Application from modules.persons.application.create import PhoneCreator from modules.persons.application.create.command import CreatePhoneCommand # Domain from modules.shared.domain.http import status as h...
3,119
784
import json import logging import unittest from typing import Dict from SPARQLWrapper import JSONLD from obasparql.query_manager import QueryManager, QUERIES_TYPES, QUERY_TYPE_GET_ONE_USER from obasparql.utils import generate_uri from tests.settings import * logger = logging.getLogger('testing') graph_user = generat...
5,651
2,067
import time import json import sqlite3 import os conn = sqlite3.connect('configs/Database.db') c = conn.cursor() start_time = time.time() with open('configs/config.json') as json_data: config = json.load(json_data) server_config_raw = c.execute("SELECT * FROM ServerConfig").fetchall() server_config = {} def serve...
1,538
569
class Solution: def validPalindrome(self, s): """ :type s: str :rtype: bool """ left = 0 right = len(s)-1 while left < right: if s[left] != s[right]: return self.isPalindrome(s, left, right-1) or self.isPalindrome(s, left+1, right)...
643
188
__author__ = 'Bram van Dartel - xirixiz' __author_email__ = 'spam@rootrulez.com' __license__ = 'MIT' __maintainer_email__ = 'spam@rootrulez.com' __url__ = 'https://github.com/xirixiz/afvaldienst', __version__ = '1.1.4' from .Afvaldienst import Afvaldienst from .AfvaldienstScraper import AfvaldienstScraper
308
125
''' 日付モジュール ''' import calendar from datetime import date, datetime, timedelta from typing import Iterator from zoneinfo import ZoneInfo from dateutil.relativedelta import relativedelta def get_first_date_of_this_month(base_date: date) -> date: ''' 今月初日取得 Args: base_date (d...
4,749
2,046
import argparse import logging log = logging.getLogger(__name__) def get_main_parser(): parser = argparse.ArgumentParser(prog="tpi") return parser def main(argv=None): parser = get_main_parser() args = parser.parse_args(argv) log.debug(args)
267
89
#!/usr/bin/env python # Intro to Robotics - EE5900 - Spring 2017 # Final Project # Philip (Team Lead) # Ian # Akhil # # Revision: v1.2 # imports import rospy import smach import smach_ros import time import actionlib from easter_egg_hunt.srv import EnableDiscovery from m...
2,948
1,010
from flask import render_template, Blueprint hello_blueprint = Blueprint('hello', __name__) @hello_blueprint.route('/') @hello_blueprint.route('/hello') def index(): return render_template('index.html')
209
64
from django.shortcuts import render from django.http import HttpResponse from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from .serializers import ModelDataSerializer from .optimisation.model import run_model class RunModel(APIView): """Cons...
682
181
"""Query graph utilities.""" import re from bmt import Toolkit BMT = Toolkit() def get_subcategories(category): """Get sub-categories, according to the Biolink model.""" return [ descendant.replace("_", "") for descendant in BMT.get_descendants(category, formatted=True, reflexive=True) ]...
1,456
464
import numpy C_3 = numpy.array([1, 2]) / 3 a_3 = numpy.array([[3, -1], [1, 1]]) / 2 sigma_3 = numpy.array([[[1, 0], [-2, 1]], [[1, 0], [-2, 1]]]) C_5 = numpy.array([1, 6, 3]) / 10 a_5 = numpy.array([[11, -7, 2], [2, 5, -1], [-1, 5, 2]]) / 6 sigma_5 = numpy.array([[[40, 0, 0], [-124, 100, 0], ...
3,493
1,521
from pathlib import Path import shutil import unittest import numpy as np import siml.optimize as optimize import siml.setting as setting class TestOptimize(unittest.TestCase): def test_generate_dict(self): main_setting = setting.MainSetting.read_settings_yaml( Path('tests/data/deform/optun...
2,832
878
import asyncio import logging import os import pubnub from vivintpy.account import Account from vivintpy.devices import VivintDevice from vivintpy.devices.camera import MOTION_DETECTED, Camera from vivintpy.exceptions import VivintSkyApiMfaRequiredError pubnub.set_stream_logger(name="pubnub", level=logging.ERROR) ...
1,773
525
from django.contrib.auth.mixins import LoginRequiredMixin from django.http.response import HttpResponseRedirect, HttpResponseBadRequest from django.urls.base import reverse from django.utils import timezone from django.views.generic import ( CreateView, DayArchiveView, DetailView, RedirectView, Templ...
3,811
1,432
# 888 888 # 888 888 # 888 888 # .d8888b 88888b. 8888b. 88888b. .d88b. .d88b. 888 .d88b. .d88b. # d88P" 888 "88b "88b 888 "88b d88P"88b d8P Y8b 888 d88...
92,214
27,832
from typing import List, Dict from pyhcl.ir.low_ir import * from pyhcl.ir.low_prim import * from pyhcl.passes._pass import Pass from pyhcl.passes.utils import get_binary_width DEFAULT_READ_LATENCY = 0 DEFAULT_WRITE_LATENCY = 1 @dataclass class ExpandMemory(Pass): def run(self, c: Circuit): def get_mem_po...
4,440
1,314
import logging import time import os BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) format = "%(asctime)s %(levelname)-10s %(message)s" id = time.strftime("%Y%m%d-%H%M%S") #These are the sequences need to get colored ouput RESET_SEQ = "\033[0m" COLOR_SEQ = "\033[1;%dm" BOLD_SEQ = "\033[1m" def for...
2,071
765
from ethereum import tester as t from ethereum import utils def test(): s = t.state() test_company = s.abi_contract('company.se', ADMIN_ACCOUNT=utils.decode_int(t.a0)) order_book = s.abi_contract('orders.se') test_currency = s.abi_contract('currency.se', sender=t.k0) assert test_company.getAdmin() ...
4,485
1,686
import torch import numpy as np from libyana.visutils.viz2d import visualize_joints_2d from meshreg.datasets.queries import BaseQueries, TransQueries from meshreg.visualize import consistdisplay def get_check_none(data, key, cpu=True): if key in data and data[key] is not None: if cpu: return ...
14,338
5,386
from fastapi import Depends, HTTPException, Path, status from pydantic import UUID4 from api.dependencies.database import get_repository from db.errors import EntityDoesNotExist, ResourceIsNotDeployed from db.repositories.user_resources import UserResourceRepository from db.repositories.workspace_services import Works...
3,185
1,030
# Copyright (c) 2017 The Khronos Group Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
14,828
5,063
import unittest from payroll import * class P2Test(unittest.TestCase): def setUp(self): self.emp = payroll.Employee('12-3456789', 'John', 'Doe', '123 Anystreet', 'Anytown', 'Anystate', '98765') def testHourly(self): rate = 35.5 self.emp.make_hourly(rate) for d in range(10): ...
1,015
407
# -*- coding: utf-8 -*- import time import numpy as np from scipy import interpolate import astropy.units as u import astropy.constants as const import os, inspect try: import cPickle as pickle except: import pickle import hashlib from EXOSIMS.Prototypes.Completeness import Completeness from EXOSIM...
17,884
6,042
# Copyright 2017-2020 Palantir Technologies, Inc. # Copyright 2021- Python Language Server Contributors. import logging from pylsp import hookimpl, _utils log = logging.getLogger(__name__) @hookimpl def pylsp_hover(document, position): code_position = _utils.position_to_jedi_linecolumn(document, position) ...
1,418
413
# -*- coding: utf-8 -*- import items class TxtFileWriter: """ Write the repository representation in the file. """ def __init__(self, file_path): self.file_path = file_path def __enter__(self): self.file = open(self.file_path, 'w', encoding='utf-8') return self def ...
4,753
1,342
import numpy as np def apply_tikhonov_regularization(u,s,v,usetikparam,vector): #alpha = usetikparam*np.sqrt(u.shape[0]/v.shape[1]) # Tikhonov parameter interpreted as scaled by sqrt(matrix rows/matrix cols) so that it is directly interpretable as NETD/NESI (noise equivalent temperature difference over no...
736
253
import flask import telebot import words from dotenv import load_dotenv load_dotenv() app = flask.Flask(__name__) bot = telebot.TeleBot(environ.get("TG_TOKEN"), threaded=False) WEBHOOK_URL_PATH = "/%s/" % (environ.get("TG_TOKEN")) # # Remove webhook, it fails sometimes the set if there is a previous webhook # bot.re...
1,563
558
""" lvsfunc, a collection of VapourSynth functions and wrappers written and/or modified by LightArrowsEXE. If you spot any issues, please do not hesitate to send in a Pull Request or reach out to me on Discord (LightArrowsEXE#0476)! """ # flake8: noqa from . import aa, comparison, deinterlace, denoise, m...
547
193
roman_dict = { "I" : 1, "V" : 5, "X" : 10, "L" : 50, "C" : 100, "D" : 500, "M" : 1000 } class Solution: def romanToInt(self, s: str) -> int: previous = 0 current = 0 result = 0 for x in s[::-1]: current = roman_dict[x] if (previous > current): ...
529
204
""" MIT License Copyright (c) 2019 Ildoo Kim Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, dis...
4,214
1,348
import abc import logging from typing import List from ee.models import EnvironmentDefinition logger = logging.getLogger(__name__) class DeploymentBackend(abc.ABC): def run(self, env_def: EnvironmentDefinition, command: List[str]): """ This is the main public method. This is a template ...
2,154
544
#! /usr/bin/env python import rospy import sys import copy import moveit_commander import moveit_msgs.msg import geometry_msgs.msg import actionlib class Ur5Moveit: # Constructor def __init__(self, arg_robot_name): rospy.init_node('node_eg2_predefined_pose', anonymous=True) self._robot_ns =...
2,946
1,091
# -*- coding: utf-8 -*- """ Gist embedding plugin for Pelican ================================= This plugin allows you to embed `Gists`_ into your posts. .. _Gists: https://gist.github.com/ """ from __future__ import unicode_literals import hashlib import logging import os import re import codecs import pygments lo...
5,047
1,598
import time from socket import * import sys host = sys.argv[1] #port = sys.argv[2] #message = sys.argv[2] sock = socket(AF_INET, SOCK_DGRAM) sock.settimeout(1) sock.bind((str(host),0)) print(sock.getsockname(),sock.getsockname()[1]) port = 5967 for message in 'abcdefghijklmnopqrstuvwxyz': sock.sendto(message.e...
1,188
460
XXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXX XXXX XXXXXXXX XXXXXXXX XXX XXXXXXXXX XXXXXXXX XXX XXX XXXXXXXXXX XX XXXXXXXX XXXXXXXXXXXXXX XXXXXXX XXX XXXX XXXXXXX XX XXX XXXXX XX XXXXX XXXXXXXXXX XX XXX XX XXXXXXXXX XXXXXXXXXXXXXX XXX XXXXXXXXXXXXX XXX XXX XXXXXXXXXXXXXXXXXXXX XXXXX XXXXX XXX...
26,799
8,322
""" A script that reads a file from the web and returns the all the words having frequency in between two words passed """ import re from nltk.corpus import stopwords import requests from operator import itemgetter def run(url, word1, word2): freq = {} # keep the freq of each word in the file freq[word1] = 0...
2,218
678
# 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...
4,487
1,358
#!/usr/bin/python3 import argparse import ctypes import json import sys if not '..' in sys.path: sys.path.append('..') from comm import BoardTypes from comm import CANInterface from comm import XCPConnection from util import plugins from util import ctypesdict from util import config import argProc plugins.l...
4,715
1,306
""" Dependency graph: Evaluated ID example ++++++++++++++++++++++++++++++++++++++ This example demonstrates access to the evaluated ID (such as object, material, etc.) state from an original ID. This is needed every time one needs to access state with animation, constraints, and modifiers taken into account. """ impor...
2,383
633
# Usage: execute # $ python support/generate.py # at wpt/upgrade-insecure-requests/. # # Note: Some tests (link-upgrade.sub.https.html and # websocket-upgrade.https.html) are not covered by this generator script. template = '''<!DOCTYPE html> <html> <head> <!-- Generated by wpt/upgrade-insecure-requests/support/genera...
2,411
800
from functools import partial from .activations import Mish from .net import Net __all__ = ['mxresnet_parameters', 'mxresnet34', 'mxresnet50'] mxresnet_parameters = {'stem_sizes': [3, 32, 64, 64], 'act_fn': Mish()} mxresnet34 = partial(Net, name='MXResnet32', expansion=1, layers=[3, 4, 6, 3], **mxresnet_parameters...
424
178
import os import pandas as pd from imblearn.under_sampling import RandomUnderSampler from contextlib import contextmanager import psutil import time @contextmanager def timer_memory(name): t0 = time.time() yield print( f'Memory: {(psutil.Process(os.getpid()).memory_info().rss/2**30):.02f}GB') ...
1,242
431
import unittest import spydrnet as sdn class TestEdifNamespace(unittest.TestCase): original_default = None @classmethod def setUpClass(cls) -> None: cls.original_default = sdn.namespace_manager.default sdn.namespace_manager.default = "EDIF" @classmethod def tearDownClass(cls) -> N...
8,652
3,010
# coding=utf-8 # Copyright 2018 The TF-Agents Authors. # # 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...
3,344
1,029
import pygame as pg pg.init() from src.main import Main main = Main()
72
25
import frappe def execute(): # all icons hidden in standard are "blocked" # this is for the use case where the admin wants to remove icon for everyone # in 7.0, icons may be hidden by default, but still can be shown to the user # e.g. Accounts, Stock etc, so we need a new property for blocked frappe.db.sql('upda...
388
115
#!/usr/bin/env python3 # pylint: disable=missing-docstring,invalid-name,broad-except,cell-var-from-loop import hashlib import json import os import sys from utils import get_date_from_zip, get_metadata_from_zip ALLOWED_BUILDTYPES = ["Alpha", "Beta", "Official", "Gapps"] ALLOWED_VERSIONS = ["9.0", "10"] FILE_BASE: s...
3,985
1,202
import os # from signal import pause from gpiozero import Button from datetime import datetime def take_screen(): screen_btn = Button(2) while True: if screen_btn.is_pressed: timestamp = datetime.now() cmd = "scrot -u d 5 $n {}.png".format('screen_' + str(timestamp)) ...
431
136
import common lines = common.get_lines('day21_data.txt') food_dict = {} all_ingredients = [] for line in lines: ingredients, allergens = line.split(' (contains ') allergens = allergens[:-1].split(', ') ingredients = ingredients.split(' ') all_ingredients.extend(ingredients) for alle...
1,435
489
# -*- coding: utf-8 -*- """ @author: david """ import matplotlib.pyplot as plt import seaborn as sns import numpy as np from sklearn.model_selection import KFold from sklearn.metrics import confusion_matrix, classification_report from sklearn.metrics import PrecisionRecallDisplay, RocCurveDisplay class ModelEvaluatio...
4,279
1,336
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/11/20 8:15 # @Author : HaiFeng # @Email : 24918700@qq.com from setuptools import setup import os this_directory = os.path.abspath(os.path.dirname(__file__)) # 读取文件内容 def read_file(filename): with open(os.path.join(this_directory, filename), enc...
1,632
662
# Copyright 2020 The FedLearner Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
6,478
1,721
# -*- coding: utf-8 -*- import json from typing import List, Optional from flask import make_response __author__ = "Sören Gebbert" __copyright__ = "Copyright 2018, Sören Gebbert, mundialis" __maintainer__ = "Sören Gebbert" __email__ = "soerengebbert@googlemail.com" def as_dict_without_nones(o): d = o.__dict__ ...
4,636
1,369
import avalon.api class UpdateNamespace(avalon.api.InventoryAction): """Update container imprinted namespace Sometimes artist may import loaded subsets from other scene, which may prefixing an extra namespace on top of those subsets but the namespace attribute in the container did not update hence a...
1,457
370
import logging import gpg from rest_framework import serializers from .conf import settings from . import models logger = logging.getLogger(__name__) class PGPFileField(serializers.Field): def to_representation(self, value): with gpg.Context(armor=True) as c: imp = c.key_import(settings.SAL...
3,694
1,049
from flask import ( Blueprint, flash, g, redirect, render_template, get_template_attribute, request, url_for, jsonify ) #from ....dataprocessing import # dataprocessin .read_rdf import from demosauruswebapp.demosaurus.db import get_db import pandas as pd from nltk.metrics import distance as nl_distance import re im...
11,950
3,511
import math import numpy as np import torch from torch import nn from torch.backends import cudnn from torch.utils.data import DataLoader from tqdm import tqdm from model import CharRNN from data import TextDataset, TextConverter class Trainer(object): def __init__(self, args): self.args = args ...
6,784
2,226
#!/usr/bin/env python import time import random import math import unittest import numpy as np import pandas as pd import std_msgs from std_msgs.msg import String # from control_msgs.msg import JointControllerState # from gazebo_msgs.msg import LinkStates # import matplotlib.pyplot as plt import dynamixel_adapter ##...
17,360
5,536
# This is a public namespace, so we don't want to expose any non-underscored # attributes that aren't actually part of our public API. But it's very # annoying to carefully always use underscored names for module-level # temporaries, imports, etc. when implementing the module. So we put the # implementation in an under...
10,278
4,746
import pytest from d3rlpy.models.torch.encoders import PixelEncoder from d3rlpy.models.torch.encoders import PixelEncoderWithAction from d3rlpy.models.torch.encoders import VectorEncoder from d3rlpy.models.torch.encoders import VectorEncoderWithAction from d3rlpy.encoders import create_encoder_factory from d3rlpy.enco...
2,258
714
# -*- coding: utf-8 -*- #import game from glob import glob file1 = glob("01_face_dataset.py") file2 = glob("02_face_training.py") import facedataset import facetrain import cv2 import numpy as np import os from PIL import Image #facedataset.first() #facetrain.second() recognizer = cv2.face.LBPHFaceRecognizer_create() ...
2,217
905
from transformers import ( RobertaModel, RobertaPreTrainedModel, BertModel, BertPreTrainedModel, ) class BertEncoder(BertPreTrainedModel): def __init__(self, config): super(BertEncoder, self).__init__(config) self.bert = BertModel(config) self.init_weights() def forwa...
1,047
337
#!/usr/bin/env python3 # MIT License # # Copyright (c) 2022 Eugenio Parodi <ceccopierangiolieugenio AT googlemail DOT 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 restricti...
3,395
1,251
# This DAG is for running python scripts to generate static visualisation data # from syncthing every month end import airflow from airflow import DAG from airflow.operators.bash_operator import BashOperator from airflow.operators.python_operator import PythonOperator from airflow.operators.dummy_operator import Dumm...
4,433
1,414
from nadl.tensor import Tensor from nadl.parameter import Parameter
67
17