text
string
size
int64
token_count
int64
"""编译go语言模块.""" import warnings from typing import List, Optional from pathlib import Path from pmfp.utils.run_command_utils import run def _build_grpc(includes: str, flag: str, to: str, target: str, cwd: Path) -> None: command = f"protoc {includes} {flag} --go_out={to} --go-grpc_out={to} {target}" try: ...
1,642
704
# Generated by Django 2.2.1 on 2019-05-22 00:07 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('instapp', '0002_auto_20190522_0006'), ] operations = [ migrations.RenameField( model_name='image', old_name='profile', ...
369
137
import json import logging from flask import jsonify, make_response, request from flask_jwt_extended import jwt_required from flask_restful import Resource from http import HTTPStatus from marshmallow import ValidationError, Schema from werkzeug.security import generate_password_hash from app.models import db from ap...
4,007
1,241
from main import readData, getTrueLabels, binariseLabels, removePacketsAfterChange label_data = list() label_data.append(readData("..\\data\\test5_targets_1.csv")) label_data.append(readData("..\\data\\test5_targets_2.csv")) label_data.append(readData("..\\data\\test5_targets_3.csv")) labels = [getTrueLabels(label) ...
984
356
import numpy as np from mpi4py import MPI from src.imagine.goal_generator.simple_sentence_generator import SentenceGeneratorHeuristic from src import logger class GoalSampler: def __init__(self, policy_language_model, reward_language_model, goal_dim, ...
14,183
4,251
#!/usr/bin/env python #This is different from AIY Kit's actions #Copying and Pasting AIY Kit's actions commands will not work from googleapiclient.discovery import build from googleapiclient.errors import HttpError from gmusicapi import Mobileclient from googletrans import Translator from gtts import gTTS import req...
711
243
from Qt import QtWidgets, QtGui from .categories import ( CategoryState, SystemWidget, ProjectWidget ) from .widgets import ShadowWidget from .. import style class MainWidget(QtWidgets.QWidget): widget_width = 1000 widget_height = 600 def __init__(self, user_role, parent=None): super(...
2,358
702
import lambda_handler from unittest import TestCase from mock import call, patch, Mock from datetime import datetime import boto3 import json from botocore.stub import Stubber import urllib3 mock_s3_client = boto3.client('s3') s3_stubber = Stubber(mock_s3_client) list_objects_response = { 'IsTruncated': False, ...
6,093
2,092
import uuid from mongoengine import Document, StringField, ListField, UUIDField from django.conf import settings from cripts.core.cripts_mongoengine import CriptsBaseAttributes, CriptsSourceDocument from cripts.core.cripts_mongoengine import CriptsActionsDocument class UserName(CriptsBaseAttributes, CriptsSourceDoc...
2,189
543
import pytest import operator as op from sweetpea import fully_cross_block from sweetpea.primitives import Factor, DerivedLevel, WithinTrial, Transition, Window from sweetpea.encoding_diagram import __generate_encoding_diagram color = Factor("color", ["red", "blue"]) text = Factor("text", ["red", "blue"]) con_lev...
7,611
2,599
import json from labinstrument.SS.CMW500.CMW500_WIFI.CMW500_WIFI import * if __name__ == '__main__': new_config_name='emm' new_config=CMW_WIFI(17).get_parameters() config=json.load(open('config.txt')) config[new_config_name]=new_config json.dump(config,open('config.txt','w'))
297
121
import yaml import os import time import datetime from pycti.utils.constants import StixCyberObservableTypes from weasyprint import HTML from pycti import OpenCTIConnectorHelper, get_config_variable from jinja2 import Environment, FileSystemLoader class ExportReportPdf: def __init__(self): # Instantiate t...
9,957
2,861
from django.urls import path from .views import initiate_payment, callback urlpatterns = [ path('', initiate_payment, name='pay'), path('callback/', callback, name='callback'), ]
189
56
def get(isamAppliance, check_mode=False, force=False): """ Retrieve an overview of updates and licensing information """ return isamAppliance.invoke_get("Retrieve an overview of updates and licensing information", "/updates/overview") def get_licensing_info(isamAppl...
544
155
# -*- coding: utf-8 -*- __author__ = "Paul Schifferer <dm@sweetrpg.com>" """ config.py - settings for the flask application object """ import os import redis from sweetrpg_library_api.application import constants class BaseConfig(object): DEBUG = bool(os.environ.get(constants.DEBUG) or True) PORT = os.env...
1,741
706
import pandas as pd from group import Group class Frames: def __init__(self, frame=None): self.cleanups = Cleanup() self.groups = Group() class Cleanup: def __init__(self, frame=None): self.frame = frame def __call__(self, frame): self.frame =...
1,711
887
# Copyright (c) 2018 Mycroft AI, Inc. # # This file is part of Mycroft Skills Manager # (see https://github.com/MatthewScholefield/mycroft-light). # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional inf...
20,594
5,860
# Autogenerated by the mkresources management command 2014-11-13 05:39 from tastypie.resources import ModelResource from tastypie.fields import CharField from tastypie.constants import ALL from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from ietf import api from ...
973
278
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import bisect import numpy as np from torch.utils.data.dataset import ConcatDataset as _ConcatDataset class ConcatDataset(_ConcatDataset): """ Same as torch.utils.data.dataset.ConcatDataset, but exposes an extra method for querying t...
1,624
503
# 153. Find Minimum in Rotated Sorted Array # # Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. # # (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). # # Find the minimum element. # # You may assume no duplicate exists in the array. class Solution(object): # http://b...
1,129
443
import pytest from brownie import ( accounts, interface, MockVault, BadgerBridgeAdapter, CurveSwapStrategy, CurveTokenWrapper, ) from helpers.constants import AddressZero from helpers.registry import registry from config.badger_config import badger_config from scripts.systems.badger_system impo...
10,452
3,505
import os class Config: # Statement for enabling the development environment DEBUG = True # Define the application directory BASE_DIR = os.path.abspath(os.path.dirname(__file__)) # Logging config. LOG_DIR = "logs" LOG_TYPE = ["LOG_TYPE", "watched"] LOG_LEVEL = "DEBUG" APP_LOG_NAM...
1,423
543
"""Top-level package for etherscan-py.""" __author__ = """Julian Koh""" __email__ = 'juliankohtx@gmail.com' __version__ = '0.1.0'
131
56
from subprocess import Popen, PIPE def run_command(command): process = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE) while True: output = process.stdout.readline() if output == '' and process.poll() is not None: break if output: print output.str...
427
133
from db_connection import db class Agenda(db.Model): __tablename__ = "agendas" id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) work_start = db.Column(db.Time) work_end = db.Column(db.Time) rest_start = db.Column(db.Time) rest_end = db.Column(db.Time) user_id = db...
923
325
"""Database models""" from sqlalchemy import orm import sqlalchemy from .db_session import SqlAlchemyBase # Task database model class Task(SqlAlchemyBase): __tablename__ = 'tasks' id = sqlalchemy.Column( sqlalchemy.Integer, primary_key=True, autoincrement=True ) user_id = sqlalchemy.Column(...
661
237
# Generated by Django 3.0 on 2019-12-18 21:09 import ckeditor.fields from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('graduated_site', '0028_auto_20191218_2028'), ] operations = [ migrations.AlterField( model_name='user_internship_po...
470
172
#!/usr/bin/env python """Unit tests for M2Crypto.m2 obj_* functions. """ from M2Crypto import ASN1, BIO, Rand, X509, m2, six from tests import unittest """ These functions must be cleaned up and moved to some python module Taken from CA managment code """ def x509_name2list(name): for i in range(0, name.entry_c...
4,945
1,872
#!/bin/python # -*- coding: utf-8 -*- # Droplet Name: ubuntu-512mb-sfo2-01 # IP Address: 138.68.252.152 # Username: root # Password: fbe29a96430704766b5054c4d9 # New Password: Rowing525 # https://medium.com/@hoppy/how-to-test-or-scrape-javascript-rendered-websites-with-python-selenium-a-beginner-step-by-c137892216aa ...
4,656
1,706
from gdsfactory.simulation.gmeep.add_monitors import add_monitors from gdsfactory.simulation.gmeep.get_simulation import get_simulation from gdsfactory.simulation.gmeep.get_transmission_2ports import ( get_transmission_2ports, plot2D, plot3D, ) from gdsfactory.simulation.gmeep.plot_xsection import plot_xsec...
532
207
#!/usr/bin/python3 import boto3 import botocore import fedora_messaging import fedora_messaging.api import hashlib import json import logging import os import subprocess import sys import tarfile import tempfile import traceback # Set local logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) ...
11,212
3,629
from torch.utils.data.dataset import Dataset import numpy as np import pandas as pd import os import nibabel as nib from nilearn.image import resample_img import torch class UKBBDataset(Dataset): def __init__(self, csv_path, base_path='/vol/biobank/12579/brain/rigid_to_mni/images', crop_type=None, crop_size=(64, 6...
1,837
686
# Copyright (C) 2021 Intel 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 License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
4,493
1,342
from typing import List class Solution: def luckyNumbers (self, matrix: List[List[int]]) -> List[int]: m = len(matrix) n = len(matrix[0]) ans = [] for i in range(m): row_min_index = 0 row_min = 10**5+1 for j in range(n): if matrix[i...
846
296
# UC10 - Evaluate price # # User U exists and has valid account # We create two Users, User1_UC10, User2_UC10 and one new gasStation GasStationUC10 # # Registered on a 1920x1080p, Google Chrome 100% zoom ### SETUP #User1 click("1590678880209.png") click("1590678953637.png") wait(2) type("1...
3,282
1,859
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-27 16:14 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('basic', '0002_auto_20170727_1741'), ] operations = [ migrations.AddField( ...
540
193
# -------------------------------------------------------- # Pytorch Multi-GPU Faster R-CNN # Licensed under The MIT License [see LICENSE for details] # Written by Jiasen Lu, Jianwei Yang, based on code from Ross Girshick # -------------------------------------------------------- from __future__ import absolute_import ...
29,337
11,488
from flask import Flask, render_template, request, redirect, url_for, Markup import app_helper as apHelp app = Flask(__name__) @app.route('/') def root(): return render_template('home.html') # click convetBtn. get HttpParam. @app.route('/post', methods=['GET', 'POST']) def post(): if request.method == 'POST'...
1,231
372
""" Makes subdirectories with slices of seismic time or depth images. For example, the directory with name "s3_84" contains a constant-i3 slice, where i3 = 84. """ from tputils import * #setupForSubset("subz_401_4_600") setupForSubset("subt_251_4_500") seismicDir = getSeismicDir() #####################################...
1,322
550
""" LLDB AppKit formatters part of The LLVM Compiler Infrastructure This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details. """ # summary provider for class NSException import lldb.runtime.objc.objc_runtime import lldb.formatters.metrics import CFString import lldb i...
4,442
1,300
self.description = "Install a package ('any' architecture)" p = pmpkg("dummy") p.files = ["bin/dummy", "usr/man/man1/dummy.1"] p.arch = 'any' self.addpkg(p) self.option["Architecture"] = ['auto'] self.args = "-U %s" % p.filename() self.addrule("PACMAN_RETCODE=0") self.addrule("PKG_EXIST=dummy") for f in ...
364
154
from simple_network.tcp_app_server import * import httptools """ Module Docstring Docstrings: http://www.python.org/dev/peps/pep-0257/ """ __author__ = 'ButenkoMS <gtalk@butenkoms.space>' # ====================================================================== # ===================GLOBAL SETTINGS FOR ALL TESTS=====...
7,995
2,520
from os import path from launch import LaunchDescription from ament_index_python.packages import get_package_share_directory from launch_ros.actions import Node from launch.actions import DeclareLaunchArgument from launch.substitutions import Command, LaunchConfiguration def generate_launch_description(): use_sim_...
1,066
286
from pyformance.meters import Event, EventPoint from tests import TimedTestCase class EventTestCase(TimedTestCase): def setUp(self): super(EventTestCase, self).setUp() self.event = Event( clock=TimedTestCase.clock, key="test_event", tags={"name", "value"} ...
1,211
381
""" Good morning! Here's your coding interview problem for today. This problem was asked by Amazon. Implement a stack that has the following methods: push(val), which pushes an element onto the stack pop(), which pops off and returns the topmost element of the stack. If there are no elements in the stack, then it sh...
4,894
1,428
""" Link extractor based on lxml.html """ import lxml.html from scrapy.link import Link from scrapy.utils.python import unique as unique_list class LxmlParserLinkExtractor(object): def __init__(self, tag="a", attr="href", process=None, unique=False): self.scan_tag = tag if callable(tag) else lambda t: t ...
1,161
351
from django.contrib import admin from .models import Meeting admin.site.register(Meeting)
97
31
from flask import Flask, url_for import os app = Flask(__name__) app.config['DEBUG'] = True app.config['SECRET_KEY'] = 'SECRET_KEY_CH1ng3me' # Determines the destination of the build. Only usefull if you're using Frozen-Flask app.config['FREEZER_DESTINATION'] = os.path.dirname(os.path.abspath(__file__))+'/../build' ...
578
194
import numpy as np import argparse from sklearn.svm import LinearSVR from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.datasets import make_regression parser = argparse.ArgumentParser() parser.add_argument('-x', '--datapath', type=str, required=True) parser.add_a...
936
338
#!/usr/bin/env python # MIT License # # Copyright (c) 2020 Rik Baehnemann, ASL, ETH Zurich, Switzerland # # 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 witho...
4,797
1,603
"""Google Cloud Hierarchical Firewall Generator. Hierarchical Firewalls (HF) are represented in a SecurityPolicy GCP resouce. """ import copy import re from typing import Dict, Any from absl import logging from capirca.lib import gcp from capirca.lib import nacaddr class ExceededCostError(gcp.Error): """Raised ...
20,198
6,094
"""Kits class defines the available Toolboxes.""" from enum import Enum class Kits(Enum): """Enumerator for toolbox class name lookups.""" HOSTS = "HostsToolbox" RTR = "RTRToolbox"
196
68
#!/bin/python3 # https://www.hackerrank.com/challenges/time-conversion import sys def timeConversion(s): # Complete this function ar = s.split(':') tail = ar[-1][-2:].lower() addition_hours = 0 if (tail == 'pm' and ar[0] != '12') or (tail == 'am' and ar[0] == '12'): addition_hours ...
559
238
from decimal import Decimal, getcontext, ROUND_HALF_UP from supplychainpy.demand import analyse_uncertain_demand from supplychainpy.demand.eoq import minimum_variable_cost, economic_order_quantity class EconomicOrderQuantity(analyse_uncertain_demand.UncertainDemand): __economic_order_quantity = Decimal(0) ana...
5,296
1,626
from __future__ import division import mmcv import numpy as np import pytest def test_quantize(): arr = np.random.randn(10, 10) levels = 20 qarr = mmcv.quantize(arr, -1, 1, levels) assert qarr.shape == arr.shape assert qarr.dtype == np.dtype('int64') for i in range(arr.shape[0]): for...
2,182
940
#!/usr/bin/env python """ Author: João Ribeiro """ import argparse import numpy as np from model import FeedForwardNetwork from utils import load_ocr_dataset, plot if __name__ == '__main__': parser = argparse.ArgumentParser() # Hyperparams parser.add_argument('-epochs', default=20, type=int, help="N...
2,373
807
from guardian.shortcuts import get_objects_for_user from django.http import Http404, HttpResponseRedirect from django.db.models import Count from django.core.urlresolvers import reverse from django.shortcuts import render, get_object_or_404 from vdw.samples.models import Sample, Project, Batch, Cohort from .forms impor...
3,935
1,230
import sys from pprint import pprint import os #--------------------------------------------------------------------------# class CsPP(): def __init__(self, domains): self.domains = domains self.maindict = {} self.keyitems = [] pass def check_if(self): emptylist = [] ...
6,656
1,918
#!/usr/bin/env python3 # coding: utf-8 # Adapted from: https://github.com/zpincus/celltool/blob/master/celltool/numerics/image_warp.py from scipy import ndimage import numpy as np from probreg import bcpd import tifffile import matplotlib.pyplot as plt import napari from magicgui import magic_factory, widgets from nap...
6,079
2,607
from django.test import TestCase, RequestFactory import vcr from django.conf import settings from django.core.management import call_command from open_humans.models import OpenHumansMember from main.celery import read_reference, clean_raw_23andme from main.celery_helper import vcf_header import os import tempfile impor...
6,235
2,067
from django.contrib import admin from .models import LogCategory, BudgetLog # Register your models here. admin.site.register(LogCategory) admin.site.register(BudgetLog)
168
47
# -*- coding: UTF-8 -*- #!/usr/bin/python3 """ Embedding Layer """ #************************************************************ # Imported Libraries #************************************************************ import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from gensim.models i...
2,060
743
import abc import socket import logging import asyncio import warnings import h2.config import h2.exceptions from .utils import DeadlineWrapper from .const import Status from .stream import send_message, recv_message from .stream import StreamIterator from .metadata import Metadata, Deadline from .protocol import H2P...
17,810
4,721
#!/usr/bin/env python import argparse from eva import EvaProgram, Input, Output from eva.ckks import CKKSCompiler from eva.seal import generate_keys import numpy as np import time from eva.std.numeric import horizontal_sum def dot(x, y): return np.dot(x, y) def generate_inputs_naive(size, label="x"): inputs...
3,923
1,392
from __future__ import division from __future__ import print_function # -*- coding: utf-8 -*- # Copyright 2020 Google 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.a...
5,903
1,764
# Generated by Django 2.2 on 2019-10-25 10:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sales', '0028_auto_20191024_1736'), ] operations = [ migrations.AlterField( model_name='interaction', name='result', ...
401
147
""" UI for controlling how api classes and mel commands are combined into pymel classes. This UI modifies factories.apiToMelData which is pickled out to apiMelBridge. It controls: which mel methods correspond to api methods disabling of api methods preference for overloaded methods (since currently only o...
41,238
11,924
x:[int] = None x = [] print(x[0])
35
20
from .model import VQVCModel from .pl_model import VQVCModule
62
21
from typing import Union, TypeVar from enum import Enum import torch pi = torch.tensor(3.14159265358979323846) T = TypeVar('T', bound='Resample') U = TypeVar('U', bound='BorderType') class Resample(Enum): NEAREST = 0 BILINEAR = 1 BICUBIC = 2 @classmethod def get(cls, value: Union[str, int, T]) ...
1,040
368
import intrepyd from intrepyd.iec611312py.plcopen import parse_plc_open_file from intrepyd.iec611312py.stmtprinter import StmtPrinter import unittest from . import from_fixture_path class TestOpenPLC(unittest.TestCase): def test_simple_1(self): pous = parse_plc_open_file(from_fixture_path('openplc/simple1....
1,731
654
__author__ = 'Georgios Rizos (georgerizos@iti.gr)' import numpy as np import scipy.sparse as sparse from reveal_graph_embedding.common import get_file_row_generator def read_adjacency_matrix(file_path, separator): """ Reads an edge list in csv format and returns the adjacency matrix in SciPy Sparse COOrdina...
3,506
1,116
# create_tweet_classes.py # this assumes the existence of a get_class(day, hour, ticker) function # that returns the class (0, 1, or -1) for a given hour and ticker import collections import json import random refined_tweets = collections.defaultdict(list) #returns label for company and time def getLabel(ticker, mon...
1,255
515
from unittest import TestCase import json from helpers import * from pytezos import ContractInterface, pytezos, MichelsonRuntimeError from pytezos.context.mixin import ExecutionContext token_a = "KT1AxaBxkFLCUi3f8rdDAAxBKHfzY8LfKDRA" token_b = "KT1PgHxzUXruWG5XAahQzJAjkk4c2sPcM3Ca" token_c = "KT1RJ6PbjHpwc3M5rw5s2Nb...
11,538
3,998
def remove_duplicates(lst): new = [] for x in lst: if x not in new: new.append(x) return new
109
42
import datetime from datetime import timedelta import pprint from config import * from helper import * import time import logging from logging.handlers import RotatingFileHandler logger = logging.getLogger('Twitch Relay Monitor') logger.setLevel(logging.DEBUG) handler = RotatingFileHandler('/home/pi/twitch_relay_monit...
4,013
1,488
class Config: # helps to store settings for an experiment. def __init__(self, _experiments_folder_path='experiments', _dataset_name='dataset', _column_names='unknown', _types={1:'integer', 2:'string', 3:'float', 4:'boolean', 5:'gender', 6:'unknown', 7:'date-iso-8601', 8:'date-eu', 9:'date-non-s...
793
252
import os from collections import defaultdict from rbc.omnisci_backend import Array from rbc.errors import OmnisciServerError from numba import types as nb_types import pytest rbc_omnisci = pytest.importorskip('rbc.omniscidb') available_version, reason = rbc_omnisci.is_available() pytestmark = pytest.mark.skipif(not a...
12,928
5,102
data = ( 'Lun ', # 0x00 'Kua ', # 0x01 'Ling ', # 0x02 'Bei ', # 0x03 'Lu ', # 0x04 'Li ', # 0x05 'Qiang ', # 0x06 'Pou ', # 0x07 'Juan ', # 0x08 'Min ', # 0x09 'Zui ', # 0x0a 'Peng ', # 0x0b 'An ', # 0x0c 'Pi ', # 0x0d 'Xian ', # 0x0e 'Ya ', # 0x0f 'Zhui ', # 0x10 'Le...
4,666
2,988
from dataclasses import dataclass import re from tokenize import group from core.constructs.resource import ResourceModel from core.constructs.workspace import Workspace RUUID = "cdev::simple::bucket" def get_cloud_output_from_cdev_name(component_name: str, cdev_name: str) -> str: try: ws = Workspace.in...
1,785
565
from greens_thm_form import greens_form_line, greens_form_shape from numpy import arange, linspace, float64, indices, zeros_like, ones_like, pi, sin, complex128, array, exp, newaxis, cumsum, sum, cos, sin, log, log10 from osrefl.theory.DWBAGISANS import dwbaWavefunction class shape: def __init__(self, name): ...
7,434
3,300
# -*- coding: utf-8 -*- # Demo: MACD strategy # src: ./test_backtest/MACD_JCSC.py # jupyter: ./test_backtest/QUANTAXIS回测分析全过程讲解.ipynb # paper: ./test_backtest/QUANTAXIS回测分析全过程讲解.md import QUANTAXIS as QA import numpy as np import pandas as pd import datetime st1=datetime.datetime.now() # define the MACD strategy def M...
3,750
1,564
from zquantum.core.interfaces.ansatz_test import AnsatzTests from zquantum.core.circuits import Circuit, H, RX, RZ from zquantum.core.utils import compare_unitary from zquantum.core.openfermion import change_operator_type from zquantum.qaoa.ansatzes.farhi_ansatz import ( QAOAFarhiAnsatz, create_farhi_qaoa_circu...
6,247
2,192
from html.parser import HTMLParser class Paper(): def __init__(self): self.title = "" self.source_link = "" self.authr_and_pub = "" # self.publication = "" self.abstract = "" self.star_link = "" def add_title(self, title): self.title = title retu...
3,297
1,011
"""Wrapper for pygame, which exports the PSP Python API on non-PSP systems.""" __author__ = "Per Olofsson, <MagerValp@cling.gu.se>" import pygame pygame.init() _vol_music = 255 _vol_sound = 255 def setMusicVolume(vol): global _vol_music if vol >= 0 and vol <= 255: _vol_music = vol pygame...
1,067
394
import os import csv import ast # used to generate folder-seperated corpus from CMUMovie dataset # just type python utility_parseCMUMovie.py in a terminal and the data will be downloaded and split to subfolders in the moviePlots/ path os.system("wget http://www.cs.cmu.edu/~ark/personas/data/MovieSummaries.tar.gz") o...
1,540
527
import torch import torch.nn as nn import torchvision.models as models import numpy as np class EncoderCNN(nn.Module): def __init__(self, embed_size): super(EncoderCNN, self).__init__() resnet = models.resnet50(pretrained=True) for param in resnet.parameters(): param.requires_gr...
1,923
626
"""Items model. """ # Django from django.db import models # Utilities from App.utils.models import BlackMarketModel # Models from .category import Category from .unit import Unit from .owner import Owner class Item(BlackMarketModel): """Items model. Is a model to items we goin to sell """ name = mode...
981
316
import json import time from multiprocessing import Process from utils.paths import PATHS from years.AoC2021.tasks import TASKS2021 # Constants PARALLEL_COMPUTATION = True TASKS = { 2021: TASKS2021 } def asses_task(task: type, answers: dict, year: int) -> None: """ Run a task 4 times (part 1 test, part 1...
2,241
770
# Copyright (c) 2020 PaddlePaddle 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 appli...
1,467
469
import typing from commercetools import schemas, types from commercetools.services import abstract from commercetools.typing import OptionalListStr __all__ = ["TypeService"] class TypeDeleteSchema(abstract.AbstractDeleteSchema): pass class TypeQuerySchema(abstract.AbstractQuerySchema): pass class TypeSe...
4,262
1,162
import random import cv2 import numpy as np from augraphy.base.augmentation import Augmentation class NoiseTexturize(Augmentation): """Creates a random noise based texture pattern to emulate paper textures. Consequently applies noise patterns to the original image from big to small. :param sigma_range:...
3,454
984
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright: (c) 2021, kevin-dot-g-dot-stewart-at-gmail-dot-com # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Version: 1.0.1 #### Updates: #### 1.0.1 - added 9.0 support # - changed max version # - added clie...
50,333
13,771
""" This module defines pipelines - sets of tasks in nemo that we sometimes want to do on different inputs (e.g., real data or simulated data). """ import os import sys import glob import shutil import time import astropy.io.fits as pyfits import astropy.table as atpy from astLib import astWCS import numpy as np fro...
52,854
15,569
#!/usr/bin/env python ''' This program is free software; you can redistribute it and/or modify it under the terms of the Revised BSD License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FO...
5,026
1,915
import time print (time.strftime("%B %e, %Y")) # Guides: # how to formate date: # http://strftime.net/ # how to use time: # http://www.cyberciti.biz/faq/howto-get-current-date-time-in-python/
194
84
import re with open('input.txt', 'r') as f: pw_ok=0 for line in f: (rule,s,space_and_pw) = line.partition(':') (lowhigh,s,c) = rule.partition(' ') (low,s,high) = lowhigh.partition('-') pw=space_and_pw[1:-1] c1=pw[int(low)-1] c2=pw[int(high)-1] if (c1==c ...
514
229
# Copyright (c) 2019, CRS4 # # 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, distribu...
8,399
2,571
"""Global config management This module provides functions for initializing, accessing and destroying a global config object. You can initialize a global config from any object. However, in the context of pyppy, only the instance attributes of the object are used and work with the decorators ``fill_args`` and ``condit...
4,772
1,228
def three_sum(nums): """ Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. :param nums: list[int] :return: list[list[int]] """ if len(nums) < 3: return [] nums.sort() ...
878
323