text
string
size
int64
token_count
int64
# -*- coding: utf-8 -*- # ------------------------------------------------------------ # StreamOnDemand-PureITA / XBMC Plugin # Canal para italiafilmvideohd # http://www.mimediacenter.info/foro/viewtopic.php?f=36&t=7808 # ------------------------------------------------------------ import base64 import re import urlpar...
17,263
5,388
"""Tests Tier Data""" import numpy as np from covid.data import TierData def test_url_tier_data(): config = { "AreaCodeData": { "input": "json", "address": "https://services1.arcgis.com/ESMARspQHYMw9BZ9/arcgis/rest/services/LAD_APR_2019_UK_NC/FeatureServer/0/query?where=1%3D1&out...
1,129
414
import pyautogui import time import pyperclip import pandas as pd #pyautogui.displayMousePosition() pyautogui.PAUSE = 1 #Passo 1 #Abrir uma nova aba time.sleep(2) pyautogui.hotkey('ctrl', 't') #Entrar no link do sistema link = "https://drive.google.com/drive/folders/149xknr9JvrlEnhNWO49zPcw0PW5icxga" py...
1,550
716
import tkinter import json from math import * from random import * from tkinter import * class brain_abstract(): ''' # один слой это лист туплов: колво нейронов в группе, # плюс(True) или минус(False) на выходе нейронов группы, # номер...
34,289
10,508
from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path('', views.index, name='home'), url(r'^artist/(?P<inputID>.*?)/$', views.showArtistPage, name='showArtistPage'), url(r'^album/(?P<inputID>.*?)/$', views.showAlbumPage, name='showAlbumPage'), url(r'^so...
761
286
"""Table CLI formatter. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import yaml from treadmill.formatter import tablefmt def _sort(unsorted): """Sort list.""" unsorted.sort() return '\n'.join(un...
19,030
5,422
r="" for _ in range(int(input())): s=input();tn=s[-2]+s[-1] if tn=='ne': r+=s[:-2]+'anes\n' else: t=s[-1] if t=='a' or t=='o' or t=='u': r+=s+'s\n' elif t=='i' or t=='y': r+=s[:-1]+'ios\n' elif t=='l' or t=='r' or t=='v': r+=s+'es\n...
483
222
from __future__ import print_function """Updates database json representation """ import argparse import itertools import logging import relstorage.adapters.postgresql import relstorage.options import sys from . import pg_connection from . import follow from .jsonpickle import Jsonifier from ._adapter import DELETE_T...
10,156
2,782
import string ALPHABET = set(string.ascii_lowercase) def is_pangram(sentence): return ALPHABET <= set(sentence.lower())
124
47
class ShardConfigException(ValueError): pass
48
13
#!/usr/bin/env python """Merge multiple evaluation files into one with prefixed measure names If directories are given, and --out-dir, will group by filename. Example usage: ./scripts/merge_evaluations.py --label-re='[^/]+/?$' -x eval_merged -l =TEDL2015_neleval-no1331 --out-dir /tmp/foobar tac15data/TEDL2015_nel...
3,538
1,217
from __future__ import absolute_import, division, print_function import os import numpy as np import theano.tensor as T from .model_basis import ModelBasis from .model_record import Record from ..layers import layers class Model(ModelBasis): def __init__(self, model_config, rng=None): super...
11,276
4,095
import csv import os import json from string import join from scrapy import log from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from scrapy.http import Request, HtmlResponse, FormRequest from scrapy.utils.url import urljoin_rfc from product_spiders.items import Product, ProductLo...
3,964
1,474
import streamlit as st title = st.text_input("Search:", "") st.write("You search for: ", title)
97
33
#!/usr/bin/env python # WS client example to test server import asyncio import websockets import json import time async def hello(): uri = "ws://localhost:8001" async with websockets.connect(uri) as websocket: inp = input("Input msg number? ") obj = { "source" : "sim", ...
908
321
#NOT YET WORKING PROPERLY #NOT INTEGRATED WITH THE ASSISTANT YET from pytrends.request import TrendReq # Only need to run this once, the rest of requests will use the same session. pytrend = TrendReq() def trending_searches(): # Get Google Hot Trends data trending_searches = pytrend.trending_...
1,834
612
import os import asyncio import re import requests import time import lottie import PIL.ImageOps from os.path import basename from PIL import Image from typing import Optional from .. import LOGS from ..config import Config from ..utils.extras import edit_or_reply as eor from .progress import * from .runner import r...
4,902
1,813
from __future__ import absolute_import import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.'+os.environ.get('APP_ENV', 'local')) app = Celery('app') app.config_from_object('django.conf:settings') app.autodiscover_t...
453
156
import time from typing import cast, Dict, Any from flask import request from assemblyline.common import forge from assemblyline.common.constants import SERVICE_STATE_HASH, ServiceStatus from assemblyline.common.dict_utils import flatten, unflatten from assemblyline.common.forge import CachedObject from assemblyline....
12,953
3,896
# Copyright (c) 2017 Shotgun Software Inc. # # CONFIDENTIAL AND PROPRIETARY # # This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit # Source Code License included in this distribution package. See LICENSE. # By accessing, using, copying or modifying this work you indicate your # agreement to the S...
3,627
1,103
__all__ = ['Elastix', 'Resampling'];
36
15
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-09-01 23:52 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('tournament', '0085_auto_20160901_2341'), ] operations = [ migrations.AlterUniqueTogether( name='gameselection',...
398
156
# -------- BEGIN LICENSE BLOCK -------- # Copyright 2022 FZI Forschungszentrum Informatik # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # n...
124,728
35,280
from gaffer import Plugin __all__ = ['DummyPlugin'] from .app import DummyApp class DummyPlugin(Plugin): name = "dummy" version = "1.0" description = "test" def app(self, cfg): return DummyApp()
225
82
import numpy as np import cv2 from preprocessing.utils import get_original_with_fakes from tqdm import tqdm from multiprocessing.pool import Pool from functools import partial # from skimage.measure import compare_ssim from skimage import metrics import argparse import os os.environ["MKL_NUM_THREADS"] = "1" os.environ...
2,485
874
import ast import community import datetime import lightgbm as lgb import math import matplotlib.pyplot as plt import networkx as nx import numpy as np import pandas as pd import pickle import plotly.express as px import os from sklearn.metrics import accuracy_score, confusion_matrix, roc_auc_score from tqdm import tqd...
18,905
6,383
from django import forms from recipe_app.models import Author from django.contrib.auth.forms import UserCreationForm # Create two forms: RecipeForm & AuthorForm """ Author: - Name: CharField - Bio: TextField Recipe: - Title: CharField - Author: ForeignKey - Description: TextField - Time Requ...
1,074
339
from typing import * import collections import copy import hashlib import math import numpy as np from pathlib import Path import random import re from tqdm import tqdm import traceback import sys from seutil import LoggingUtils, IOUtils, BashUtils from seutil.project import Project from roosterize.data.CoqDocument ...
42,840
13,884
""" This package contains implementations of pairwise similarity queries. """ # bring classes directly into package namespace, to save some typing import warnings try: import Levenshtein # noqa:F401 except ImportError: msg = ( "The gensim.similarities.levenshtein submodule is disabled, because the opt...
965
317
from tpucolab.core import *
27
10
import time class PIDController: def __init__(self, Kp=0.25, Ki=0.0, Kd=0.0, anti_windup=10.0, cmd_freq=0.0): self.Kp = Kp self.Ki = Ki self.Kd = Kd # Set max integral correction per timestep self.anti_windup = anti_windup # Set delay between updates (seconds) ...
1,858
630
# -*- coding: utf-8 -*- """ SQLite emitter """ import logging import sqlite3 LOGGER = logging.getLogger() def __type__() -> str: return 'SQLite' class SQLite: # pylint: disable=too-few-public-methods """ SQLite wrapper class """ def __init__(self, config: dict) -> None: """ Initializer ...
1,420
404
import cv2 import numpy as np from numpy.linalg import norm import math import csv from operator import itemgetter from datetime import datetime import VideoEnhancement import fishpredictor import detector import kmeancluster import preproccesing import randomforst cluster = kmeancluster.kmeans() classifier = randomfo...
6,043
2,039
""" --- geometry parameters for Wei et al stochastic sensing --- """ nm = 1e-0 # @TODO maybe include tolc in parent file tolc = 1e-2*nm # tolerance for coordinate comparisons dim = 3 # molecule radius rMolecule = 5*nm # effective pore radius ~ d^SAM_p/2 r0 = 13*nm # aperture angle in degrees angle = 40 # SiN mem...
889
340
import requests sample_user = {"latitude" : 42.2561110, "longitude" : -71.0741010, "uid" : "0" , "first_name" : "alex", "last_name" : "iansiti"} send_url = "http://flask-macoder.rhcloud.com/near" r = requests.post(send_url, sample_user) print(r.json())
254
115
#!/usr/bin/python # -*- coding: utf-8 -*- # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], ...
3,293
1,140
from functools import total_ordering def keys_to_scrap(keyprice, keys, metal): return round(keys * round(keyprice * 9)) + round(metal * 9) def scrap_to_keys(keyprice, scrap, force_ref=False): keys = 0 while not force_ref and scrap > round(keyprice * 9): keys += 1 scrap -= round(keyprice ...
1,660
598
from typing import Tuple, Pattern from urllib.request import urlopen import os from ftplib import FTP from tempfile import TemporaryDirectory from hashlib import sha256 import re from course_valve.valve_defs import ( TARGET_FTP, ENCRYPTED_PASSWORD, TARGET_FILE_NAME, IDENTIFIER, NO_IDENTIFIER, F...
6,251
2,096
""" Tests for the base module """ from vlnm.normalizers.base import ( FormantGenericNormalizer, FormantSpecificNormalizer, FormantsTransformNormalizer, Normalizer) from tests.helpers import Helper class TestBaseNormalizers(Helper.TestNormalizerBase): """ Tests for the base Normalizer class. ...
1,782
480
#!/usr/bin/env python3 import os import sys import time import traceback from itertools import combinations from multiprocessing.pool import ThreadPool from exchangebase import ExchangeBase from exchangepair import ExchangePair from gdaxapi import Gdax from krakenapi import Kraken class Arbiter: def __init__(se...
5,934
1,735
import boto3 import sys import numpy as np import random import time # endpoint_url = 'https://mturk-requester-sandbox.us-east-1.amazonaws.com' endpoint_url = 'https://mturk-requester.us-east-1.amazonaws.com' ##Remember to put the AWS credential in ~/.aws/credential like below: ####### #[default] #aws_access_key_id = ...
2,289
825
# def get_param_traj_file_path(dir_name, net_name, index): # return f'{dir_name}/{net_name}_{index}.txt' import os from datetime import datetime def get_current_timestamp(): return datetime.now().strftime('%Y-%m-%d-%H:%M:%S') def get_project_dir(): project_dir = os.path.abspath(os.path.join(os.path.abspa...
4,623
1,876
from __future__ import print_function import pytest from tempfile import mkdtemp from glob import glob import shutil import fnmatch import os import os.path import sami TEST_DIR = os.path.join(os.path.split(__file__)[0], "test_data") # Note: if the test data is changed, then these lists must be updated # (too hard...
6,018
2,153
# -*- coding: utf-8 -*- from model.contact import Contact def test_add_contact(app): old_contacts = app.contact.get_contact_list() contact = Contact(firstname='firstname', middlename='middlename', lastname='lastname', nickname='nick', title='title', company='company', address='address', home='home phone', mob...
1,536
539
# -*- coding:utf-8 -*- """ Description: Inventory Class Usage: from AntShares.Network.Inventory import Inventory """ from AntShares.IO.MemoryStream import MemoryStream from AntShares.IO.BinaryWriter import BinaryWriter from AntShares.Cryptography.Helper import * from AntShares.Helper import * import binascii...
1,038
325
#!/usr/bin/python # Copyright (c) 2015-2017 Martin F. Falatic # # 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 # # Unl...
1,585
563
#!/usr/bin/env python3 import os.path import random from pathlib import Path from random import randint from pymongo import MongoClient from web3.logs import DISCARD from broker import cfg from broker._utils import _log from broker._utils._log import console_ruler from broker._utils.tools import _time, _timestamp, c...
11,024
4,378
from torch.autograd import Variable import torch.nn.functional as F import torch.nn as nn import torch as th from components.transforms import _to_batch, _from_batch, _check_inputs_validity, _tdim, _vdim class DQN(nn.Module): def __init__(self, input_shapes, n_actions, output_type=None, output_shapes=None, layer_...
8,441
2,752
from datetime import date nascimento = int(input('Digite o ano de nascimento: ')) idade = date.today().year - nascimento print(f'Ele tem {idade} anos.') if idade <= 9: lugar = 'mirim' elif idade <= 14: lugar = 'infantil' elif idade <= 19: lugar = 'junior' elif idade <= 25: lugar = 'sênior' ...
401
167
from .utils import add_weight_decay, AverageMeter, label_img_to_color, check_mkdir
82
29
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 27 18:11:58 2021 @author: TSAI, TUNG-CHEN @update: 2021/10/05 """ MODEL_NAME = 'PhysicalCNN' DIRECTORY = r"../dataset/preprocessed/data/" WALK = True SUBSET = 'all' from wtbd.infer import infer from wtbd.utils import print_info from wtbd.data_c...
1,159
344
""" 排列五的概率输出 """ from lottery import get_history import pandas as pd import dash import dash_html_components as html import dash_core_components as dcc CODE = '排列五' MIN = 1 COUNT = 200 def _calc_prob(num, datas): """ 计算num在datas里的概率 e.g.: num = 1 data = [[2,3],[1,7],[3,6]] retun...
2,262
867
""" Copyright [2013] [Rackspace] 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 writing, software ...
1,947
590
from datetime import datetime today = datetime.today().strftime('%Y-%m-%d %H-%M-%S') def log_msg(text): with open(f'./logs/{today}.log', 'a+') as log: log_time = datetime.today().strftime('%Y-%m-%d %H:%M:%S') log.write(f'[{log_time}] {text}\n')
266
105
Import("env") import hashlib import os import shutil def _file_md5_hexdigest(fname): return hashlib.md5(open(fname, 'rb').read()).hexdigest() def after_build(source, target, env): if not os.path.exists("builds"): os.mkdir("builds") lang = env.GetProjectOption('lang') target_name = lang.lower(...
581
220
import re import os from bs4 import BeautifulSoup from . import settings def html2list(html_string, level='word'): """ :param html_string: any ol' html string you've got level: either 'word' or 'character'. If level='word', elements will be words. If level='character', elem...
8,184
2,471
########################################################################## # # pgAdmin 4 - PostgreSQL Tools # # Copyright (C) 2013 - 2020, The pgAdmin Development Team # This software is released under the PostgreSQL Licence # ########################################################################## import os import...
3,846
1,006
#!/usr/bin/env python # Copyright 2014, Deutsche Telekom AG - Laboratories (T-Labs) # # 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 # # Unl...
1,467
414
import frappe def permission_ov(user): pass # print("///////////******///////******////******///**") # print(user) # print(frappe.session.user) # return """(`tabValiant`.`native`='Salem' )""" # return "(`tabValiant`.owner = 'i am')".format(user=frappe.db.escape(user)) def has_permission(doc, user=None, permiss...
840
273
from django.shortcuts import render from django.http import HttpResponse,JsonResponse from django.conf import settings from Book.models import PictureInfo,AreaInfo from django.core.paginator import Paginator # Create your views here. def sheng(request): """获取省级数据,并转JSON字典,响应给ajax""" # 查询省级数据 sheng_list = [Ar...
2,760
1,303
""" File: add2.py Name: ------------------------ TODO: """ import sys class ListNode: def __init__(self, data=0, pointer=None): self.val = data self.next = pointer def add_2_numbers(l1: ListNode, l2: ListNode) -> ListNode: ####################### # # # TOD...
4,925
1,637
import obelisk import logging import bitcoin from twisted.internet import reactor _log = logging.getLogger('trust') TESTNET = False def burnaddr_from_guid(guid_hex): _log.debug("burnaddr_from_guid: %s", guid_hex) if TESTNET: guid_hex = '6f' + guid_hex else: guid_hex = '00' + guid_hex ...
1,157
420
# Collage Generator Backend Application import logging.config from starlette.applications import Starlette from starlette.middleware import Middleware from starlette.middleware.authentication import AuthenticationMiddleware from starlette.middleware.gzip import GZipMiddleware from starlette_context import plugins from...
1,261
342
""" [Golf](https://www.codechef.com/MAY21C/problems/LKDNGOLF) It's a lockdown. You’re bored in your house and are playing golf in the hallway. The hallway has N+2 tiles numbered from 0 to N+1 from left to right. There is a hole on tile number x. You hit the ball standing on tile 0. When you hit the ball, it bounces a...
2,298
778
""" Application logger """ import logging import os import sys from yogit import get_name, get_version from yogit.yogit.paths import get_log_path, SETTINGS_DIR def get_logger(stdout=False, logger_name=get_name(), version=get_version()): """ Create and configure a logger using a given name. """ os.ma...
1,446
465
# coding: utf-8 """ Connect Statistics API Connect Statistics API provides statistics about other cloud services through defined counters. OpenAPI spec version: 3 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import # import models into m...
481
127
import logging, sys def sane_logger(log_level=logging.INFO): logger = logging.getLogger() logger.setLevel(log_level) sh = logging.StreamHandler(sys.stdout) formatter = logging.Formatter( '[%(asctime)s] %(levelname)s [%(filename)s.%(funcName)s:%(lineno)d] %(message)s', datefmt='%a, %d %b %Y %H:%M:%S %...
488
193
from core_tools.data.SQL.SQL_connection_mgr import SQL_database_manager from core_tools.drivers.hardware.hardware_SQL_backend import virtual_gate_queries import time import numpy as np def lamda_do_nothing(matrix): return matrix class virtual_gate_matrix(): def __init__(self, name, gates, v_gates, data, ...
7,104
2,432
from django.shortcuts import render from django.shortcuts import get_object_or_404 from rest_framework.views import APIView from rest_framework import status from rest_framework.response import Response from rest_framework import generics from .models import kotoUser from .models import transaction from .models import ...
4,658
1,232
import sys import re import json import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.cluster import KMeans from sklearn.decomposition import PCA from sklearn.preprocessing import MultiLabelBinarizer from scipy.spatial.distance import cdist from colorama import Fore, Style from kneed impo...
54,648
16,468
import json from collections import OrderedDict import pprint import json import sys # prons = sys.argv prons = ['pron1.json', 'pron2.json','pron3.json','pron4.json'] def war(pron): with open(pron, encoding='utf8') as f: d_update = json.load(f, object_pairs_hook=OrderedDict) synset = {} ...
748
287
from flask import Blueprint,Flask main = Blueprint('main',__name__) from app.main import views from flask_bootstrap import Bootstrap from flask_sqlalchemy import SQLAlchemy bootstrap= Bootstrap() db = SQLAlchemy() def create_app(): app= Flask(__name__) #initializing flask extensions bootstrap.init_app(...
495
157
#!/usr/bin/env python3 '''set frame height 10%, 80%, 10%''' import tkinter as tk root = tk.Tk() root.geometry('400x300') header = tk.Frame(root, bg='green') content = tk.Frame(root, bg='red') footer = tk.Frame(root, bg='green') root.columnconfigure(0, weight=1) # 100% root.rowconfigure(0, weight=1) # 10% root.rowc...
506
218
from lib import * generate_bins("./bld/bits/vex_pb0_partial.bit","./bld/bins/vex_pb0.bin",0x8D) generate_bins("./bld/bits/vex_pb1_partial.bit","./bld/bins/vex_pb1.bin",0x8D) generate_bins("./bld/bits/vex_pb2_partial.bit","./bld/bins/vex_pb2.bin",0x8D) generate_bins("./bld/bits/vex_tmr_pb0_partial.bit","./bld/bins/vex...
2,524
1,372
import unittest from pysie.dsl.set import TernarySearchTrie class TernarySearchTrieUnitTest(unittest.TestCase): def test_map(self): trie = TernarySearchTrie() self.assertTrue(trie.is_empty()) trie.put('hello', 'world') self.assertTrue(trie.contains_key('hello')) self.asse...
922
328
from sanic import Blueprint from sanic import response from sanic.log import logger from sanic_openapi import doc from .user import get_user, get_routes user_svc = Blueprint('user_svc') @user_svc.get('/currentUser', strict_slashes=True) @doc.summary('get current user info') async def user(request): try: ...
825
255
from opentrons import protocol_api # Rename to 'purification_template' and paste into 'template_ot2_scripts' folder in DNA-BOT to use metadata = { 'apiLevel': '2.8', 'protocolName': 'purification_template', 'description': 'Implements magbead purification reactions for BASIC assembly usin...
15,071
4,773
# Generated by Django 3.2.4 on 2021-08-15 12:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('articles', '0008_auto_20210808_0801'), ] operations = [ migrations.AddField( model_name='article', name='doi', ...
1,921
556
import pytest import json from django.urls import reverse def test_view_get_page_not_found(client): response = client.get('/') assert response.status_code == 404 def test_purchase_without_authentication(client, db): url = reverse('purchase') body = { "products" : [ { ...
2,567
884
''' Created on Nov 16, 2011 @author: jcg ''' from Features.Feature import Feature import Functions from uuid import uuid4 class CAI(Feature): """ CAI Feature solution - solution where CAI should be computed label - some label to append to the name cai_range - start and end position to...
3,056
838
from django.urls import path from .views import portfolio_view urlpatterns = [ path('', portfolio_view, name='projects_view') ]
132
41
#! /usr/bin/env python ''' This node uses the detection_info topic and performs the actual Ur5 arm manipulation ''' import rospy import random from math import pi, sin, cos from geometry_msgs.msg import Point, Quaternion, Pose, PointStamped, PoseStamped from std_msgs.msg import Header from object_msgs.msg import Obj...
17,690
6,714
import tensorflow as tf from cleverhans.attacks import FastGradientMethod from cleverhans.utils_keras import KerasModelWrapper from keras.utils import to_categorical import keras.backend as K import numpy as np from functools import lru_cache from pickle import loads, dumps from models import filter_correctly_class...
2,224
800
from urlparse import urlparse from re import match def get_redirect(req_path, ref_url): ''' >>> get_redirect('/style.css', 'http://preview.local/tree/foo/view/') '/tree/foo/view/style.css' >>> get_redirect('/style.css', 'http://preview.local/tree/foo/view/quux.html') '/tree/foo/view/style.css' ...
2,187
752
from flask import Blueprint, render_template home_bp = Blueprint( "home_bp", __name__, ) @home_bp.route("/") def home(): return render_template("index.html", title="Chuyển ảnh thành văn bản", submit_localtion="/scanner")
237
90
from p3ui import * import matplotlib.pyplot as plt import numpy as np def gradient_image(ax, extent, direction=0.3, cmap_range=(0, 1), **kwargs): phi = direction * np.pi / 2 v = np.array([np.cos(phi), np.sin(phi)]) X = np.array([[v @ [1, 0], v @ [1, 1]], [v @ [0, 0], v @ [0, 1]]]) a,...
1,746
670
from collections import deque """ Operations * Enqueue * Dequeue * Peek (first element) * Size * IsEmpty * Print """ def demo_queue_operation_using_deque(): stack = deque() # enqueue - inserting at the Right stack.append(1) stack.append(2) stack.append(3) stack.append(4) stack.append(5) ...
816
319
mask = 255 print(mask == 255) blue_mask = mask == 255 print(mask) print(blue_mask)
85
43
''' Contains the implementation of the FindSongs class. ''' from re import compile as rcompile from zipfile import ZipFile from os.path import dirname import pandas as pd from tensorflow.keras.models import load_model from sklearn.neighbors import NearestNeighbors from joblib import load DIR = dirname(__file__) rex =...
7,664
2,364
import tweepy import time import pandas as pd import datetime import re from auth import consumer_key,consumer_secret,key,secret,user_ID def trimtweet(tweet): if(tweet.length <= 280): return tweet return tweet.substring(0, 277) + "..." # twitter auth process auth = tweepy.OAuthHandler(consumer_key, c...
3,516
1,309
#!/usr/bin/env python import rosbag import numpy as np import matplotlib.pyplot as plt import sys import os args = sys.argv print(len(args)) assert len(args)>=2, "you must specify the argument." # get path filename=os.path.normpath(os.path.join(os.getcwd(),args[1])) print(filename) # read from bag file bag = rosbag....
1,277
574
''' Created on Dec 21, 2014 @author: Alina Maria Ciobanu ''' import numpy import re TOKEN_NER_TAGS = ['DATE', 'NUMBER'] WIKI_NER_TAGS = ['PERSON', 'ORGANIZATION', 'LOCATION'] DEFAULT_YEAR_VALUE = 1858 # the mean of the lowest and highest value for all possible intervals, hardcoded for now def get_tem...
1,748
695
"""This module handles classifier calculation.""" from academia_tag_recommender.definitions import MODELS_PATH from sklearn.model_selection import train_test_split from sklearn.model_selection import GridSearchCV from sklearn.metrics import make_scorer, recall_score from sklearn.model_selection import StratifiedKFold f...
7,270
2,163
class Solution: def maxTurbulenceSize(self, arr: List[int]) -> int: n = len(arr) if n == 1: return 1 def calc(a, b): if a == b: return 0 elif a > b: return -1 else: return 1 res = 0 ...
646
200
from node.behaviors import Adopt from node.behaviors import DefaultInit from node.behaviors import Nodespaces from node.behaviors import Nodify from node.behaviors import OdictStorage from node.tests import NodeTestCase from odict import odict from plumber import plumbing #############################################...
2,332
678
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-06-07 13:30 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('excerptexport', '0041_set_date_to_past_for_existing_exports_20160531_2235'), ] operations = ...
443
168
""" Extract as-run river time series. To test on mac: run extract_rivers -gtx cas6_v3_lo8b -0 2019.07.04 -1 2019.07.04 To run on perigee: run extract_rivers -gtx cas6_v3_lo8b -0 2018.01.01 -1 2018.01.10 run extract_rivers -gtx cas6_v3_lo8b -0 2018.01.01 -1 2018.12.31 Performance: takes 23 sec per year on perigee M...
3,673
1,500
# Generated by Django 3.0.7 on 2020-11-07 16:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('common', '0015_task_unique_dir'), ] operations = [ migrations.AlterField( model_name='comment', name='line', ...
570
183
from __future__ import absolute_import import math import operator from collections import OrderedDict from functools import reduce from typing import Union, Sequence, Optional import torch from laia.data import PaddedTensor from laia.nn.pyramid_maxpool_2d import PyramidMaxPool2d from laia.nn.temporal_pyramid_maxpoo...
6,361
2,261
import pyglet from pyglet.gl import * from robocute.node import * from robocute.vu import * from robocute.shape import Rect class WidgetVu(Vu): def __init__(self, node): super().__init__(node) # self.content = Rect() # self.margin_top = 5 self.margin_b...
1,541
502