text
string
size
int64
token_count
int64
km = float(input('Digite qual a distância da sua viagem em km: ')) if km <= 200: preço = km * 0.50 print('O valor da sua viagem é de {:.2f}R$'.format(preço)) else: preço = km * 0.45 print('O valor da sua viagem é de {:.2f}R$'.format(preço))
266
119
import json import kubernetes.config import pytest_bdd import pytest_bdd.parsers import utils.helper pytest_bdd.scenarios('features/metrics_server.feature') @pytest_bdd.when('I wait for metrics-server to be initialized') def wait_until_initialized(kubeconfig): client = kubernetes.config.new_client_from_config...
1,802
594
default = False actions = 'store_true' ENC = 'utf-8'
52
21
import sre_constants as sc import sre_parse as sp import typing import unicodedata from pprint import pprint from RichConsole import groups, rsjoin from .knowledge import CAPTURE_GROUP, LITERAL_STR class RXASTNode: """Current AST generated by sre_parse is badly structured and doesn't suit well for our purposes. So...
10,751
4,110
import torch from torch import nn class UserModel(nn.Module): def __init__(self, filter_sizes, userprofile_size, applist_size, output_size=32, char_embed_size=32, chars_size=6000, out_channel_size=3): super().__init__() # embedding of lines and apps self.embed = nn.Embedd...
2,615
918
from pastila.fields import Field class Schema(object): data = None def __init__(self): self.data = {} def load(self, data): for field, value in data.items(): self.load_to_field(field, value) self.validate() def validate(self): for name, field in self.fie...
952
283
import multiprocessing import time from typing import List from constants import CPU_BIG_NUMBERS from utils import show_execution_time def cpu_bound(number: int) -> int: return sum(i * i for i in range(number)) def find_sums(numbers: List[int]) -> None: with multiprocessing.Pool() as pool: pool.ma...
436
150
from abc import ABCMeta from whatsapp_tracker.bases.selenium_bases.base_selenium_kit import BaseSeleniumKit from whatsapp_tracker.mixins.seleniun_keyboard_press_mixin import SeleniumKeyBoardPressMixin class BaseSeleniumKeyboard(BaseSeleniumKit, SeleniumKeyBoardPressMixin, metaclass=ABCMeta): ...
304
101
import numpy as np from layers import FullyConnectedLayer, ReLULayer, softmax_with_cross_entropy, l2_regularization class TwoLayerNet: """ Neural network with two fully connected layers """ def __init__(self, n_input, n_output, hidden_layer_size, reg): """ Initializes the neural network ...
3,056
976
import numpy as np class Solver: def __init__(self, matrix, vector, initialVector, precision, gamma): self.initialVector = initialVector self.precision = precision self.matrix = matrix self.bVector = vector self.gamma = gamma # lower triangular part ...
3,066
1,003
# Copyright (C) 2013-2014 DNAnexus, Inc. # # This file is part of dx-toolkit (DNAnexus platform client libraries). # # 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...
12,491
3,836
"""Routines to make objects serialisable. Each of the functions in this module makes a specific type of object serialisable. In most cases, this module needs to be imported and the function run in both the serialising and the unserialising environments. Here's a summary (see function documentation for details): mk_...
2,946
1,063
from floxcore.config import Configuration, ParamDefinition class AWSConfiguration(Configuration): def parameters(self): return ( ParamDefinition("region", "AWS Default region"), ParamDefinition("role_arn", "Role (ARN) to be assumed", default="", filter_empty=False), Par...
773
196
from flask import Flask from flask_restful import Api, Resource, reqparse from kuet_teacher_data import get_data app = Flask(__name__) api = Api(app) data = get_data() class Teacher_data(Resource): def get(self,id="CSE"): if(id=='ALL' or id=='all'): return data, 200 for datac in ...
1,769
610
import os import sys sys.path.append(os.path.dirname(__file__) + "/../") from scipy.misc import imread from util.config import load_config from nnet import predict from util import visualize from dataset.pose_dataset import data_to_input cfg = load_config("demo/pose_cfg.yaml") # Load and setup CNN part detector s...
892
300
import datetime import logging import os import warnings import matplotlib.pyplot as plt import numpy as np import pandas as pd from logutils import BraceMessage as __ from tqdm import tqdm import simulators from mingle.models.broadcasted_models import inherent_alpha_model from mingle.utilities.chisqr import chi_squa...
19,771
6,387
import pandas as pd from datetime import datetime, timedelta from bs4 import BeautifulSoup as bs from etl.logger import get_logger from etl.main import ETL logger = get_logger("transform") def transform_data(service: str, data_file: str) -> pd.DataFrame: """ Simple function to guide the request ...
4,910
1,550
# Generated by Django 2.2.24 on 2021-07-19 11:52 import cloudinary.models from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('projects', '0002_project_technologies'), ] operations = [ migrations.AlterField( model_name='profile', ...
646
202
from django.urls import path from academic.views import SectionCreate, SectionUpdate, SectionDelete from .views import ( StudentView, AttendanceMark, AttendanceSearch, AttendanceView, IndividualMarksView, AdmissionCreate, AdmissionView, AdmissionDelete, AdmissionUpda...
3,567
1,165
import os import sys # PATH vars BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) ROOT_DIR = lambda *x: os.path.join(BASE_DIR, *x) APPS_DIR = os.path.join(ROOT_DIR(), "apps") sys.path.insert(0, APPS_DIR) # SECURITY WARNING: keep the secret key used in production secret! SECRET...
5,598
1,913
import happybase from settings.default import DefaultConfig import redis pool = happybase.ConnectionPool(size=10, host='hadoop-master', port=9090) # 召回数据 redis_client = redis.StrictRedis(host=DefaultConfig.REDIS_HOST, port=DefaultConfig.REDIS_PORT, db=...
827
246
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy class AlimamaItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() url = scrapy.Field() img = scrapy.F...
783
282
sign_sock = None vrfy_sock = None MAX_PACKET_LEN = 8192 NOT_BINARY_STR_ERR = -1 MISSING_DELIMITER_ERR = -2 ORIGINAL_MSG_ERR = -3 def Oracle_Connect(): import socket global sign_sock global vrfy_sock sign_sock, vrfy_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM), socket.socket(socket.AF_INET,...
2,516
875
from django.contrib.auth.models import User from django.db import models class Measurement(models.Model): class Meta: db_table = 'measurement' verbose_name = 'Измерение' verbose_name_plural = 'Измерения' name = models.CharField(max_length=10, verbose_name='Единицы измерения') desc...
5,932
1,767
import socket try: from .idarest_mixins import IdaRestConfiguration except: from idarest_mixins import IdaRestConfiguration # idarest_master_plugin_t.config['master_debug'] = False # idarest_master_plugin_t.config['master_info'] = False # idarest_master_plugin_t.config['api_prefix'] = '/ida/api/v1.0' # ida...
11,153
3,339
import logging import json from datetime import datetime from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, Job, CallbackQueryHandler) from telegram import (ChatAction, ParseMode, InlineKeyboardButton, InlineKeyboardMarkup) from peewee import fn import pytz from word...
11,750
3,661
import setuptools from setuptools import setup, find_namespace_packages setuptools.setup( name="small_nn-jcanode", version="0.0.1", author="Justin Canode", author_email="jcanode@my.gcu.edu", description="A small Neural Network Framework", long_description_content_type="text/markdown", url=...
599
193
import os import sys import utils import extras.downloadStats as stats import extras.downloadManuscript as dm import extras.unpaywall as up def main(): # get the configuration parameters from environment variables cosApiToken = os.environ['cosApiToken'] # for accessing COS API emailAddress = os.environ['...
1,829
543
""".""" from django.urls import path, reverse_lazy from account.views import (AccountView, InfoFormView, EditAccountView, AddAddressView, AddressListView, DeleteAddress) from django.con...
1,212
343
#!/usr/bin/env python import os import sys sys.path.insert(0, '/home/nullism/web/dnd.nullism.com/') from main import app conf = {} conf['SECRET_KEY'] = 'CHANGEME' app.config.update(conf) application = app
209
82
#!/usr/bin/env python import logging from binance.spot import Spot as Client from binance.lib.utils import config_logging config_logging(logging, logging.DEBUG) key = "" secret = "" spot_client = Client(key, secret) logging.info( spot_client.sub_account_futures_asset_transfer_history( email="", ...
394
137
# -*- coding:utf-8 -*- import json class JsonUtil(object): def __init__(self, jsonFilePath): with open(jsonFilePath, 'r', encoding='utf-8') as f: self.content = json.load(f) if __name__ == '__main__': pass
236
85
import pytest from jubox import JupyterNotebook, RawCell, CodeCell, MarkdownCell def test_get_tags(): nb = JupyterNotebook([ RawCell("first cell"), RawCell("second cell", tags=["tagged"]), RawCell("third cell", taggs=["Not this", "tagged"]), ]) nb_of_tags = nb.get(tags=["tagged"]...
864
313
# coding: utf-8 #------------------------------------------------------------------------- # Copyright (c) Microsoft. 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 #...
2,453
685
from selenium import webdriver from selenium.webdriver.common.keys import Keys import unittest from time import sleep path="C:\chromedriver.exe" url="http://www.hudl.com/login" #username:nathanyang18@outlook.com #password:test1234 class TestLogin(unittest.TestCase): #Open url def setUp(self): self.driv...
5,556
1,772
from django.contrib.auth.models import User from rest_framework import serializers # MODEL IMPORTS from project.notes.models import Note, NoteItem class UserSerializer(serializers.HyperlinkedModelSerializer): notes = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='note-detail') cla...
1,013
300
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- # vim: tabstop=2 shiftwidth=2 softtabstop=2 expandtab import sys import json import os import urllib.parse import traceback import datetime import boto3 DRY_RUN = (os.getenv('DRY_RUN', 'false') == 'true') AWS_REGION = os.getenv('REGION_NAME', 'us-east-1') KINESIS_STR...
4,286
1,628
from pathlib import Path from src.main import retrieve_soil_composition # This example is base on geodatabase obtain from ssurgo on Ohio area ssurgo_folder_path = Path().absolute().parent / 'resources' / 'SSURGO' / 'soils_GSSURGO_oh_3905571_01' \ / 'soils' / 'gssurgo_g_oh' / 'gSSURGO_OH.gdb' coor...
483
217
class Solution: def combination(self, m, n): if dp[m][n]: return dp[m][n] if m <= n: dp[m][n] = 1 return dp[m][n] if n == 1: dp[m][n] = m return dp[m][n] dp[m][n] = self.combination(m-1, n-1)...
592
249
import unittest from palindrome import is_palindrome class TestPalindrome(unittest.TestCase): def test_even_numbers(self): self.assertTrue(is_palindrome('toot')) def test_odd_numbers(self): self.assertTrue(is_palindrome('tot')) def test_simple_values(self): self.assertTrue(is_pal...
901
313
import requests import json import re def get_course_requirements(course_id): link = "http://fireroad.mit.edu/requirements/get_json/" + course_id r = requests.get(link) j = r.json()["reqs"] return j def get_all_course_requirements(): major_reqs = {} major_id_link = "https://fireroad.mit.edu/requirements/list_...
1,738
680
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import bytes from builtins import chr from builtins import range from builtins import super import random from pprint import pprint from binascii import hexl...
4,423
1,605
from PyQt5 import QtWidgets, QtCore from utils.styling import rename_user_dialog_title_style class RenameUserDialog(QtWidgets.QDialog): def __init__(self, parent=None): super(RenameUserDialog, self).__init__(parent) self.setWindowFlags( QtCore.Qt.Dialog | QtCore.Qt.Customiz...
2,509
787
#!/usr/bin/python import bluetooth, sys, os, re, subprocess, time, getopt BT_BLE = int(os.getenv('BT_BLE', 0)) BT_SCAN_TIMEOUT = int(os.getenv('BT_SCAN_TIMEOUT', 2)) if BT_BLE: from gattlib import DiscoveryService from ble_client import BleClient def parse_argv (myenv, argv): usage = 'Command line args: ...
6,053
1,971
#!/usr/bin/env python import os import sys if not os.getegid() == 0: sys.exit( 'Script must be run as root' ) from pyA20.gpio import gpio from pyA20.gpio import port pin = port.PA12 gpio.init() gpio.setcfg(pin, gpio.OUTPUT) gpio.output(pin, int(sys.argv[1]))
267
115
######################################### # Author: Chenfu Shi # Email: chenfu.shi@postgrad.manchester.ac.uk # BSD-3-Clause License # Copyright 2019 Chenfu Shi # All rights reserved. # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions ...
4,369
1,415
# Year 2022 # Authors: Anais Möller based on fink-broker.org code import os import sys import glob import logging import argparse import numpy as np import pandas as pd from tqdm import tqdm from pathlib import Path from functools import partial from astropy.table import Table from astropy import units as u from astro...
11,501
4,095
#!/usr/bin/python3 '''Day 11 of the 2017 advent of code''' class HexCounter(): '''A hex maze walker object for keeping track of our position''' def __init__(self): self.x = 0 self.y = 0 self.z = 0 self.furthest = 0 def move(self, direction): ...
1,990
717
# Copied from /u/jlu/data/microlens/20aug22os/reduce/reduce.py ################################################## # # General Notes: # -- python uses spaces to figure out the beginnings # and ends of functions/loops/etc. So make sure # to preserve spacings properly (indent). This # is easy to do if you use em...
8,291
3,332
import tkinter as tk from PIL import Image, ImageTk from game import Game from threading import Thread import time from gameSaver import sendFull from Client import DummyAgent class ConsoleAgent: """Agent running in the console for testing only""" def render(self, state): "render the state to the conso...
7,613
2,400
class Solution: def generateMatrix(self, n: int) -> List[List[int]]: matrix = [[None] * n for _ in range(n)] startRow, endRow = 0, n - 1 startCol, endCol = 0, n - 1 count = 1 while startRow <= endRow and startCol <= endCol: for col ...
1,007
295
"""Core classes for motto """ from typing import Any, Callable, ClassVar, Dict, List, Optional, Tuple, Union from typing_extensions import Protocol, TypedDict class Message(object): """Reporting message class. This object is appended for paragraphes by skills. Responsibility is only telling event "what" ...
1,742
549
from diffrascape.env import BadSeeds def test_construct(): bad_seeds = BadSeeds() bad_seeds_states = bad_seeds.states() print(f"### states: {bad_seeds_states}") assert bad_seeds_states["shape"][0] == 6 bad_seeds_actions = bad_seeds.actions() print(f"### actions: {bad_seeds_actions}") ass...
361
137
#!/usr/bin/python import json, subprocess, sys, platform from os.path import expanduser if len (sys.argv) < 2 : print("Usage: python " + sys.argv[0] + " username(s)") sys.exit (1) HOME=expanduser("~") # determine paths SYSTEM=platform.system() if SYSTEM == 'Darwin': SERVERJSON=HOME+'/Library/Application ...
1,418
480
# coding: utf-8 """ OriginStamp Client OpenAPI spec version: 3.0 OriginStamp Documentation: https://docs.originstamp.com Contact: mail@originstamp.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class TimestampResponse(...
7,141
2,098
power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate...
68,531
25,592
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-12-13 22:10 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import folder_tree.models import mptt.fields class Migration(migrations.Migration): initial ...
6,450
1,910
from __future__ import absolute_import # flake8: noqa # import apis from groupdocs_viewer_cloud.apis.file_api import FileApi from groupdocs_viewer_cloud.apis.folder_api import FolderApi from groupdocs_viewer_cloud.apis.info_api import InfoApi from groupdocs_viewer_cloud.apis.license_api import LicenseApi from groupdo...
428
136
from models.wrap_mobilenet import * from models.wrap_resnet import * from models.wrap_vgg import * from models.wrap_alexnet import * def get_model(config="resnet"): if "resnet" in config.backbone: model = get_resnet(config=config) elif "mobilenet" in config.backbone: model = get_mobilenet(confi...
481
164
import torch import torch.nn as nn from NeuralBlocks.blocks.convnormrelu import ConvNormRelu class segnetDown(nn.Module): def __init__(self, in_channels, out_channels, norm=None, num_conv = 2): super(segnetDown, self).__init__() module = [] if num_conv < 2: raise ValueError("Se...
4,571
1,500
#!/usr/bin/python # This script derived from a piece of the rubber project # http://launchpad.net/rubber # (c) Emmanuel Beffara, 2002--2006 # # Modified by Nathan Grigg, January 2012 import re import string import sys import getopt #---- Log parser ----{{{1 re_loghead = re.compile("This is [0-9a-zA-Z-]*") re_reru...
15,484
4,164
# Copyright 2018 Fujitsu. # # 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...
5,665
1,500
#This program converts KPH to MPH. #constant CONVERT_FACTOR = 0.6214 #head output print("KPH \t MPH") print("_" * 20) #loop for kph_speed in range (60, 131, 10): #calculation mph_speed = kph_speed * CONVERT_FACTOR #output print(kph_speed, '\t', format(mph_speed, '.1f')) input("\nPress any key to ...
527
256
from __future__ import absolute_import from django.core.urlresolvers import reverse from mock import Mock, patch from sentry.rules.registry import RuleRegistry from sentry.testutils import APITestCase class ProjectRuleConfigurationTest(APITestCase): def setUp(self): self.project.flags.has_issue_alerts_t...
3,841
1,161
# train-script.py # Grab data from movie_data.csv and train a ML model. # Kelly Fesler (c) Nov 2020 # Modified from Soumya Gupta (c) Jan 2020 # STEP 1: import ------------------------------------------- # Import libraries import urllib.request import os import pandas as pd import numpy as np import nltk import sklear...
3,297
1,092
from abc import ABCMeta, abstractmethod from collections import defaultdict from copy import deepcopy from typing import Union, Type, Any, Tuple import numpy as np import torch import torch.nn as nn from scipy.signal import find_peaks_cwt from .net import MyNN, MyNNRegressor from .utils import autoregression_matrix, ...
10,947
3,458
import types from testutils import assert_raises ns = types.SimpleNamespace(a=2, b='Rust') assert ns.a == 2 assert ns.b == "Rust" with assert_raises(AttributeError): _ = ns.c
182
68
# entrada value = int(input()) # variaveis cashier = True valueI = value n1 = 0 n2 = 0 n5 = 0 n10 = 0 n20 = 0 n50 = 0 n100 = 0 # laço quando cashier == False sai while cashier == True: # condicionais if value >= 100: valueA = value // 100 n100 = valueA valueB = ...
1,664
736
from abc import ABCMeta def _make_delegator_method(name): def delegator(self, *args, **kwargs): return getattr(self.__delegate__, name)(*args, **kwargs) # pragma: no cover # todo: consider using __call__() instead of __delegate__ # in Python delegates are objects with __call__ method.. ...
2,164
644
# -*- coding: utf-8 -*- from pymystem3 import Mystem # text = "some good newses" text = "Красивая мама красиво мыла раму" m = Mystem() lemmas = m.lemmatize(text) print(''.join(lemmas))
186
79
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from config.template_middleware import TemplateResponse from desenho.desenho_model import Desenho, DesenhoForm from gaecookie.decorator import no_csrf #from pedido.pedido_model import Pedido, PedidoForm from routes import desenhos from tek...
795
277
# import necessary libraries import csv from PIL import Image import argparse # create argument parser with PATH argument ap = argparse.ArgumentParser() ap.add_argument('-p', '--path', required=True, help='''PATH to CUB_200_2011 folder i.e. folder with CUB 200 csv files (make sure to include full path name for so ...
4,484
1,927
import torch from torch import nn class Criterion: def __call__(self, model: nn.Module, batch_x: torch.Tensor, batch_y: torch.Tensor, *args, **kwargs): pass class Image2ImageMSELoss(Criterion): def __init__(self): self.mse_loss = nn.MSELoss() def __repr__(self): return repr(sel...
3,487
1,315
__all__ = [ 'IUserService', 'UserService', ] from services.users.iuser_service import IUserService from services.users.user_service import UserService
160
49
# Copyright 2019 The Oppia 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 applicable ...
6,190
2,066
class UploadPrefixMiddleware(object): ''' Sets a cookie with the upload prefix. To be agnostic about your method of user authentication, this is handled using middleware. It can't be in a signal, since the signal handler doesn't have access to the response. In most applications, the client alr...
1,109
308
"""Utility module for setting up different envs""" import numpy as np import structlog from shapely.geometry import Point from ray.rllib.agents.ppo import DEFAULT_CONFIG from ray.rllib.env.multi_agent_env import MultiAgentEnv from deepcomp.util.constants import SUPPORTED_ENVS, SUPPORTED_AGENTS, SUPPORTED_SHARING, SUPP...
14,157
4,977
def parameters(model_type): if model_type == 'random forest': param_grid = { 'classifier__estimator__n_estimators': [50, 100], 'classifier__estimator__max_features' :['sqrt', 'log2'], 'classifier__estimator__max_depth' : [4,6,8] } elif model_type == 'logistic...
905
304
""" Faça um programa que receba o salário de um funcionário, calcule e mostre o novo salário, sabende-se que este sofreu um aumento de 25%""" sal = float(input('Salário:')) nsal = sal*1.25 print ('novo salário = ', nsal)
221
81
import numpy as np from numpy import random, linspace, cos, pi import math import random import matplotlib.pyplot as plt from scipy.fft import fft, fftfreq from scipy.fft import rfft, rfftfreq import copy from mpl_toolkits.mplot3d import axes3d from mpl_toolkits import mplot3d from plotly import __version__ import pand...
1,866
918
import unittest import sys import os import sys import json TEST_DIR = os.path.dirname(os.path.abspath(__file__)) PROJECT_DIR = os.path.abspath(os.path.join(TEST_DIR, os.pardir)) sys.path.insert(0, PROJECT_DIR) from module.cmdparse import cmdargs class test_cmdparse(unittest.TestCase): def __init__(self, methodN...
1,947
661
""" ebb_fit_prior : fits a Beta prior by estimating the parameters from the data using method of moments and MLE estimates augment : given data and prior, computes the shrinked estimate, credible intervals and augments those in the given dataframe check_fit : plots the true average and the shrinked average """ impo...
3,498
1,294
import sqlite3 from flask import Flask, render_template app = Flask(__name__) # database details - to remove some duplication db_name = 'shopping_data.db' @app.route('/') def index(): return render_template('index.html') @app.route('/customers') def customers(): conn = sqlite3.connect(db_name) conn.row_...
1,554
488
# Decode Ways: https://leetcode.com/problems/decode-ways/ # A message containing letters from A-Z can be encoded into numbers using the following mapping: # 'A' -> "1" # 'B' -> "2" # ... # 'Z' -> "26" # To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of th...
3,372
998
#!/usr/bin/python -W all """ word2vec.py: process tweets with word2vec vectors usage: word2vec.py [-x] [-m model-file [-l word-vector-length]] -w word-vector-file -T train-file -t test-file notes: - optional model file is a text file from which the word vector file is built - option x writes tokeni...
7,503
2,309
from .pipeline import SampleDataContainer, run_pipeline, make_pipeline from .preprocess import preprocess_noob from .postprocess import consolidate_values_for_sheet __all__ = [ 'SampleDataContainer', 'preprocess_noob', 'run_pipeline', 'make_pipeline,', 'consolidate_values_for_sheet' ]
307
102
from .rsmaker import RunstatMaker
36
13
row1 = ["⬜️","⬜️","⬜️"] row2 = ["⬜️","⬜️","⬜️"] row3 = ["⬜️","⬜️","⬜️"] map = [row1, row2, row3] print(f"{row1}\n{row2}\n{row3}") position = input("Where do you want to put the treasure? ") col = int(position[0]) ro = int(position[1]) map[ro-1][col-1] = "X" print(f"{row1}\n{row2}\n{row3}")
291
161
import xml.etree.ElementTree as ET from shared import * # neutral for skin in skins: name = f'{font}/emoji_u1f48f.svg' if skin == 'none' else f'{font}/emoji_u1f48f_{skin}.svg' left = ET.parse(name).getroot() right = ET.parse(name).getroot() remove(left, 2) remove(left, 1) remove(right, 0) w...
1,809
831
# © 2019 KidsCanCode LLC / All rights reserved. # Game options/settings TITLE = "Jumpy!" WIDTH = 480 HEIGHT = 600 FPS = 60 # Environment options GRAVITY = 9.8 # Player properties PLAYER_ACC = 0.5 PLAYER_FRICTION = -0.01 PLAYER_JUMPPOWER = 10 # Define colors # I changed the screen color to aqua, the platform color t...
488
251
def r2i(s): i = 0 result = 0 while i < len(s): a = {'IV': 4, 'IX': 9, 'XL': 40, 'XC': 90, 'CD': 400, 'CM': 900} if s[i:i + 2] in a: result += a[s[i:i + 2]] i += 2 continue b = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} ...
1,446
578
from asyncio import Queue, QueueEmpty from abc import ABC, abstractmethod from typing import List class TelemetryChannel(ABC): def __init__(self): self._queue = Queue() self._max_length = 500 def get(self): try: return self._queue.get_nowait() except QueueEmpty: ...
966
275
def processInput(inputFile='input.txt'): return [l.strip() for l in open(inputFile).readlines()] def filter(data, a=1): setA = set(range(len(data))) setB = set(range(len(data))) def count(bit, value, dataset): return set(d for d in dataset if data[d][bit] == value) for bit in range(12): ...
759
289
""" Distributed under the MIT License. See LICENSE.txt for more info. """ from django import template register = template.Library() @register.filter def get_item(dictionary, key): """ Returns the object for that key from a dictionary. :param dictionary: A dictionary object :param key: Key to search ...
659
181
contmaior = 0 contahomi = 0 contamuie = 0 while True: print('CADASTRE UMA PESSOA') print('=-' * 19) idade = int(input('INFORME SUA IDADE: ')) if idade > 18: contmaior += 1 sexo = str(input('INFORME SEU SEXO <<M/F>>: ')).upper().strip()[0] if sexo not in 'MF': while True: ...
1,091
438
from django.conf.urls import patterns, url from .views import template_test urlpatterns = patterns( '', url(r'^', template_test, name='template_test2'), )
165
53
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. #You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...
11,920
4,934
import numpy as np import imageio from evaluation.eval_utils import to_img_padded, format_img, init_evaluation def save_frames(env, agent, pad, folder): observation, ep_reward, done = env.reset(), 0, False count = 0 while not done: action, generated_next_observation = agent.act(observation, get_g...
1,031
351
# # HttpServer.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # Server to implement the http part of the oneM2M Mcx communication interface. # from __future__ import annotations import logging, sys, traceback, urllib3 from copy import deepcopy from typing ...
22,950
8,188
""" Tests for the sprockets.mixins.statsd package """ import mock import socket try: import unittest2 as unittest except ImportError: import unittest from tornado import httputil from tornado import web from sprockets.mixins import statsd as statsd class StatsdRequestHandler(statsd.RequestMetricsMixin, ...
2,855
884