text
string
size
int64
token_count
int64
"""Defines an Table Status Message.""" # System imports from enum import IntEnum # Local source tree imports from pyof.foundation.base import GenericMessage, GenericStruct from pyof.foundation.basic_types import BinaryData, FixedTypeList, UBInt16, UBInt8, UBInt32, UBInt64, Pad from pyof.v0x05.common.header import He...
1,457
482
import torch from torch.autograd import Function class Identity(Function): @staticmethod def forward(ctx, x, name): ctx.name = name return x.clone() def backward(ctx, grad): import pydevd pydevd.settrace(suspend=False, trace_only_current_thread=True) grad_temp = gr...
361
112
from os.path import isfile import os import cv2 from os.path import join import numpy as np import tqdm import random from big_pun.tracker_utils import filter_first_tracks, getTrackData def component(): return random.randint(0, 255) class FeatureTracksVisualizer: def __init__(self, gt_file,track_file, dat...
13,629
4,379
# -*- coding: utf-8 -*- """ This module provides functions for reading and writing Polygons in different formats. The following write-methods will accept different argument types for the output. If ofile is None, the method will create and return a StringIO-object. If ofile is a string, a file with that name will b...
12,163
4,137
from typing import List, Optional def reverse_string(string: str) -> str: return string[::-1] def reverse_string_in_place(string: [str]): index = 0 length = len(string) middle = length / 2 while index < middle: string[index], string[length - 1 - index] = string[length - 1 - index], strin...
743
266
# Copyright 2022 Quantapix 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 l...
14,706
4,887
import datetime, os, base64 from flask import Flask, jsonify, request, Blueprint from dbstore import dbconf import json from bson import json_util # process kill # lsof -i tcp:3000 file_upload = Blueprint('uploadAPI', __name__) app = Flask(__name__) def song_upload(val): try: # content = request.get_j...
29,495
6,973
#!/usr/bin/env python # zfec -- a fast C implementation of Reed-Solomon erasure coding with # command-line, C, and Python interfaces from __future__ import print_function import os, sys, argparse from zfec import filefec from zfec import __version__ as libversion __version__ = libversion def main(): if '-V' i...
2,542
809
# Generated by Django 3.2.2 on 2021-07-10 03:16 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('blweb', '0011_vehiclecolor'), ] operations = [ migrations.AddField( model_name='vehicleconfig',...
576
196
import numpy as np from . import acs_map_xy as acs_map def acs_3dpsf_basisfunctions( degree, x, y, focus ): # Generate relevant basis functions n_stars=np.max( np.array([len(x),len(y),len(focus)])) basis_function_order=np.zeros((1,3)) # All zeros for k in range(degree[2]+1): for j in range(...
11,634
4,684
import numpy as np import sys import scipy.interpolate as interpolate import asdf from .function import * from .basic_func import Basic class Func: ''' The list of (possible) `Func` attributes is given below: Attributes ---------- ''' def __init__(self, MB, dust_model=0): ''' ...
27,400
10,852
#! /usr/bin/env python3 # -*- coding: utf-8 -*- """ Definition of all Rainman2 exceptions """ __author__ = 'Ari Saha (arisaha@icloud.com), Mingyang Liu(liux3941@umn.edu)' __date__ = 'Wednesday, February 14th 2018, 11:38:08 am' class FileOpenError(IOError): """ Exception raised when a file couldn't be opene...
1,855
525
# Escreva um programa que converta uma temperatura digitando em graus Celsius e converta para graus Fahrenheit. print('-' * 100) print('{: ^100}'.format('EXERCÍCIO 014 - CONVERSOR DE TEMPERATURAS')) print('-' * 100) c = float(input('Informe a temperatura em ºC: ')) f = ((9 * c) / 5) + 32 print(f'A temperatura de {c:...
411
188
from odoo import SUPERUSER_ID, http from odoo.http import request from odoo.addons.web_settings_dashboard.controllers.main import WebSettingsDashboard class WebSettingsDashboardCustom(WebSettingsDashboard): @http.route("/web_settings_dashboard/data", type="json", auth="user") def web_settings_dashboard_data(...
848
268
import game as g import time as t def start_game(): r.add_sprite(player1, 0,0) r.add_sprite(player2, 5,0) r.add_sprite(ball, 3,3) r.print() def wait(length_of_time): inital = t.time() x = False while(not(x)): current = t.time() x = (current - inital) > length_of_time de...
686
325
from pyrogram import Client import json api_id = 2763716 api_hash = "d4c2d2e53efe8fbb71f0d64deb84b3da" app = Client("+639277144517", api_id, api_hash) target = "cnsex8" # Target channel/supergroup sigui588 cnsex8 with app: members = app.iter_chat_members(target) print(f"Chanel members counts : {len(members)...
662
263
__title__ = "FisherExactTest" __version__ = "1.0.1" __author__ = "Ae-Mc" __author_email__ = "ae_mc@mail.ru" __description__ = "Two tailed Fisher's exact test wrote in pure Python" __url__ = "https://github.com/Ae-Mc/Fisher" __classifiers__ = [ "Programming Language :: Python :: 3 :: Only", "Programming Language...
590
206
"""Parse PDFs about mimosas.""" from tqdm import tqdm from . import mimosa_pipeline from . import sentence_pipeline from .parsed_data import Datum def read(args): with open(args.in_text) as in_file: lines = in_file.readlines() if args.limit: lines = lines[: args.limit] nlp = mimosa_pipe...
875
290
# -*- coding: utf-8 -*- """ Created on Sat Oct 24 11:39:42 2015 @author: dahoiv """ import numpy as np def loadMetrics(filepath): mr_points=dict() us_points=dict() with open(filepath, 'r') as file : for line in file.readlines(): line = line.translate(None, '"') ...
1,647
634
# -*- coding: utf-8 -*- __all__ = ['interpolate', 'polynomial', 'SmoothSpline'] from .interpolate import SmoothSpline
118
48
## @ingroup Methods-Weights-Correlations-Tube_Wing # tube.py # # Created: Jan 2014, A. Wendorff # Modified: Feb 2014, A. Wendorff # Feb 2016, E. Botero # ---------------------------------------------------------------------- # Imports # --------------------------------------------------------------------...
3,286
953
# -*- Mode: Python -*- # GObject-Introspection - a framework for introspecting GObject libraries # Copyright (C) 2010 Johan Dahlin # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either versio...
3,837
1,094
import os import sys import json from manager import dbmanager def loadJson(filename): print("loadJson: " + filename) memoList = [] try: if os.path.isfile(filename): file = open(filename, 'r', encoding="UTF-8") lines = file.readlines() file.close() ...
1,219
397
import FWCore.ParameterSet.Config as cms # This modifier sets replaces the default pattern recognition with mkFit for tobTecStep trackingMkFitTobTecStep = cms.Modifier()
171
56
# My config.py script for overviewer: worlds["pudel"] = "/tmp/server/world/" worlds["pudel_nether"] = "/tmp/server/world_nether/" texturepath = "/tmp/overviewer/client.jar" processes = 2 outputdir = "/tmp/export/" my_cave = [Base(), EdgeLines(), Cave(only_lit=True), DepthTinting()] my_nowater = [Base(), EdgeLines(), No...
3,772
1,477
from django.db import models # Create your models here. class Encuesta(models.Model): nombre=models.CharField(max_length=150) descripcion=models.TextField() estructura=models.TextField() fecha = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.nombre) class Pregunta(models.Model):...
1,764
676
# -*- coding: utf-8 -*- from __future__ import absolute_import,unicode_literals from pythainlp.tools import get_path_db,get_path_data from tinydb import TinyDB,Query from future.moves.urllib.request import urlopen from tqdm import tqdm import requests import os import math import requests from nltk.corpus import names ...
3,150
1,016
# Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. # Example: # Given nums = [-2, 0, 3, -5, 2, -1] # sumRange(0, 2) -> 1 # sumRange(2, 5) -> -1 # sumRange(0, 5) -> -3 class NumArray: def __init__(self, nums): """ :type nums: List[int] ...
649
252
__all__ = [ 'Terminated', 'Unavailable', 'client', 'server', ] import logging import time import curio import nanomsg as nn from garage import asyncs from garage.assertions import ASSERT from garage.asyncs import futures from garage.asyncs import queues LOG = logging.getLogger(__name__) class Te...
8,257
2,193
from collections import namedtuple Bit = namedtuple('Bit', 'x y isset') def parsebit(val: str): """Parses bit notation for .db files to Bit class. Parameters ---------- val: str A string containing .db bit notation, i.e. "!012_23" => (12, 23, False) Returns ------- Bit: A named...
1,412
506
import tensorboardX from threading import Event from queue import Queue from delira.logging.writer_backend import WriterLoggingBackend class VisdomBackend(WriterLoggingBackend): """ A Visdom Logging backend """ def __init__(self, writer_kwargs: dict = None, abort_event: Event = None...
927
245
#! /usr/bin/env python3.5 # vim:ts=4:sw=4:ai:et:si:sts=4 import argparse import json import re import os import uuid import shutil import sys import requests filterRe = re.compile(r'(?P<block>^%=(?P<mode>.)?\s+(?P<label>.*?)\s+(?P<value>[^\s\n$]+)(?:\s*.*?)?^(?P<section>.*?)^=%.*?$)', re.M | re.S) subItemRe = re.com...
7,706
2,710
import dash_html_components as html from utils import Header def create_layout(app): # Page layouts return html.Div( [ html.Div([Header(app)]), # page 1 # add your UI here, and callbacks go at the bottom of app.py # assets and .js go in assets folder ...
379
104
from django.contrib import admin from offices.models import OfficeType, Office class OfficeTypeAdmin(admin.ModelAdmin): search_fields = ['title'] admin.site.register(OfficeType, OfficeTypeAdmin) ''' class OfficeAdmin(admin.ModelAdmin): search_fields = ['title'] admin.site.register(Office, OfficeAdmin) '''
318
90
from dataclasses import dataclass, field from datetime import datetime from enum import Enum from typing import Dict, List import pytest from openapi.data.fields import ( as_field, bool_field, data_field, date_time_field, number_field, ) from openapi.exc import InvalidSpecException, InvalidTypeExc...
6,511
1,918
import torch from torch import nn from models.GeneralModel import GeneralModel class MSE(GeneralModel): def __init__(self, device, l1_reg=0, lp_reg=0, **kwargs): super(MSE, self).__init__(device, **kwargs) self.loss = nn.MSELoss() def forward(self, output=None, target=None, weight_generator...
394
130
"""LMM testing code""" import unittest import scipy as sp import numpy as np from limix.core.covar import CategoricalCov from limix.utils.check_grad import mcheck_grad class TestCategoricalLowRank(unittest.TestCase): """test class for CategoricalCov cov""" def setUp(self): sp.random.seed(1) sel...
2,046
738
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/3/13 0013 下午 3:44 # @Author : Stephen # @Site : # @File : 005.py # @Purpose : # @Software : PyCharm # @Copyright: (c) Stephen 2019 # @Licence : <your licence> import os, re, time from pyecharts import Line """ 配置游戏包名和名字 """ package_na...
4,274
1,599
import numpy as np import torch from torch import optim from torch.nn import functional import torch.nn as nn import torch.utils.data from torch.nn import BatchNorm1d, Dropout, LeakyReLU, Linear, Module, ReLU, Sequential,Sigmoid from torch.nn import functional as F from opendp.smartnoise.synthesizers.base import SDGYMB...
13,470
4,249
import socket import threading import time # Create constants HEADER = 64 PORT = 5050 FORMAT = 'utf-8' DC_MSG = "!DISCONNECT" SERVER = "localhost" ADDR = (SERVER, PORT) # Set up client var and connect to the server client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(ADDR) erase = ...
1,814
626
from __future__ import annotations import disnake from disnake.ext import commands from typing import TYPE_CHECKING from src.utils.utils import EmbedFactory, ExitButton, SaveButton, add_lines, get_info if TYPE_CHECKING: from src.utils import File def clear_codeblock(content: str): content.strip("\n") ...
9,183
2,802
import discord, sqlite3, asyncio, utils, re from discord.ext import commands from datetime import datetime TIME_REGEX = re.compile("(?:(\d{1,5})\s?(h|hours|hrs|hour|hr|s|seconds|secs|sec|second|m|mins|minutes|minute|min|d|days|day))+?") TIME_DICT = {"h": 3600, "s": 1, "m": 60, "d": 86400} class TimeConverter...
11,878
3,709
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ## Created by: Hang Zhang ## Email: zhanghang0704@gmail.com ## Copyright (c) 2020 ## ## LICENSE file in the root directory of this source tree ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ """ResNet variants""" imp...
23,650
8,267
# AUTOGENERATED! DO NOT EDIT! File to edit: 02_inference.ipynb (unless otherwise specified). __all__ = ['device', 'pad_output', 'get_activ_offsets_mns'] # Cell #from fastai.vision.all import * from fastai import * from typing import * from torch import tensor, Tensor import torch import torchvision # Needed to i...
7,473
2,379
# -------------- import pandas as pd import numpy as np # Read the data using pandas module. data=pd.read_csv(path) # Find the list of unique cities where matches were played print("The unique cities where matches were played are ", data.city.unique()) print('*'*80) # Find the columns which contains null values if a...
2,141
750
from plugin.scrobbler.core import SessionEngine, SessionHandler @SessionEngine.register class PlayingHandler(SessionHandler): __event__ = 'playing' __src__ = ['create', 'pause', 'stop', 'start'] __dst__ = ['start', 'stop'] @classmethod def process(cls, session, payload): # Handle media c...
794
222
print('====== DESAFIO 46 ======') import time for c in range(10,-1,-1): time.sleep(1) print(c)
102
45
# Placeholder for adding logic specific to application # and backend key store. # import os import json import sys from azure.identity import DefaultAzureCredential from azure.keyvault.keys import KeyClient from azure.keyvault.keys.crypto import CryptographyClient, EncryptionAlgorithm # Append the current application p...
4,329
1,305
from distutils.core import setup, Extension setup(name='jawbonePyScss', version='1.1.8', description='jawbonePyScss', ext_modules=[ Extension( '_scss', sources=['src/_scss.c', 'src/block_locator.c', 'src/scanner.c'], libraries=['pcre'], optional=True ...
338
114
# python3 # 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...
18,301
5,681
# -*- coding: utf-8 -*- class Solution: def sortSentence(self, s: str) -> str: tokens = s.split() result = [None] * len(tokens) for token in tokens: word, index = token[:-1], int(token[-1]) result[index - 1] = word return ' '.join(result) if __name__ == '...
518
178
from django.apps import AppConfig class TodoapiConfig(AppConfig): name = 'todoapi'
89
30
# The MIT License (MIT) # # Copyright (c) 2014 Steve Milner # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modi...
3,101
967
from math import sin, cos, pi f = lambda x: 9*pi*cos(x) + 7*sin(x) + 4*x - 5*x*cos(x) # Analytical Solution df = lambda x: -9*pi*sin(x) + 7*cos(x) + 4 - 5*(cos(x)-x*sin(x)) dy = lambda x,y,u: u # 1st Derivative, y' = u du = lambda x,y,u: 4*x + 10*sin(x) - y # 2nd Derivative, u' = 4x+10sin(x)-y x = ...
2,365
1,214
#! /usr/bin/env python #ros library #import rospy #import the API #from iq_gnc.py_gnc_functions import * #print the colours #from iq_gnc.PrintColours import * # Importing Point message from package geometry_msgs. #from geometry_msgs.msg import Point #import opencv library import cv2 cap = cv2.VideoCapture(0) while T...
1,029
451
from switchmng import config from switchmng.schema.base import Base from switchmng.database import DatabaseConnection from switchmng.routes import create_app def app(*args, **kwargs): """ Entry point for wsgi server like `gunicorn` serving this application. Parse all command line arguments, initialize...
1,083
294
from records_mover.utils import quiet_remove from records_mover.records.delimited import cant_handle_hint, ValidatedRecordsHints from typing import Set, Tuple, Optional from .types import DateOrderStyle, DateOutputStyle def determine_date_output_style(unhandled_hints: Set[str], hints: ...
1,598
498
# Copyright 2018 NTT DATA # 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 applica...
6,239
2,138
"""test_example .. codeauthor:: John Lane <john.lane93@gmail.com> """ from flask import url_for from eve import Eve import pytest @pytest.mark.example def test_example(client: Eve): """Example test for reference :param Eve client: Mockerena app instance :raises: AssertionError """ res = clien...
445
153
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
1,243
389
#! /usr/bin/python3 import time import json import pickle import socket import argparse import numpy as np from tqdm import tqdm parser = argparse.ArgumentParser( description='Streams a file to a Spark Streaming Context') parser.add_argument('--file', '-f', help='File to stream', required=False,type=str, default=...
6,100
1,834
#!/usr/bin/python3 ##python3 闭包 与 nonlocal #如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用, #那么内部函数就被认为是闭包(closure) def A_(): var = 0 def clo_B(): var_b = 1 # 闭包的局部变量 var = 100 print(var) # 引用外部的var , 但是不会改变var 的值 return clo_B #clo_B是一个闭包 #nonlocal 关键字 def A_(): var = 0 def clo_B(): nonlocal var # nonlocal关...
394
289
import os import numpy as np class Tracker: def __init__(self, seed, model_name): self.save_tag = model_name + '_seed_' + str(seed) self.model_save = "models/" if not os.path.exists(self.model_save): os.makedirs(self.model_save) def save_model(self, model): model.save(self.mod...
352
123
from typing import Any, Dict, List, Type, TypeVar, Union, cast import attr from ..types import UNSET, Unset T = TypeVar("T", bound="Cluster") @attr.s(auto_attribs=True) class Cluster: """ """ addr: Union[Unset, str] = UNSET auth_timeout: Union[Unset, int] = UNSET cluster_port: Union[Unset, int] = U...
2,663
854
# import tkinter module from tkinter import * # import other necessery modules import random # Vigenère cipher for encryption and decryption import base64 # creating root object root = Tk() # defining size of window root.geometry("1200x4000") # setting up the title of window root.title("Message Enc...
4,287
1,625
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Jérôme Eberhardt 2018 # Bootstrap RMSF # Author: Jérôme Eberhardt <qksonoe@gmail.com> # # License: MIT from bootstrap_rmsf import Bootstrap_RMSF from utils import plot_rmsf
224
95
from selenium import webdriver from fixture.session import SessionHelper from fixture.group import GroupHelper from fixture.contact import ContactHelper class Application: def __init__(self, browser, base_url): if browser == "firefox": self.wd = webdriver.Firefox() elif browser == "Ch...
1,221
356
#!/usr/bin/env python # Dave B. # Uses fasta sorting functions written by Dan Blankenberg. import json import optparse import os import shutil import subprocess import sys import tempfile CHUNK_SIZE = 2**20 DEFAULT_DATA_TABLE_NAME = "fasta_indexes" def get_id_name(params, dbkey, fasta_description=None): # TODO:...
7,601
2,533
# Standard Library imports # Core Django imports # Third-party imports from rest_framework import permissions from rest_framework.throttling import UserRateThrottle, AnonRateThrottle # App imports class BurstRateThrottle(UserRateThrottle): scope = 'burst' class SustainedRateThrottle(UserRateThrottle): sc...
818
240
#!/usr/bin/env python # perform cellular-resolution expression analyses! import sys import time import optparse import general import hyper import numpy import math import pickle import pdb import metrn import modencode import itertools import os import re import datetime import calendar #import simplejson as json fr...
171,517
63,740
# https://stackoverflow.com/questions/47295473/how-to-plot-using-matplotlib-python-colahs-deformed-grid """ 这个形状仍然不对。靠近坐标轴的地方变化太大。不管是横轴还是纵轴。应该是以原点为圆心,各个网格均匀分担才对 而不管是否靠近坐标轴 变形的目标,是在某处给定一个球体或者立方体,整个坐标中的网格,靠近这个物体的,受到变形影响,距离越远,影响 越小,直到可以忽略不计 但有个要求是靠近物体的网格,是均匀的受到影响,不能有的多,有的少 或许用极坐标是更好的选择?但是也不行。极坐标如何体现原有的坐标系呢? 极坐标没有平直的地方...
1,838
1,017
from Onnx import make_dir, OnnxImportExport import subprocess import pickle import os import numpy as np import time def generate_svg(modelName, marked_nodes=[]): """ generate SVG figure from existed ONNX file """ if marked_nodes ==[]: addfilenamestr = "" add_command_str = "" els...
7,780
2,685
# Python script uses flask and SQL alchemy to create API requests for weather data from Hawaii. # Import dependencies. import numpy as np import datetime as dt import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func from flask impo...
9,961
2,792
import argparse import logging import sys import time import glob import os from . import logger from . import config from . visualization import plot from . optimization import run from . optimization import utils class optimalTAD: def __init__(self): self.log = logger.initialize_logger() self.cfg...
5,194
1,588
# Generated by Django 2.2.4 on 2019-09-02 11:59 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('communications', '0001_i...
944
296
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Sensirion SHT2x humidity sensor. Drives SHT20, SHT21 and SHT25 humidity and temperature sensors. Sensirion `SHT2x Datasheets <https://www.sensirion.com/en/environmental-sensors/humidity-sensors/humidity-temperature-sensor-sht2x-digital-i2c-accurate/>` """ from i2cmo...
1,126
431
from pipeline import * box_detection = BoxDetector()
52
16
"""Specifies the supported Bazel versions.""" CURRENT_BAZEL_VERSION = "5.0.0" OTHER_BAZEL_VERSIONS = [ "6.0.0-pre.20220223.1", ] SUPPORTED_BAZEL_VERSIONS = [ CURRENT_BAZEL_VERSION, ] + OTHER_BAZEL_VERSIONS
217
108
def _compile(words): if not len(words): return None, '' num = None if words[0].isdigit(): num = int(words[0]) words = words[1:] return num, ' '.join(words) def _split_out_colons(terms): newterms = [] for term in terms: if ':' in term: subterms = term...
1,372
441
class BankAccount: def __init__(self, checking = None, savings = None): self._checking = checking self._savings = savings def get_checking(self): return self._checking def set_checking(self, new_checking): self._checking = new_checking def get_savings(self): return self._savings def s...
539
207
import argparse from os import listdir, path import numpy as np def convert(main_folder, output): ret = [] for label, class_folder in listdir(main_folder): class_folder_path = path.join(main_folder, class_folder) for img_name in listdir(class_folder_path): image_path = path.join...
800
252
""" LeetCode Problem: 344. Reverse String Link: https://leetcode.com/problems/reverse-string/ Language: Python Written by: Mostofa Adib Shakib Time Complexity: O(n) Space Complexity: O(1) """ class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-pla...
509
172
#!/usr/bin/env python # Copyright 2018 The Fuchsia Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse from common import FUCHSIA_ROOT, get_package_imports, get_product_imports import json import os import subprocess import...
7,242
2,183
import tensorflow as tf import argparse import logging from src.helpers.NNHelper import NNHelper from src.controller.Controller import Controller from src.params.Parameters import Parameters def createParser(): parser = argparse.ArgumentParser(prog='langid_server', descriptio...
8,064
2,486
######################### # 单进程服务器 ######################### """ 同一时刻只能为一个客户进行服务,不能同时为多个客户服务类似于找一个“明星”签字一样,客户需要耐心等待才可以获取到服务 当服务器为一个客户端服务时,而另外的客户端发起了connect,只要服务器listen的队列有空闲的位置,就会为这个新客户端进行连接, 并且客户端可以发送数据,但当服务器为这个新客户端服务时,可能一次性把所有数据接收完毕当receive接收数据时,返回值为空, 即没有返回数据,那么意味着客户端已经调用了close关闭了;因此服务器通过判断receive接收数据是否为空 来判断客户端是否...
1,086
622
# -*- coding: utf-8 -*- from django.db import models class BaseCatalog(models.Model): name = models.CharField(max_length=255) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __unicode__(self): return...
3,098
1,028
import os import nltk import spacy from datetime import datetime from pyspark.sql import SparkSession from pyspark.sql.types import StringType, ArrayType from pyspark.sql.functions import udf, col, explode, collect_list, count from SYS import COL, MODE, DIR, FILE nltk.download('stopwords') os.system("python -m spacy d...
2,607
918
import uftpd uftpd.stop() # uftpd.start([port = 21][, verbose = 1]) uftpd.restart() # Version abfragen # wenn neuer - Dateien downloaden
141
61
from django.shortcuts import render, redirect from django.core.mail import send_mail from django.contrib import messages from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators impor...
10,672
3,278
#!/usr/bin/env python from setuptools import setup, find_packages import sys, os setup( name='anglerfish', version='0.4.1', description='Anglerfish, a tool to demultiplex Illumina libraries from ONT data', author='Remi-Andre Olsen', author_email='remi-andre.olsen@scilifelab.se', url='https://gi...
975
328
from django.urls import path from . import views app_name = 'files' urlpatterns = [ path('', views.index, name='index'), path('file/<int:file_id>/', views.fileview, name='file'), path('file/<int:file_id>/edit', views.fileedit, name='fileedit'), path('dir/<int:dir_id>/', views.dirview, ...
600
203
# Copyright 2018 Side Li and Arun Kumar # 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 writ...
1,733
598
# 670. 最大交换 # # 20200905 # huao class Solution: def maximumSwap(self, num: int) -> int: return int(self.maximumSwapStr(str(num))) def maximumSwapStr(self, num: str) -> str: s = list(num) if len(s) == 1: return num maxNum = '0' maxLoc = 0 for i in ran...
796
310
#!/usr/bin/env python3 import sys def solve(${formal_arguments}): return def main(): def iterate_tokens(): for line in sys.stdin: for word in line.split(): yield word tokens = iterate_tokens() ${input_part} solve(${actual_arguments}) if __name__ == '__main__'...
333
107
import sublime import sublime_plugin import datetime import re import regex from pathlib import Path import os import fnmatch import OrgExtended.orgparse.node as node from OrgExtended.orgparse.sublimenode import * import OrgExtended.orgutil.util as util import OrgExtended.orgutil.navigation as nav import OrgExtended...
21,501
7,746
import os import pandas as pd from qso_toolbox import utils as ut from qso_toolbox import catalog_tools as ct targets = pd.read_csv('/Users/schindler/Observations/LBT/MODS/190607-190615/lukas_efficiency_candidates.csv') offsets = pd.read_csv('') # query = 'rMeanPSFMag - rMeanApMag < 0.05 and 10 < zMeanPSFMag < 18' #...
3,519
1,221
# Generated by Django 2.2.6 on 2019-10-04 19:12 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0007_auto_20191005_0011'), ] operations = [ migrations.AddField( model_name='technologies', name='textAddEN'...
1,451
427
import os from sys import platform def say_beep(n: int): for i in range(0, n): if platform == "darwin": os.system("say beep")
152
52
from starlette.testclient import TestClient import pytest,os # from server.app import app import json import requests from faker import Faker fake = Faker() # The root url of the flask app url = 'http://127.0.0.1:5000/employee' @pytest.mark.skip(reason="long time running") def test_company_api_by_name_not_exists()...
1,685
661
import os import io import json import argparse import time import glob from doc2json.grobid2json.grobid.client import ApiClient import ntpath from typing import List ''' This version uses the standard ProcessPoolExecutor for parallelizing the concurrent calls to the GROBID services. Given the limits of ThreadPoolExec...
9,491
2,870