text
string
size
int64
token_count
int64
__author__ = "Otto van der Himst" __credits__ = "Otto van der Himst, Pablo Lanillos" __version__ = "1.0" __email__ = "o.vanderhimst@student.ru.nl" import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np import datetime import sys import gym import ...
36,252
11,994
from abc import ABC, abstractmethod from typing import List from BribeNet.helpers.bribeNetException import BribeNetException class BriberyActionExecutedMultipleTimesException(BribeNetException): pass class BriberyActionTimeNotCorrectException(BribeNetException): pass class BriberyAction(ABC): def __...
2,465
677
# Copyright 2019 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 copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
4,269
1,526
from serial import Serial from time import sleep from telnetlib import Telnet from logging import debug class TimeoutError(Exception): """An error to be thrown for a movement timeout""" pass # TODO: Can I check which axis are connected in open_x? class Micronix_Device(): """Class for controlling Micronex...
9,748
2,711
import functools from unittest import TestCase import ddt from hamcrest import assert_that, equal_to, raises from storops.exception import SystemAPINotSupported from storops.lib.resource import Resource from storops.lib.version import version, Criteria from storops_test.unity.rest_mock import t_rest, patch_rest from ...
7,151
2,333
""" .. See the NOTICE file distributed with this work for additional information regarding copyright ownership. 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....
2,251
746
""" A collection of generic functions and iterators intended for use in various parts of the App, and will probably be of use to future development. """ from importlib import import_module as imp from os import listdir, path import sys import functools import click class periods(): """ Iterator for financia...
7,625
2,378
import os import cflearn import platform import unittest import numpy as np from typing import Dict from cflearn_benchmark import Benchmark from scipy.sparse import csr_matrix from cftool.ml import patterns_type from cftool.ml import Tracker from cftool.ml import Comparer from cftool.misc import timestamp from cfdata...
5,157
1,532
""" Various utils """ import json import socket def jprint(anything): """ pprint() alternative """ print(json.dumps(anything, default=str, sort_keys=True, indent=4)) def resolve_host(hostname): """ Resolve hostname """ try: return socket.gethostbyname(hostname) except soc...
352
118
class BaseBond(object): def __init__(self): super(BaseBond, self).__init__()
90
32
import json from final.model import model import os import numpy as np import tensorflow as tf import jieba from tqdm import tqdm import ahocorasick from gensim.models import Word2Vec os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE" path = os.getcwd() graph = tf.get_default_graph() train_data = json.load(open(path + '/dat...
6,117
2,440
import os from collections import defaultdict import logging from operator import itemgetter from pathlib import Path from typing import List, Optional, Tuple, Dict, Iterable, Iterator import time import numpy as np import torch as T import torch.nn as nn import torch.nn.functional as F import torch.optim as optim fro...
16,976
5,745
from .structures import format_vector, add_size, save_screen_data_to_img, Border, QuadNode from .collision_detection import create_collision_detection from .config_utils import deep_merge_dicts from .tool import * from .colors import *
236
73
import uuid def generate_uuid4() -> uuid.UUID: return _generate_uuid4() def _generate_uuid4() -> uuid.UUID: # Defined as a private method for easy monkeypatching return uuid.uuid4() def bytes_to_uuid(data: bytes) -> uuid.UUID: return uuid.UUID(bytes=data.rjust(16, b"\0"))
295
116
"""Maximize_product_of_arry(array series#2), Codewars Kata, level 7.""" def max_product(li, n): """Return maxima(not maximum) product from a list from the set number. input: list of integers output: integer, product of given integers ex: maxProduct ({4,3,5} , 2) returns return 20 since the s...
475
167
from tensorflow.keras.optimizers.schedules import *
52
16
from pyramid.view import view_config from pyramid.request import Request import pyramid.httpexceptions as x # /project/{package_name}/ @view_config(route_name='package_details', renderer='pypi:templates/packages/details.pt') @view_config(route_name='package_details/', renderer='pypi:template...
1,874
582
import Crypto import Crypto.Random from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA256 import binascii import sys def main(my_pass): random_gen = Crypto.Random.new().read _private_key = RSA.generate(2048, random_gen) _public_key = _private_key.publickey(...
1,043
445
"""Unit test subpackage for numpy-lapacke-demo.regression. .. codeauthor:: Derek Huang <djh458@stern.nyu.edu> """
115
47
class EmptyException(Exception): """Raised when the input value is too large""" pass class ArrayStack: # Space used: O(n) def __init__(self): self._data = [] # O(1) def __len__(self): return len(self._data) # O(1) def is_empty(self): return len(self._data) == 0 # O(1...
2,515
852
import abstract __version__ = "2.1.100"
40
18
people = ['Jonas', 'Julio', 'Mike', 'Mez'] ages = [25, 30, 31, 39] position = 0 while position < len(people): person = people[position] age = ages[position] print(person, age) position += 1
206
82
def fun(x): if x > 1: return 0 else: return "str"
74
30
#!/usr/bin/env python # Written by Andrew Dalke # Copyright (c) 2008 by Dalke Scientific, AB # Modified by Jim Pivarski, 2016 # # (This is the MIT License with the serial numbers scratched off and my # name written in in crayon. I would prefer "share and enjoy" but # apparently that isn't a legally acceptable.) # #...
13,215
4,601
class Vaga: def __init__( self, titulo, descricao, salario, local, quantidade, contato, tipo_contratacao, tecnologias, ): self.__titulo = titulo self.__descricao = descricao self.__descricao = descricao self....
1,870
597
# flake8: noqa from triad.utils.assertion import assert_arg_not_none, assert_or_throw from triad.utils.hash import to_uuid from triad.utils.iter import make_empty_aware
169
58
#Opening file filename=open('words.txt') for line in filename: print(line.upper().rstrip()) filename.close() second_file=open('mbox.txt') sum=0 count=0 for line in second_file: if line.startswith("X-DSPAM-Confidence:"): sum=sum+float(line[-7:-1]) count=count+1 print("Average sp...
352
135
# -*- coding: utf-8 -*- """ Created on Fri Aug 28 15:27:21 2020 @author: Cb """ import numpy as np import pandas as pd import baupy as bp # #%% path = 'C:/Users/CB.MAGMA/Documents/GitHub/baupy/kennwerte.xlsx'# r'/home/cb/Dokumente/GitHub/baupy/kennwerte_streichholzstrasse.txt' container = bp.kennwerte(...
401
184
#!/usr/bin/env python # encoding: utf-8 # # Copyright (c) 2008 Doug Hellmann All rights reserved. # """ """ __version__ = "$Id$" #end_pymotw_header import string values = { 'var':'foo' } t = string.Template("$var is here but $missing is not provided") try: print 'substitute() :', t.substitute(values) excep...
425
158
from django.apps import AppConfig class MeConfig(AppConfig): name = 'me'
79
26
""" ASGI config for authentik project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/ """ import django from channels.routing import ProtocolTypeRouter, URLRouter from defusedxml import ...
2,196
680
from struct import unpack_from from typing import Iterable as IterableT, TypeVar, Union, Dict from ..datasheet import DataRowBase, IDataSheet, IDataRow from ..column import Column from ..relational import IRelationalDataRow from ..relational.datasheet import IRelationalDataSheet class SubRow(DataRowBase, IRelational...
4,922
1,529
from .. import toolz from ..searching import get_many, equals from ..transformations import rescale_exchange from functools import partial def get_generators_in_mix(db, name="market for electricity, high voltage"): """Get names of inputs to electricity mixes""" inputs = set() for act in db: if act...
9,874
3,087
# Copyright (c) 2020-2021, Manfred Moitzi # License: MIT License from pathlib import Path import ezdxf from ezdxf.render.forms import sphere DIR = Path("~/Desktop/Outbox").expanduser() doc = ezdxf.new() doc.layers.new("form", dxfattribs={"color": 5}) doc.layers.new("csg", dxfattribs={"color": 1}) doc.layers.new("no...
634
268
from typing import Any, Type import pytest from philipstv import ( PhilipsTVAPI, PhilipsTVAPIMalformedResponseError, PhilipsTVAPIUnauthorizedError, PhilipsTVError, ) from philipstv.model import ( AllChannels, AmbilightColor, AmbilightLayer, AmbilightMode, AmbilightModeValue, Am...
12,595
4,222
from django.contrib import admin from metrics.models import InventoryProduct class InventoryAdmin(admin.ModelAdmin): pass admin.site.register(InventoryProduct)
169
47
from airflow.models import DAG from rockflow.dags.const import * from rockflow.dags.symbol import MERGE_CSV_KEY from rockflow.operators.logo import * with DAG("public_logo_download", default_args=DEFAULT_DEBUG_ARGS) as public: PublicLogoBatchOperator( from_key=MERGE_CSV_KEY, key=public.dag_id, ...
1,277
445
import matplotlib.pyplot as plt # from copy import deepcopy import numpy as np from mvmm.viz_utils import set_xaxis_int_ticks def plot_opt_hist(loss_vals, init_loss_vals=None, loss_name='loss value', title='', step_vals=None, inches=10): loss_val_diffs = np.diff(loss_vals) ...
1,651
644
# a hacky smoke test that sends a file from one chrome window to another. # docker build -t ww-selenium . # docker run --rm -it -v $PWD:$PWD -w $PWD ww-selenium python3 ./smoke.py # it isn't much but it's start. # TODO: # - use go package / go test # - run the server # - eventually smoke test *all* client com...
2,537
908
"""matwrap.py: wrapper around matplotlib.""" import json import warnings from pkg_resources import resource_filename class MatWrap: _rc_defaults_path = resource_filename("shinyutils", "data/mplcfg.json") with open(_rc_defaults_path, "r") as f: _rc_defaults = json.load(f) _mpl = None _plt = N...
2,696
890
keys_map = { 'A':'2', 'B':'2', 'C':'2', 'D':'3', 'E':'3', 'F':'3', 'G':'4', 'H':'4', 'I':'4', 'J':'5', 'K':'5', 'L':'5', 'M':'6', 'N':'6', 'O':'6', 'P':'7', 'Q':'7', 'R':'7', 'S':'7', 'T':'8', 'U':'8', 'V':'8', 'W':'9', 'X':'9', 'Y':'9', 'Z':'9', } n = int(input()) f...
649
329
# Get executables import os import shutil import pymake from framework import running_on_CI if running_on_CI(): print("running on CI environment") os.environ["PYMAKE_DOUBLE"] = "1" # paths to executables for previous versions of MODFLOW ebindir = os.path.abspath( os.path.join(os.path.expanduser("~"), "....
3,078
1,142
__version__ = "0.1.0" from .region import MaxPHeuristic from .region import RegionKMeansHeuristic from .region import Skater from .region import WardSpatial from .region import Spenc from .region import w_to_g from .region import AZP
236
78
from .Node import Node from .BooleanNode import BooleanNode from .MappingNode import MappingNode from .Matrix import Matrix from .NumberNode import IntegerNode from typing import Any, Dict, List class Strategy(MappingNode): def __init__(self, info: Dict[str, Any]): assert isinstance(info, dict) converted: Di...
949
281
from django.core import validators from django.utils.translation import ugettext_lazy as _ from django.utils.deconstruct import deconstructible MONTH_MAP = { 'JAN': 1, 'FEB': 2, 'MAR': 3, 'APR': 4, 'MAY': 5, 'JUN': 6, 'JUL': 7, 'AUG': 8, 'SEP': 9, 'OCT': 10, 'NOV': 11, '...
4,216
1,292
import re import pytest import numpy as np import discretisedfield as df import micromagneticmodel as mm from .checks import check_term class TestRKKY: def setup(self): self.valid_args = [(1, ['a', 'b']), (-1, ['a', 'bc']), (0, ['r1', 'r2'])] s...
1,103
357
import pytest import kkt from kkt.exception import MetaDataNotFound from kkt.commands.status import status, status_impl @pytest.mark.parametrize( "given, expected", [ ( {"status": "complete", "failureMessage": None, "user": "user"}, "status: complete", ), ( ...
1,048
339
__author__ = 'Denver' import sys import logging from datetime import datetime # sys.path.append('/home/denver/Documents/ODM2PythonAPI') from odm2api.ODMconnection import dbconnection from odm2api.ODM2.services import * logger = logging.getLogger('SDL_logger') class Database: ''' This class uses the ...
3,813
1,031
''' A working example for signals from Anymal Plots x,y,z in position and the yaw angle ''' import numpy import sys sys.argv = ['test'] import tf def getYawDegrees(msg): '''yaw degrees''' quaternion = ( msg.pose.pose.orientation.x, msg.pose.pose.orientation.y, msg.pose.pose.orienta...
1,460
574
# -*- coding: utf-8 -*- # @Time : 20-6-9 上午10:20 # @Author : zhuying # @Company : Minivision # @File : anti_spoof_predict.py # @Software : PyCharm import cv2 import math import numpy as np class FaceModel: def __init__(self): caffemodel = "./resources/detection_model/Widerface-RetinaFace.caffemodel" ...
1,366
514
#!/usr/bin/env python import argparse __author__ = 'kinpa200296' def check_if_sorted(filename, ascending=True): with open(filename, 'r') as f: s = f.readline() if s == '': return True prev = int(s) s = f.readline() while s != '': cur = int(s) ...
1,160
337
# Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. """IPVS module This mod...
21,645
7,300
""" Set module shortcuts and globals """ version = ['0', '9', '1'] __version__ = '.'.join(version) pynetdicom_version = 'PYNETDICOM3_' + ''.join(version) # UID prefix provided by https://www.medicalconnections.co.uk/Free_UID pynetdicom_uid_prefix = '1.2.826.0.1.3680043.9.3811.' + '.'.join(version) import logging fro...
810
303
import torch from torch import nn from torch.nn import functional as F class GQN_Pool(nn.Module): def __init__(self, representation_dim, covariate_dim, net=None, **kwargs): assert representation_dim == 256 assert (isinstance(net, nn.Identity) or (net is None)) super(GQN_Pool, self).__init_...
1,814
762
import requests from bs4 import BeautifulSoup url = 'https://weather.com/weather/tenday/l/' param = 'b757e0078b0b135DetailsSummary--tempValue--RcZzi0973ea8930d24ef111c7b8457939f4e2046fc8bbe48119f17' response = requests.get(url + param) print(response.text) soup = BeautifulSoup(response.text, 'html.parser') dateTime...
622
263
import random as r import cv2 import numpy as np from skimage.util import random_noise def create_figs(image, image_pre_result, no_of_objects=1): for i in range(no_of_objects): width = r.randint(0, image.shape[0] / 2) height = r.randint(0, image.shape[1] / 2) xpos = r.randint(0, ...
2,857
1,109
from datetime import datetime import datetime as dt import shlex import os from auxiliary_shared import strfdelta from config import SPEC_DIR import respy def get_actual_evaluations(): with open('est.respy.info', 'r') as infile: for line in infile.readlines(): list_ = shlex.split(line) ...
3,697
1,267
import json import requests import sys from datetime import date from datetime import datetime from elasticsearch import Elasticsearch from time import sleep from veggie_utils import * from elastic_utils import es_connect with open('flow_conf.json') as json_file: conf = json.load(json_file) override_conf_from_en...
1,925
697
import datetime from .common import db, timeformat class Revisions(db.Model): """ After the admin views the reports, they will make a revision record. The table is connected to `Records`, `Users` and `Statuses`. id: PK. record_id: `id` in `Records` table. user_id: `id` in `Users` table. s...
2,006
638
from sds011sensor import * import aqi import time from datetime import datetime import argparse import os import csv import timeit from sense_hat import SenseHat #Initate arg parser my_parser = argparse.ArgumentParser(description='Input Parameters') #Create args my_parser.add_argument('-a', t...
3,093
1,172
#!/usr/bin/env python """Run Gammapy validation: CTA 1DC""" import logging import yaml import matplotlib.pyplot as plt from gammapy.analysis import Analysis, AnalysisConfig def target_config3d(config_file, target_config_file, tag): """Create analyis configuration for out source.""" targets_config_ = yaml.safe_...
4,373
1,595
from flask import Blueprint, render_template, request, session, redirect, current_app, Markup, jsonify import sqlite3 import os from static.classes.User import User, encryptPassword, decryptPassword from cryptography.fernet import Fernet authentication_blueprint = Blueprint("authentication_blueprint", __name__, templa...
6,805
1,728
# -*- coding: utf-8 -*- import llbc class pyllbcProperty(object): """ pyllbc property class encapsulation. property can read & write .cfg format file. file format: path.to.name = value # The comments path.to.anotherName = \#\#\# anotherValue \#\#\# # The comments too Property clas...
6,487
1,851
""" NER for sermons in content.dat """ import os import pandas as pd import numpy as np from polyglot.text import Text import nltk.data from nltk.stem.snowball import DanishStemmer stemmer = DanishStemmer() if __name__ == "__main__": """ First processing to create NER outputs """ df = pd.read_csv(os.pa...
2,944
935
""" Find the Minimum, Maximum, Length and Average Values Create a function that takes a list of numbers and returns the following statistics: Minimum Value Maximum Value Sequence Length Average Value """ def minMaxLengthAverage(lst): return [min(lst), max(lst), len(lst), sum(lst)/len(lst)] """ Return the Sum of ...
794
243
# dilated_convolution.py from __future__ import absolute_import from __future__ import division from __future__ import print_function from layers.normalization import InstanceNormalization from typing import Tuple, Union import tensorflow as tf class DilatedConv2D(tf.keras.layers.Layer): def __init__(self, fil...
2,994
979
# -*- coding: utf-8 -*- from odoo import models, fields,api class LibraryBook(models.Model): _name = 'library.book1' _description = 'Library Book' _order = 'date_release desc, name' name = fields.Char('Title', required=True) short_name = fields.Char('Short Title', required=True) date_release ...
1,605
530
with open("data/input_1.txt", 'r') as f: input_data = f.readlines() data = [int(i.replace("\n", "")) for i in input_data] print(len(data)) def part_1(): for i in data: for j in data: if i + j == 2020: print(i * j) def part_2(): for i in data: ...
472
175
import pyttsx3 import PyPDF2 from tkinter.filedialog import * #Ask for book file book_file=askopenfilename() pdfreader=PyPDF2.PdfFileReader(book_file)#Initialize Reading the pdf file num_pages=pdfreader.numPages#Finds the number of pages in that book #Now iterate through each and every page and convert that to ...
661
216
""" MACed Message with Recipients COSE_Mac = [ Headers, payload : bstr / nil, tag : bstr, recipients :[+COSE_recipient] ] """ from typing import Optional, List import cbor2 from cose import CoseMessage from cose.messages import cosemessage, maccommon from cose.attributes.algorithms import Co...
2,857
904
#!/usr/bin/env python """ Background: -------- oer_glidervsCTD_plot.py Purpose: -------- History: -------- """ import argparse, os import numpy as np import calc.aanderaa_corrO2_sal as optode_O2_corr from plots.profile_plot import CTDProfilePlot import io_utils.EcoFOCI_netCDF_read as eFOCI_ncread # V...
8,083
3,276
#! /usr/bin/python3 """Delete all Operators from the Quay Snyk Operator repository Args: username (str): Quay username password (str): Quay password """ from requests import get, delete from json import loads from get_quay_token import getQuayToken from typing import List, Dict from sys import argv Package ...
1,551
495
import sys import pandas as pd import sherpa from schools3.config import base_config from schools3.data.features.processors.impute_null_processor import ImputeNullProcessor, ImputeBy from schools3.data.features.processors.composite_feature_processor import CompositeFeatureProcessor from schools3.data.features.processor...
4,009
1,242
# Computations def multiply_a_list_by(a_list, number): """Return a list with every item multiplied by number.""" return [item * number for item in a_list] def square_a_list(a_list): """Return a list with every item squared.""" return [item * item for item in a_list] # Constants PI = 3.14159 AVOGADRO...
623
222
#!/usr/bin/env python # # Download GitHub Issued and PR as CSV # # written by Andreas 'ads' Scherbaum <andreas@scherbaum.la> # # version: 0.5 2016-08-27 # initial version # 1.0 2016-09-04 # update help # add options # remov...
11,031
3,549
from django.apps import AppConfig class UnitsConfig(AppConfig): name = 'units'
85
27
from setuptools import setup setup( name='sram_tools', version='0.1', py_modules=['sram_tools'], python_requires='>=3.6', install_requires=[ 'Click', 'pillow', 'matplotlib' ], entry_points=''' [console_scripts] sram_tools=sramanalyzer:cli ''', )
319
116
import uuid import pytest from util.security.secret import convert_secret_key @pytest.mark.parametrize( "config_secret_key, expected_secret_key", [ pytest.param("somesecretkey", b"somesecretkeysomesecretkeysomese", id="Some string"), pytest.param("255", b"\xff" * 32, id="Some int that can be ...
1,035
414
# -*- coding: utf-8 -*- from __future__ import unicode_literals from os import environ, path from .client import GoogleCalClient SCOPES = ['https://www.googleapis.com/auth/calendar'] GOOGLE_AUTH_FILENAME = environ['GOOGLE_AUTH_FILENAME'] GOOGLE_AUTH_FILEPATH = path.abspath(path.join(path.dirname(__file__), './{}'.fo...
411
160
import os import time import pyodbc from azure.common.credentials import ServicePrincipalCredentials from azure.mgmt.resource import ResourceManagementClient from azure.mgmt.sql import SqlManagementClient from dotenv import find_dotenv, load_dotenv load_dotenv(find_dotenv()) class Database: def __init__( ...
17,403
4,807
"""A sample custom HTTP server.""" import functools import html import traceback import collect import server server.Logger.name = __file__ HTML_TMPL = '''\ <html> <head> <link rel="stylesheet" type="text/css" href="/myStyle.css"/> </head> <body id="consolas"> %s</body> </html> ''' LINK_HOME = '<a href="/">Home<...
3,395
1,172
""" Handlers for CRUD operations on /projects/{*}/tags/{*} """ import logging from aiohttp import web from .._meta import api_version_prefix as VTAG from ..login.decorators import RQT_USERID_KEY, login_required from ..security_decorators import permission_required from .projects_db import APP_PROJECT_DBAPI, Project...
1,512
520
# classes from Air import Air from CO2 import CO2 from Steam import Steam from Gas import Gas # packages # ...
113
37
import argparse import os import sys import logging from audioToJummbox import converter def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("infile", help="The audio file to convert") parser.add_argument("--base", "-b", default="./resources/template.json", help="The file used as the b...
1,362
435
def func(arg1, arg2): arg1 = 20 arg2 = arg2[:] arg2[0] = 10 print('arg1', arg1) print('arg2', arg2) ten = 10 l = [1, 2, 3] func(ten, l) print("ten:", ten) print("l:", l)
194
105
# -*- coding: UTF-8 -*- import time import pygame from pygame.locals import * from constants import BLACK, GAME_WIDTH, HQ_LOCATIONS from helpers import create_save_state, erase_save_state, is_half_second, load_save_states, copy_save_state from text import create_prompt, MenuBox, MenuGrid, TextBox MAIN_MENU = [ ...
18,680
5,988
# -*- encoding: utf-8 -*- # # Copyright © 2021 Mergify SAS # # 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 applicabl...
5,951
1,857
from django.apps import AppConfig class HashConfig(AppConfig): name = 'hash'
83
26
from django.urls import path from . import views app_name = "groups" urlpatterns = [ path("", views.GroupListView.as_view(), name="group-list"), # group path("<int:pk>", views.GroupDetailView.as_view(), name="group-detail"), path("create/", views.GroupCreateView.as_view(), name="group-create"), p...
1,033
352
# Copyright (C) 2010-2014 Cuckoo Foundation. # This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org # See the file 'docs/LICENSE' for copying permission. # Note: This is unmodified from the Cuckoo Windows version class CuckooError(Exception): pass class CuckooPackageError(Exception): pass
315
107
# baseline2D.py # baseline method for problems using the Cross2D object import math import torch import argparse from src.utils import normpdf from src.initProb import * from src.OCflow import ocG from src.plotter import * parser = argparse.ArgumentParser('Baseline') parser.add_argument( '--data', choices=['soft...
5,792
2,235
# Do not edit this file directly. # It was auto-generated by: code/programs/reflexivity/reflexive_refresh load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file") def emsdk(): http_archive( name = "emsdk", sha256 = "c9eb...
600
301
from mbus_h import * from mbus_telegram import * from exceptions import * class MBusControlFrame(MBusTelegram): def __init__(self, dbuf=None): self.base_size = MBUS_FRAME_BASE_SIZE_CONTROL return def compute_crc(self): return (self.control + self.address + self.control_information) % 256 def check_crc(sel...
1,419
535
L = list(map(int,input().split())) a = int(input()) L.sort(reverse= True) k = -1 for i in range(len(L)): if L[i] == a: k = i+1 D = [[1,5,'A+'],[6,15,'A0'],[16,30,'B+'],[31,35,'B0'],[36,45,'C+'],[46,48,'C0'],[49,50,'F']] for i in D: if i[0] <= k <= i[1]: print(i[2]) break
303
162
defendPoints = [{"x": 35, "y": 63},{"x": 61, "y": 63},{"x": 32, "y": 26},{"x": 64, "y": 26}]; summonTypes = ["soldier","soldier","soldier","soldier","archer","archer","archer","archer"]; def summonTroops(): type = summonTypes[hero.built.length % summonTypes.length] if hero.gold >= hero.costOf(type): ...
1,036
395
import types import numpy as np import torch import math from torch import nn, optim import torch.nn.functional as F from torch.autograd.variable import Variable CROSS_ENTROPY_ONE_HOT_WARNING = False def to_categorical(y, num_classes=None, dtype='float32'): """Converts a class vector (integers) to bina...
33,996
11,126
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import os MODULE_BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # asset paths ASSETS_BASE_DIR = os.path.join(MODULE_BASE_DIR, "assets") AUDIO_ASSETS_DIR = os.path.join(ASSETS_BASE_DIR, "audio") TEXT_DIR = os.path.join(ASSETS_BASE_DIR, ...
1,178
518
# -*- coding: utf-8 -*- __title__ = 'transliterate.tests.data.default' __author__ = 'Artur Barseghyan' __copyright__ = '2013-2018 Artur Barseghyan' __license__ = 'GPL 2.0/LGPL 2.1' latin_text = u"Lorem ipsum dolor sit amet" armenian_text = u'Լօրեմ իպսում դօլօր սիտ ամետ' cyrillic_text = u'Лорем ипсум долор сит амет' ...
1,639
873
#%% import time import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from neo_orb_fffi import * from os import path import exportfig #basedir = '/home/calbert/net/cobra/ipp/ishw19/scripts' basedir = '.' zs = np.load(path.join(basedir, 'z.npy')) var_tips = np.load(path.join(base...
5,510
2,899
# clac edge import os from edge_detector import * from PIL import Image # import torch from image_transform import ImageTransform from config import * # from matplotlib import pyplot as plt # import glob # import numpy as np import argparse ''' python extract_edges.py --img_dir --dest_dir img_dir = './dog-breed-...
2,177
783