text string | size int64 | token_count int64 |
|---|---|---|
from molsysmt._private.exceptions import *
from molsysmt.item.openmm_GromacsGroFile.is_openmm_GromacsGroFile import is_openmm_GromacsGroFile as is_form
from molsysmt.item.openmm_GromacsGroFile.extract import extract
from molsysmt.item.openmm_GromacsGroFile.add import add
from molsysmt.item.openmm_GromacsGroFile.append... | 3,398 | 1,327 |
#%%
from itertools import permutations, product
# %%
A =['a','b']
Z = ['x','z']
[p for p in product('ab', range(3))]
[p for p in product(A,Z)]
[p for p in product(A, repeat=3)]
# %%
msg = 'Good Morning Rosa!'
msgList = msg.split()
[' '.join(p) for p in permutations(msgList,3)]
# %%
# complex phrase
s = """Find text... | 523 | 200 |
__all__ = ['IP2Loc']
import IP2Location
from .update_ipdb import download
class IP2Loc():
def __init__(self, app=None):
self.ip2loc = None
if app:
self.init_app(app)
def init_app(self, app):
path = app.config['IP2LOC_IPDB_PATH']
if not path.exists():
... | 510 | 183 |
import unittest
from school_api.app import create_app
from school_api.db import create_tables, drop_tables
from school_api.data_generator import test_db
class BaseCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = create_app('test')
def setUp(self):
drop_tables(self.app)... | 521 | 169 |
import json
import datetime
def print_json_log(logger_, level_, message_):
dict_ = {"level": level_, "message": message_, "time": str(datetime.datetime.now())}
json_str = json.dumps(dict_)
getattr(logger_, level_)(json_str)
| 238 | 78 |
# -*- coding: utf-8 -*-
import pytest
from pyisic import NACE2_to_ISIC4
from pyisic.types import Standards
@pytest.mark.parametrize(
"code,expected",
[
("DOESNT EXIST", set()),
("A", {(Standards.ISIC4, "A")}),
("01", {(Standards.ISIC4, "01")}),
("01.1", {(Standards.ISIC4, "011... | 560 | 241 |
#!/usr/bin/env python
def bubble_search_func(data_list):
cnt_num_all = len(data_list)
for i in range(cnt_num_all-1):
for j in range(1,cnt_num_all-i):
if(data_list[j-1]>data_list[j]):
data_list[j-1],data_list[j]=data_list[j],data_list[j-1]
data_list = [54, 25, 93, 17, 77... | 391 | 191 |
from django.urls import path
from custom_user_app.views import (CustomUserLoginView,
CustomUserLogoutView,
CustomUserCreationView,
CustomUserUpdateView,
CustomUserPasswordChangeVie... | 981 | 258 |
import numpy as np
import csv as csv
from clean_data import clean_data
from join_columns import join_columns
from fix_decimals import add_int, cut_decimals
def preprocess_dataset():
preprocess_data('train', False)
preprocess_data('test', False)
preprocess_data('train', True)
preprocess_data('test', Tru... | 2,691 | 1,076 |
# Generated by Django 3.1 on 2020-09-01 20:25
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('sites', '0002_alter_domain_unique'),
('helpme', '0002_category_question'),
]
operations = [
migration... | 1,691 | 481 |
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. 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 requir... | 3,799 | 1,135 |
# Generated by Django 3.2.7 on 2021-09-07 02:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('projects', '0004_location'),
]
operations = [
migrations.AlterField(
model_name='location',
name='location',
... | 382 | 128 |
import numpy as np
from napari_plugin_engine import napari_hook_implementation
from napari_tools_menu import register_function
from napari_time_slicer import time_slicer, slice_by_slice
import napari
from napari.types import ImageData, LabelsData
@napari_hook_implementation
def napari_experimental_provide_function()... | 5,491 | 1,945 |
from order import Order
class OrderManager:
def __init__(self):
self.orders = {}
def user_has_any_order(self, chat_id: int, user: str) -> bool:
order = self.get_order(chat_id)
return order.user_has_any_order(user)
def get_order(self, id: int) -> Order:
if id not in sel... | 487 | 161 |
#!/usr/bin/env python
import os, sys, getopt
TESTNAME="binary"
# generate bindings in this folder
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "k", ["keepfiles"])
except getopt.GetoptError as e:
print str(e)
sys.exit(127)
k = False
for o, a in opts:
if o in ["-k", "--keepfiles"... | 2,576 | 940 |
from django.contrib import admin
# Register your models here.
from Box.models import Player, ObservationList, Comments, ObservationForm
class PlayerAdmin(admin.ModelAdmin):
list_display = ['first_name', 'last_name', 'year_of_birth', 'club', 'position', 'status', 'mail', 'phone', 'agent']
class ObservationListA... | 1,024 | 320 |
from datetime import datetime
from CompanyProblemSolver import CompanyProblemSolver
class TimedSolution:
def __init__(self, J):
time_start = datetime.now()
solver = CompanyProblemSolver(J, displayProgress=True)
time_end = datetime.now()
self.duration = float((time_end - time_start).... | 992 | 291 |
import datetime
import re
from app import db
from bson.objectid import ObjectId
from pymongo import InsertOne, UpdateOne
from pymongo.errors import BulkWriteError
from app.error.factoryInvalid import FactoryInvalid
class Model(object):
def __init__(self, id=None, name=None):
if name is None:
n... | 2,528 | 737 |
from __future__ import print_function, division, absolute_import, unicode_literals
from numbers import Number
import numpy as np
from voluptuous import Schema, Required, Any, Range
from mitxgraders.comparers.baseclasses import CorrelatedComparer
from mitxgraders.helpers.calc.mathfuncs import is_nearly_zero
from mitxgra... | 9,087 | 2,816 |
filename = "day8.txt"
ops = {"inc": "+=", "dec": "-="}
# Initialise registers to zero
regs = {}
with open(filename) as f:
for line in f.readlines():
data = line.split(' ')
reg = data[0]
if reg not in regs:
regs[reg] = 0
# Follow the instructions
maxReg = 0
with open(filename) ... | 642 | 223 |
"""deCONZ service tests."""
from unittest.mock import Mock, patch
from homeassistant.components.unifi.const import DOMAIN as UNIFI_DOMAIN
from homeassistant.components.unifi.services import (
SERVICE_REMOVE_CLIENTS,
UNIFI_SERVICES,
async_setup_services,
async_unload_services,
)
from .test_controller ... | 4,755 | 1,702 |
"""
This is the settings file that you use when you're working on the project locally.
Local development-specific include DEBUG mode, log level, and activation of developer tools like django-debug-toolsbar
"""
from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# SECURI... | 632 | 218 |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 25 05:21:45 2021
@author: bw98j
"""
import prose as pgx
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import seaborn as sns
import numpy as np
import itertools
import glob
import os
from tqdm import tqdm
import ... | 3,094 | 1,305 |
"""Play the game."""
import engine
import numpy as np
board = engine.createBoard(4)
message1 = "Use the keys to move (L)eft (R)ight (U)p (D)own."
message2 = "Press (Q) to quit:"
while True:
print(np.array(engine.showBoard(board)))
inputValue = input("{} {} ".format(message1, message2))
inputValue = str(i... | 428 | 144 |
from ..utils import to_str
class VertexCommand(object):
def __init__(self, command_text):
self.command_text = command_text
def __str__(self):
return to_str(self.__unicode__())
def __unicode__(self):
return u'{}'.format(self.command_text)
class CreateEdgeCommand(object):
def _... | 758 | 235 |
import argparse
import os
import glob
import pandas as pd
from libraryTools import imageRegionOfInterest
#filename,width,height,class,xmin,ymin,xmax,ymax
#20170730_132530-(F00000).jpeg,576,1024,sinaleira,221,396,246,437
valid_images = [".jpg",".gif",".png",".tga",".jpeg"]
def run(image_path, classNameList = ["somecl... | 2,431 | 791 |
import datetime as dt
from functools import cached_property
from typing import Dict, List, Sequence, Union
import numpy as np
import pandas as pd
import WindPy
from tqdm import tqdm
from .DataSource import DataSource
from .. import config, constants, DateUtils, utils
from ..DBInterface import DBInterface
from ..Ticke... | 22,968 | 7,668 |
# Copyright (c) 2021 Sony Group Corporation and Hanjuku-kaso Co., Ltd. All Rights Reserved.
#
# This software is released under the MIT License.
# http://opensource.org/licenses/mit-license.php
import argparse
from distutils.util import strtobool
from pathlib import Path
import pickle
import warnings
from sklearn.exc... | 12,874 | 4,199 |
# coding=utf-8
import serial
import time
import os
KERNEL_PATH = './kernel9.img'
def serial_w(content):
ser.write(content)
time.sleep(1)
port1 = '/dev/pts/4'
port2 = '/dev/ttyUSB0'
if __name__ == "__main__":
ser = serial.Serial(port=port1, baudrate=115200)
kernel_size = os.path.getsize(KERNEL_PATH)... | 856 | 335 |
import configparser
import requests
import json
def get_callback():
#read the config.txt
config = configparser.ConfigParser()
config.read_file(open(r'config.txt'))
API_key = config.get('Basic-Configuration', 'API_key')
city_name = config.get('Basic-Configuration', 'city_name')
# API
base_u... | 1,196 | 426 |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# -----------
# SPDX-License-Identifier: MIT
# Copyright (c) 2021 Troy Williams
# uuid : 633f2088-bbe3-11eb-b9c2-33be0bb8451e
# author: Troy Williams
# email : troy.williams@bluebill.net
# date : 2021-05-23
# -----------
"""
The `repair` command has access to tools th... | 19,970 | 5,892 |
# -*- coding: utf-8 -*-
# This file is part of the Ingram Micro Cloud Blue Connect connect-cli.
# Copyright (c) 2019-2021 Ingram Micro. All Rights Reserved.
import os
import json
from datetime import datetime
from urllib import parse
import requests
from click import ClickException
from openpyxl import Workbook
from... | 29,432 | 9,667 |
import os, time, shutil
def get_used_dirs():
pids = [p for p in os.listdir("/proc") if p.isnumeric()]
res = set()
for p in pids:
try:
path = os.path.realpath("/proc/%s/cwd"%p)
if path.startswith("/tmp/fileshare."):
res.add(path)
except:
pa... | 729 | 239 |
import os
import requests
from nltk.corpus import wordnet as wn
urldir = "urls"
geturls = "http://www.image-net.org/api/text/imagenet.synset.geturls?wnid={wnid}"
if not os.path.isdir(urldir):
os.makedirs(urldir)
with open("base_concepts.txt") as fin:
for line in fin:
concept = line.strip().split("_"... | 1,441 | 466 |
import time
from . import common
from datetime import datetime
from pymongo import MongoClient, ASCENDING, errors
from _datetime import timedelta
# TODO
# - More error handling
# - Refactor
class Database:
def __init__(self):
# getting the configuration
config = common.getConfig()
client =... | 14,665 | 4,318 |
# -*- coding: utf-8 -*-
# Resource object code
#
# Created by: The Resource Compiler for PyQt5 (Qt v5.15.0)
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\x01\x64\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x18\x... | 9,859 | 9,267 |
# Copyright 2021 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, ... | 6,422 | 2,431 |
import argparse
from train_images import run
# generalized ZSL
# CUDA_VISIBLE_DEVICES=0 nohup python -u main.py --dataset AWA1 --few_train False --num_shots 0 --generalized True > awa1.log 2>&1 &
# CUDA_VISIBLE_DEVICES=1 nohup python -u main.py --dataset SUN --few_train False --num_shots 0 --generalized True > sun.lo... | 23,684 | 10,016 |
#!/usr/bin/env python3
"""OVN Central Operator Charm.
This charm provide Glance services as part of an OpenStack deployment
"""
import ovn
import ovsdb as ch_ovsdb
import logging
from typing import List
import ops.charm
from ops.framework import StoredState
from ops.main import main
import advanced_sunbeam_openstac... | 13,514 | 3,971 |
from kivy.app import App
from kivy.config import Config
from kivy.uix.listview import ListItemButton
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.label import Label
from kivy.clock import Clock
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from functools import partial
... | 9,101 | 2,623 |
from marinetrafficapi.models import Model
from marinetrafficapi.fields import TextField, NumberField, RealNumberField
class VesselParticural(Model):
"""Get vessel particulars (including type, dimensions, ownership etc)."""
mmsi = NumberField(index='MMSI',
desc="Maritime Mobile Service ... | 4,113 | 986 |
import os
import sys
import shutil
import csv
import subprocess ... | 8,985 | 2,505 |
#!/usr/bin/env python3
import os
import sys
from run_bpy_script import run_blender_script
def export_fbx(input_blend_file, output=None, **kwargs):
default_args = {
'global_scale': 1e-3
}
default_args.update(kwargs)
kwargs = default_args
run_blender_script('export_fbx.py',
blend_fil... | 957 | 336 |
# -*- coding: utf-8 -*-
'''
Special rule for processing Hangul
https://github.com/kyubyong/g2pK
'''
import re
from g2pk.utils import gloss, get_rule_id2text
rule_id2text = get_rule_id2text()
############################ vowels ############################
def jyeo(inp, descriptive=False, verbose=False):
rule =... | 4,389 | 2,624 |
#!/usr/local/bin/python2.7
##
# OOIPLACEHOLDER
#
# Copyright 2014 Raytheon Co.
##
__author__ = 'Mark Worden'
from mi.dataset.dataset_parser import DataSetDriverConfigKeys
from mi.dataset.dataset_driver import SimpleDatasetDriver
from mi.dataset.parser.flord_l_wfp_sio import FlordLWfpSioParser
from mi.core.versioning ... | 1,136 | 372 |
from django.contrib.gis.db import models
from common.models import (RequiredURLField,
OptionalTextField, RequiredCharField)
from human_services.locations.models import ServiceAtLocation
from search.models import Task
from users.models import User
class Algorithm(models.Model):
url = Req... | 1,150 | 329 |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012-2017 Alex Forencich
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... | 3,485 | 1,587 |
# Generated by Django 2.2.8 on 2020-01-21 09:07
import django.contrib.gis.db.models.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('boundaries', '0006_worldborder'),
]
operations = [
migrations.AlterField(
model_name='worldbo... | 449 | 157 |
entries = [
{
'env-title': 'atari-enduro',
'score': 207.47,
},
{
'env-title': 'atari-space-invaders',
'score': 459.89,
},
{
'env-title': 'atari-qbert',
'score': 7184.73,
},
{
'env-title': 'atari-seaquest',
'score': 1383.38,
... | 551 | 243 |
from typing import Callable
import torch
from autoPyTorch.pipeline.components.setup.network_initializer.base_network_initializer import (
BaseNetworkInitializerComponent
)
class NoInit(BaseNetworkInitializerComponent):
"""
No initialization on the weights/bias
"""
def weights_init(self) -> Call... | 701 | 175 |
from arbre_binaire import AB
from dessiner_arbre import dessiner
def hauteur(arbre):
"""Fonction qui renvoie la hauteur d'un arbre binaire"""
# si l'arbre est vide
if arbre is None:
return 0
hg = hauteur(arbre.get_ag())
hd = hauteur(arbre.get_ad())
return max(hg, hd) + 1
def taille... | 747 | 327 |
from collections import Iterable
from math import log, ceil
from mathsat import msat_term, msat_env
from mathsat import msat_make_constant, msat_declare_function
from mathsat import msat_get_integer_type, msat_get_rational_type, \
msat_get_bool_type
from mathsat import msat_make_and, msat_make_not, msat_make_or, m... | 5,441 | 2,162 |
# Function with Nested IF Else
def printColor(value):
value = value.upper()
if (value == 'Y'):
print "yellow"
elif (value == 'B'):
print "blue"
elif (value == 'R'):
print "red"
else:
print "unknown"
printColor('r') # call function
| 298 | 98 |
from estimators.weighted_edge_estimator import *
from estimators.weighted_node_estimator import *
from estimators.weighted_triangle_estimator import *
from estimators.formula_edge_estimator import *
from estimators.formula_node_estimator import *
from estimators.formula_triangle_estimator import *
| 299 | 91 |
from pandac.PandaModules import Vec3
P3D_VERSION = '0.1'
__version__ = P3D_VERSION
from constants import *
from functions import *
import commonUtils
from object import Object
from singleTask import SingleTask
from nodePathObject import NodePathObject
from pandaObject import *
from pandaBehaviour import PandaBeh... | 673 | 182 |
# !/usr/bin/python
# -*- coding: utf-8 -*-
from project.database import Base
from sqlalchemy.orm import relationship
from sqlalchemy import Column, Integer, String
from flask_login import UserMixin
from project.user.models.rbac_user_mixin import UserMixin as RBACUserMixin
class User(RBACUserMixin, UserMixin, Base):
... | 678 | 232 |
import sys
import os
sys.path.insert(0, '../..')
from nltk.corpus import framenet as fn
import FrameNetNLTK
from FrameNetNLTK import load, convert_to_lemon
my_fn = load(folder='test_lexicon',
verbose=2)
output_path = os.path.join(os.getcwd(),
'stats',
... | 1,477 | 466 |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from statsmodels.stats.weightstats import ttost_paired
data = pd.read_csv(open('combined_data.csv'))
for t in data.index:
if int(data.loc[t, 'Baseline']) == 0:
data.loc[t, 'STF Baseline'] = data.loc[t, 'Succesfully Tracked Features 0... | 1,362 | 529 |
import importlib
from zunzun import CommandRegister
from injector import inject, singleton
from click.core import Group
from zunzun import ListenerConnector
from zunzun import inspect
from pathlib import Path
@singleton
class App:
name = ""
listeners_config: list = []
@inject
def __init__(
se... | 1,829 | 545 |
from __future__ import division
from scitbx.math import principal_axes_of_inertia
from scitbx.array_family import flex
def run():
points = flex.vec3_double([
( 8.292, 1.817, 6.147),
( 9.159, 2.144, 7.299),
(10.603, 2.331, 6.885),
(11.041, 1.811, 5.855),
( 9.061, 1.065, 8.369),
( 7.6... | 775 | 464 |
import bisect
import calendar
import datetime
import pickle
import appdaemon.plugins.hass.hassapi as hass
class Event:
def __init__(self, dt, entity, new):
self.dt = dt
self.entity = entity
self.new = new
def __str__(self):
return "event({0}, {1}, {2})".format(self.dt, self.... | 8,071 | 2,611 |
# Generated by Django 3.1.2 on 2021-01-01 05:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0012_attempted_contests'),
]
operations = [
migrations.CreateModel(
name='Game',
fields=[
('... | 807 | 243 |
"""
Re-running de novo assembly, this time including reads that map to mobile elements.
"""
import os
import sys
# Setup Django environment.
sys.path.append(
os.path.join(os.path.dirname(os.path.realpath(__file__)), '../'))
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from Bio import SeqIO
from experim... | 2,224 | 730 |
class Solution:
def diStringMatch(self, S):
low,high=0,len(S)
ans=[]
for i in S:
if i=="I":
ans.append(low)
low+=1
else:
ans.append(high)
high-=1
return ans +[low]
| 288 | 86 |
from django.contrib import admin
from controle.models import Time, Music
# Register your models here.
admin.site.register(Time)
admin.site.register(Music) | 155 | 43 |
import os
import pdb
import fvm.models_atyped_double as models
import fvm.exporters_atyped_double as exporters
class Output():
def __init__(self, outputDir, probeIndex, sim):
if os.path.isdir(outputDir) == False:
os.mkdir(outputDir)
self.defFile = open(outputDir + 'deformation.dat... | 3,802 | 1,227 |
import logging
from typing import Dict, Union, Optional, Any
from ..models.presets import get_preset_models
from .abstract_trainer import AbstractForecastingTrainer, TimeSeriesDataFrame
logger = logging.getLogger(__name__)
class AutoForecastingTrainer(AbstractForecastingTrainer):
def construct_model_templates(s... | 2,663 | 683 |
class EmailAction:
pass
| 28 | 9 |
# Copyright (c) 2011 X.commerce, a business unit of eBay Inc.
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Piston Cloud Computing, Inc.
# Copyright 2012 Cloudscaling Group, Inc.
# All Rights Reserved.
#
# Licens... | 3,895 | 1,113 |
from __future__ import absolute_import
import errno
import socket
import sys
from future.utils import raise_
from boofuzz import exception
from boofuzz.connections import base_socket_connection
ETH_P_ALL = 0x0003 # Ethernet protocol: Every packet, see Linux if_ether.h docs for more details.
ETH_P_IP = 0x0800 # Et... | 4,417 | 1,382 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django_google_dork.models
import model_utils.fields
import django.utils.timezone
class Migration(migrations.Migration):
replaces = [('django_google_dork', '0001_initial'), ('django_google_dork', '0002... | 4,143 | 1,144 |
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
from torch.autograd import Variable
from torchvision.models import vgg16
from torch.nn.utils.rnn import pack_padded_sequence
class ShowAttendTellModel(nn.Module):
def __init__(self, hidden_size, context_size, vocab_siz... | 5,314 | 1,804 |
from flask import Blueprint, abort, jsonify, render_template
from src.fruit_castle.hadwin.utilities import get_json_data
from .v1.version_1 import v1
from .v2.version_2 import v2
from .v3.version_3 import v3
hadwin = Blueprint('hadwin', __name__, url_prefix='/hadwin',static_url_path='/dist',
static_folde... | 770 | 275 |
import pytest
import friendly_traceback
from friendly_traceback.console_helpers import _get_info
from ..syntax_errors_formatting_cases import descriptions
friendly_traceback.set_lang("en")
where = "parsing_error_source"
cause = "cause"
@pytest.mark.parametrize("filename", descriptions.keys())
def test_syntax_errors... | 636 | 200 |
from itertools import product
from tools.general import load_input_list
def get_new_active_range(current_active_set, dimensions):
lowest = [0] * dimensions
highest = [0] * dimensions
for point in current_active_set:
for i, coord in enumerate(point):
if coord < lowest[i]:
... | 1,783 | 581 |
# -*- coding: utf-8 -*-
import random
import uuid
import silly
def user_test_info():
set_id = str(uuid.uuid1())
rand_name: str = silly.noun()
rand_num: int = random.randint(1, 10000)
username: str = f"{rand_name}-{rand_num}"
first_name: str = silly.verb()
last_name: str = rand_name
passwo... | 1,318 | 441 |
# -*- coding: utf-8 -*-
from numpy import log2
from pickle import load
"""
* Clase que se encarga de ver la información mutua que hay entre dos tokens
* sirve para determinar si es colocación o no
"""
class MI:
def __init__(self):
self.words = load(open("./models/words.d",'r'))
self.ngrams = load(open("./models... | 759 | 328 |
import logging
import os
import subprocess
import sys
from contextlib import contextmanager
from pathlib import Path
from textwrap import dedent
import pytest
from quicken._internal.cli.cli import get_arg_parser, parse_file
from quicken._internal.constants import (
DEFAULT_IDLE_TIMEOUT,
ENV_IDLE_TIMEOUT,
... | 15,762 | 4,721 |
# Copyright 2017. Allen Institute. All rights reserved
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
# following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the follow... | 19,353 | 5,439 |
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
import math
#constants
d=2
h=1
a=0.1
I=1
#Axes
N=100
xmin=0
xmax=4
xx=np.linspace(xmin,xmax,N)
ymin=0
ymax=4
yy=np.linspace(ymin,ymax,N)
zmin=-2
zmax=2
zz=np.linspace(zmin,zmax,N)
X,Z=np.meshgrid(xx,zz)
XX,Y=np.meshgrid(xx,yy)
YY,ZZ=np.... | 4,899 | 2,875 |
#!/usr/bin/env python
import time
import pycozmo
# Last image, received from the robot.
last_im = None
def on_camera_image(cli, new_im):
""" Handle new images, coming from the robot. """
del cli
global last_im
last_im = new_im
def pycozmo_program(cli: pycozmo.client.Client):
global last_im... | 1,151 | 423 |
from functools import reduce
data = []
with open("aoc6.inp") as rf:
sets = []
for l in rf:
if l == "\n":
data.append(sets)
sets = []
else:
sets.append(set([c for c in l.strip()]))
a1 = a2 = 0
for sets in data:
a1 += len(reduce(lambda s1, s2: s1 | s2, s... | 394 | 160 |
import zeep
import logging
logging.getLogger('zeep').setLevel(logging.ERROR)
publicServiceUrl = 'https://api.tradera.com/v3/PublicService.asmx'
appId = 'REPLACE ME WITH TRADERA ID'
appKey = 'REPLACE ME WITH TRADERA KEY'
wsdl = 'https://api.tradera.com/v3/PublicService.asmx?WSDL'
client = zeep.Client(wsdl=wsdl)
au... | 513 | 190 |
import struct
import sys
import binascii
import tarfile
import usb
import recovery
BLOCKS_CNT = 8
if len(sys.argv) < 2:
print("Usage: %s <path>"%sys.argv[0])
exit(0)
infile = sys.argv[1]
if infile[-len(".tar.gz"):] == ".tar.gz":
print("cant open compressed file!")
exit(1)
else:
f = open(infile,... | 1,611 | 696 |
#!/usr/bin/env python3
import webbrowser
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from ghnotifier.notifier import Notifier
from ghnotifier.settings import Settings
class Menu:
GITHUB_NOTIFICATIONS = 'https://github.com/notifications'
def __init__(self):
self.menu =... | 1,075 | 337 |
from django.apps import AppConfig
class EnterpriceConfig(AppConfig):
name = 'enterprice'
verbose_name = '企业' | 118 | 39 |
import tensorflow as tf
########################################################################################################################
# Isometry Loss
########################################################################################################################
def getLoss(inputMeshTensor, restTe... | 1,297 | 400 |
import os
import re
import fnmatch
from logfetch_base import log, is_in_date_range
from termcolor import colored
def find_cached_logs(args):
matching_logs = []
log_fn_match = get_matcher(args)
for filename in os.listdir(args.dest):
if fnmatch.fnmatch(filename, log_fn_match) and in_date_range(args, ... | 1,571 | 515 |
# 二叉树中序遍历的 生成器写法
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def mid_order(root):
if not root: return
yield from mid_order(root.left)
yield root.val
yield from mid_order(root.right)
| 307 | 117 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
##
# @file predict_bw_lstm1.py
# @author Kyeong Soo (Joseph) Kim <Kyeongsoo.Kim@xjtlu.edu.cn>
# @date 2019-04-22
# 2022-03-23 - updated for TensorFlow version 2.6
#
# @brief Predict channel bandwidth.
#
# @remarks This code is based on the nice samp... | 1,485 | 607 |
from src.use_cases.todo import create_todo, update_todo
def test_create_todo(client, user):
payload = {
'title': 'test todo',
'description': 'very long and useful description',
}
todo = create_todo(user.id, payload)
assert todo.id == 1
assert todo.title == payload['title']
def t... | 586 | 184 |
#!/usr/bin/env python
"""Exposes functions to perform a source-to-source transformation
that detects and unrolls loops in the code being analyzed.
"""
"""See the LICENSE file, located in the root directory of
the source distribution and
at http://verifun.eecs.berkeley.edu/gametime/about/LICENSE,
for details on the Ga... | 4,818 | 1,287 |
def factorielle_rec(n: int) -> int:
"""
Description:
Factorielle méthode récursive
Paramètres:
n: {int} -- Nombre à factorielle
Retourne:
{int} -- Factorielle de n
Exemple:
>>> factorielle_rec(100)
9.332622e+157
Pour l'écriture scientif... | 859 | 324 |
from Main import main, __version__ as ESVersion
from argparse import Namespace
import random
from tkinter import Checkbutton, OptionMenu, Tk, LEFT, RIGHT, BOTTOM, TOP, StringVar, IntVar, Frame, Label, W, E, Entry, Spinbox, Button, filedialog, messagebox
def guiMain(args=None):
mainWindow = Tk()
mainWindow.wm... | 8,928 | 2,867 |
# -*- coding: utf-8 -*-
"""
Nipype workflows to co-register anatomical MRI to diffusion MRI.
"""
from src.env import DATA
import nipype.pipeline.engine as pe
from nipype.interfaces.fsl import MultiImageMaths
from nipype.interfaces.utility import IdentityInterface, Select, Split
from nipype.algorithms.misc import Gunzi... | 11,293 | 3,897 |
# coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ApplyIndividualRealnameAuthsReq:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (d... | 14,536 | 8,830 |
from datetime import datetime
from pprint import pprint
from cryptography.fernet import Fernet
from libsvc.utils import pack_data, unpack_data
def pack_data_test():
fkey = Fernet.generate_key()
data = {"today": datetime.today(),
"dog": "cat",
"red": "blue"}
p = pack_data(data, f... | 626 | 215 |
import threading
import queue
import time
def putting_thread(q):
while True:
print('start thread')
time.sleep(10)
q.put(5)
print('sup something')
q = queue.Queue()
t = threading.Thread(target=putting_thread, args=(q,), daemon=True)
t.start()
q.put(0)
print(q.get(), 'first item')... | 361 | 132 |
#!/usr/bin/env python
from __future__ import division, absolute_import, print_function
from future.builtins import super
from iris_sdk.models.activation_status import ActivationStatus
from iris_sdk.models.base_resource import BaseResource
from iris_sdk.models.data.portin import PortInData
from iris_sdk.models.history... | 1,604 | 508 |
from __future__ import unicode_literals
from encodings import utf_8
import imaplib, datetime, time, re, requests, yaml, os, email, glob, shutil, mailbox, smtplib, ssl, hashlib
from zipfile import ZipFile
from email.header import decode_header
from os.path import exists as file_exists
from os.path import basename
from ... | 9,109 | 2,671 |