index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
999,600
01da8493c1c735a7ff806dde9b16a6a927817f5e
def gen_primes(): D = {} q = 2 while True: if q not in D: yield q D[q * q] = [q] else: for p in D[q]: D.setdefault(p + q, []).append(p) del D[q] q += 1 primes = gen_primes() ...
999,601
45cc3a76afc1ed591ab23efa0831e8b4ff25be40
if __name__ == "__main__": total() escape() print_escape() print_eat() import colorama from colorama import Fore, Back, Style colorama.init() def total(*params): res = 0 for item in params: res += sum(item) return res def escape(*params): res2 = 0 for item in params: ...
999,602
a6d9069fb46a2a08ec6329e2e80399a31a157c49
import sys import array import copy file = open("../inputs/day13input.txt", "r") directions = file.read().split("\n") layers = {} #map each location to the length of the array at that location for d in directions: dSplit = d.split(":") leftSide = int(dSplit[0]) rightSide = int(dSplit[1].strip()) layers[leftSide]...
999,603
e483d65e9e64f3f5efa68d37e2654fce49244dfa
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt secondary_sales = pd.read_csv("WC_DS_Ex1_Sec_Sales.csv",parse_dates=[3],index_col=[3]).sort_index() secondary_sales['promotions'] = 1 - secondary_sales['SP']/secondary_sales['MRP'] train = secondary_sales[['Store_Code...
999,604
758b808b2b114a5a76d1b9f1880a7d1e557c2be6
def climbingStaircase(n, k): rs = Staircase().climb(n, k) return sorted(rs) class Staircase: def __init__(self): self.mem = dict() def climb(self, n, k): print(f"climbingStaircase({n}, {k})") if n == 1: return [[1]] elif n == 0: return [[]] ...
999,605
41fd187be56e648d3ecb2c0a0c02aaf7b691dac0
pyg = 'ei' original = raw_input('Escribe una palabra:') if len(original) > 0 and original.isalpha(): palabra = original.lower() primera = palabra[0].lower() if primera == "a" or primera == "e" or primera == "i" or primera == "o" or primera == "u": nueva_palabra = palabra + pyg else: ...
999,606
c7604abd4f26f3e60b7568b085fb3fb9acc27f21
#!/usr/bin/env python3 #-*- Coded By SadCode -*- import re import requests import urllib.request import json import codecs import os import sys import argparse import mutagen from mutagen.easyid3 import EasyID3 from mutagen.id3 import ID3, APIC CLIENTID="Oa1hmXnTqqE7F2PKUpRdMZqWoguyDLV0" API = "https://api.soundclou...
999,607
07d3a9be938d89a832fc534dfe6ea14c2dc737ac
# 编写一个程序,通过填充空格来解决数独问题。 # 一个数独的解法需遵循如下规则: # 数字 1-9 在每一行只能出现一次。 # 数字 1-9 在每一列只能出现一次。 # 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。 # 空白格用 '.' 表示。 # https://leetcode-cn.com/problems/sudoku-solver class Solution: def solveSudoku(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-...
999,608
2374e8feb344a24c3de015b933318a426e45f9d7
def angle_diagram(x1,x2,x3,x4,palm_point,input_image): row = input_image.shape[0] col = input_image.shape[1] copy = np.zeros((row,col)) copy = input_image #box coordinates x1=[40,15] x2=[20,25] x4=[40,65] x3=[60,55] palm_point = [75,75] top_mid = [(x1[0]+x2[0])//2,(x1[1]+x2[1])//2] base_mid = [(x3[0]...
999,609
c05154e87f3ecac43cc910f0bea3b6d397f7a59b
import numpy as np import requests, pybel, json from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, relationship from sqlalchemy import create_engine from sqlalchemy import Column, Integer, Float, Text, Boolean, String, ForeignKey, UniqueConstraint Base = declarative_base()...
999,610
e2fa8c83d258b204cc120301eae1faac267d8756
n = float(input()) if (n - int(n)) >= 0.5: print(int(n) + 1) else: print(int(n))
999,611
d0f2c31348babcf527b5aebf40aab9ec85bfc8e5
#!/usr/bin/python3 -u from tango.server import run import os from ZaberTMMAxis import ZaberTMMAxis from ZaberTMMCtrl import ZaberTMMCtrl # Run ZaberTMMCtrl and ZaberTMMAxis run([ZaberTMMCtrl, ZaberTMMAxis])
999,612
c345d59cee43bc166bf3570dc83e0d73b711acf5
#!/usr/bin/python # -*- codding: utf-8 -*- import os import sys sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) from common.execute_command import write_two_parameter # url : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/create-change-set.html if __name_...
999,613
7a5325e00f0a316ddd27e5cdc3e3e03ac771a339
''' 272. Closest Binary Search Tree Value II Given the root of a binary search tree, a target value, and an integer k, return the k values in the BST that are closest to the target. You may return the answer in any order. You are guaranteed to have only one unique set of k values in the BST that are closest to the tar...
999,614
158e68668b2977e277f87a9f23b10dc703aad1db
import json import pprint as pp import math #Authors: Evan Bluhm, Alex French, Elizabeth Gass, Samuel Gass, Margaret Yim class StarSolver(): graph = {} def get_node_with_min_f_score(node_set): min_value = math.Inf best_node = None for n in node_set.values(): if n.f_score <...
999,615
594e43b10b57189fe81d909bad79f05f7dfece44
import pandas as pd import quandl, math, datetime import numpy as np from sklearn import preprocessing,svm from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt from matplotlib import style import pickle style.use('ggplot') ...
999,616
3ea65a0da4393be49b9412a0db31c1cfac6a8905
import pandas as pd import numpy as np from sklearn.metrics import confusion_matrix, f1_score from sklearn.base import BaseEstimator from typing import Text, Dict def evaluate(df: pd.DataFrame, target_column: Text, clf: BaseEstimator) -> Dict: """Evaluate classifier on a dataset Args: df {pandas.Data...
999,617
47d345ab6c8fd9f6f913956aaf7108b5d08810f1
"""Tests xonsh tools.""" import datetime as dt import os import pathlib import stat import warnings from tempfile import TemporaryDirectory import pytest from xonsh import __version__ from xonsh.lexer import Lexer from xonsh.platform import HAS_PYGMENTS, ON_WINDOWS, PYTHON_VERSION_INFO from xonsh.pytest.tools import ...
999,618
b87cfe08c1bc27da8b25d66c690f81e980bfc360
from django.conf.urls import url, include from django.urls import path from rest_framework import permissions from .serializers import * from .views import * from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, TokenVerifyView, ) faculty_list = Fac...
999,619
96f2230ed57be6225cb9ab1164b7e4e9660a23c6
# -*- coding: utf-8 -* """ 实现模型的调用 """ from flyai.dataset import Dataset from model import Model data = Dataset() model = Model(data) # p = model.predict( # source="新华社 北京 5 月 8 日 电 中国 跳水 名将 余卓成 7 日 在 美国 佛罗里达州 举行 的 国际泳联 跳水 大奖赛 上 , 获得 男子 一米板 冠军 。 新华社 北京 5 月 8 日 电 中国 跳水 名将 余卓成 7 日 在 美国 佛罗里达州 举行 的 国际泳联 跳水 大奖赛 上 , 获得 ...
999,620
d4670ed2ae4038a376c84fd5fcd378ea6596a806
""" The tspio module basically contains the messy code that is avoided in the IOModule but has to exist, like showing file dialogues, parsing files and writing files, as well as some helper methods for string construction from data structures.""" import re import ast import os import tsputil from Node i...
999,621
5dd8f34c65644ec3314e1ad102613aa2e1bdab3e
from django.db import models from django.db.models import Sum from datetime import datetime from pytz import timezone class Destination(models.Model): name = models.CharField(max_length=100) address = models.CharField(null=True, max_length=100) def __str__(self): return str(self.name) class Produ...
999,622
4ae7f07d5148a901e4001c869ac2b173da409241
## # This is the web service form for the Crazy Ivan RDFa Test Harness script. # License: Creative Commons Attribution Share-Alike # @author Manu Sporny import os, os.path import re from re import search from urllib2 import urlopen import urllib from rdflib.Graph import Graph import xml.sax.saxutils from mod_python imp...
999,623
bfdb0ef399e0aa6cf40710235ebd4ecd45101bb1
class Node(object): def __init__(self,data): self.data = data self.nxt = None class Stack(object): def __init__(self, top): self.top = top def pop(self): if not self.top: return None output = self.top.data self.top = self.top.next return ...
999,624
a5a957cdb92325d970ccecaea0e1a8da4d3ce844
from application import db from sqlalchemy.sql import text class Book(db.Model): id = db.Column(db.Integer, primary_key=True) date_created = db.Column(db.DateTime, default=db.func.current_timestamp()) date_modified = db.Column(db.DateTime, default=db.func.current_timestamp(), ...
999,625
0dbebcbfcb84d2a6deabea913be6f2e751b99de1
#4.6 #Write a program to prompt the user for hours and rate per hour using input to compute gross pay. #Pay should be the normal rate for hours up to 40 and time-and-a-half for the hourly rate for all hours worked above 40 hours. #Put the logic to do the computation of pay in a function called computepay() and use t...
999,626
6b6804906b67f6728ba12bab3ba51f7a6b66f534
from .fluxdens import airgap, airgap_fft from .bch import torque, torque_fft, force, force_fft,\ fluxdens_surface, winding_current, winding_flux, \ voltage, voltage_fft, transientsc_demag, \ i1beta_torque, i1beta_ld, i1beta_lq, i1beta_psid, i1beta_psiq, i1beta_psim, i1beta_up, \ idq_ld, idq_lq, idq_psid...
999,627
89db014a5157795a14eae486e39a209c1aa43655
''' 1528. Shuffle String Given a string s and an integer array indices of the same length. The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string. Return the shuffled string. Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3] Output: "leetcode" Explanati...
999,628
481d7e6b8c0cd005c8144c1d404f39874f290b59
import askers import relayer import updates import convert import fields import properties import representations import term from term import Term as T from ipdb import set_trace as debug import dispatch import strings #TODO I should be allowed to have representation changes interleaved with updates? #FIXME the expl...
999,629
cd575be7f20f3ca2b1f9d8144e9422c19b6875aa
# Given a linked list, rotate the list to the right by k places, where k is non-negative. # Example 1: # Input: 1->2->3->4->5->NULL, k = 2 # Output: 4->5->1->2->3->NULL # Explanation: # rotate 1 steps to the right: 5->1->2->3->4->NULL # rotate 2 steps to the right: 4->5->1->2->3->NULL # Example 2: # Input: 0->1->2-...
999,630
e8011f792a8c39d8a0be6ff40586e0911406d1ee
from django.shortcuts import render from django.http import HttpResponse from django.views import generic from django.urls import reverse from .models import webContent, Artpiece def home(request): # think about making this another static .py file to change later # also add in my welcome message to it instea...
999,631
a3614272c8925e97e549b426733c18b94418429b
from django.contrib import admin from dal import autocomplete from .models import Topic from .forms import TopicForm # Register your models here. class TopicAdmin(admin.ModelAdmin): form = TopicForm fieldsets = ( (None, { 'fields': ('title', 'slug', 'parent_topic', 'description', 'tags...
999,632
965ff8ec6ef19347d5208f82c8fb39d65402ae9a
#!/usr/bin/env python3 """ 用于测试客户端修改属性 """ import socket import time HOST = 'localhost' PORT = 9998 def main(): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) # send_data=b'12.12,325.40,83.71,15.52,38.63,76.51,193.03,258.50,258.70#13.11,331.50,83.46,1...
999,633
d6d0c2ef5e399815432ded0580c47e312ad24b1e
from dateutil.relativedelta import relativedelta from django.contrib.auth import get_user_model from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from softdelete.models import SoftDeleteModel User = get_user_model() class TimeStampedModel(models.Mo...
999,634
3a2627b477e2717eb63afd9371928725665cfc4e
../../scripts/convertMetadataRCDB.py
999,635
c21759c88ff4ae8e79004551231d020cf2a6961f
from google.appengine.ext import ndb import json from model.package import Package class SerializeHelper(object): @staticmethod def serialize_to_dict(ndb_model_instance, exclude_properties=[]): result = ndb_model_instance.to_dict(exclude=exclude_properties) if ndb_model_instance.key: ...
999,636
2068cae8b9362794ae87f14b65dd0428c487aabf
def my_func(s): global flag sum = 0 flag = False for i in s: if i.isdigit(): sum += int(i) if i == "q": flag = True break return sum total = 0 while True: my_list = input("Stroka: ").split() total += my_func((my_list)) print(total) ...
999,637
7fe897a61c85e1dab110cab381adff881d9728eb
import numpy as np import pandas as pd import re import string import nltk import matplotlib.pyplot as plt import tensorflow as tf import seaborn as sns from sklearn.feature_extraction import text from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from sklearn.metrics imp...
999,638
2f772a28852f67144363e9729d5c08d7540858f7
from PIL import Image img=Image.open('IMG.PNG') im=img.convert('RGB') im.save('IMG.pdf')
999,639
676b6add9021f5fd9b4a45a3a4dd64c156b89e8c
#tuple_nesting_example_005.py # Tuples can contain nested elements i_am_a_nested_tuple = ((1,2,3), (4,5,6), (7,8,9)) print ( i_am_a_nested_tuple ) # Real world example # dwarves = ( (1, "Dopey"), (2, "Grumpy") ,(3, "Sneezy"), ( 4, "Bashful"), (5, "doc"), ( 6, "Happy"),( 7, "sleepy")) print (dwarves) # Using ...
999,640
44cecdd3635058727c524ea11eec83fa1107c64d
# Generated by Django 2.2 on 2020-05-17 08:35 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mysite', '0009_category_image'), ] operations = [ migrations.AlterField( model_name='category', name='image', ...
999,641
1881be2d7f3df25b8220f7fa236406ab649e2720
def moveStone(stones:list): stones.sort() n = len(stones) mx = stones[n-1] - stones[0] -n+1 mx -= min(stones[1]-stones[0]-1,stones[n-1]-stones[n-2]-1) mi = mx right = 0 for left in range(n): # find the stones already in this windows([le, le + n - 1]) while right<n-1 and stones[right+...
999,642
6f1e931a7860756de8f2e49d8c7572adb623c3f3
#!/usr/bin/env python #-*- coding:utf-8 -*- ######################################### # Function: To get the io state # Usage: python get_io_status.py # Date: 2015-11-25 # Version: 1.0 ######################################### import subprocess import sys def io_stats(device,item): child1 = 'ios...
999,643
3b4fad50f980f3cab2d1653fef6a13dcb7e80277
import os CDN_DOMAIN = os.getenv("CDN_DOMAIN", None) CDN_HTTPS = True RATELIMIT_HEADERS_ENABLED = True RATELIMIT_HEADER_RETRY_AFTER_VALUE = "delta-seconds"
999,644
f2a4a6fb9deefed4c07e71fe86ead90bd6073b90
from tensorflow.keras.preprocessing import image from tensorflow.keras import models import cv2 import numpy as np import argparse from tensorflow.keras.preprocessing import image from tensorflow.keras.applications import mobilenet_v2 ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, ...
999,645
545d82e5a8d6a38a0ffed9832cd54ecccb9ca607
a = input() b = input() a_dict, b_dict = {x:0 for x in range(1,10)}, {x:0 for x in range(1,10)} for c in a: a_dict[int(c)] += 1 for c in b: b_dict[int(c)] += 1 def find_match(num=10): for i in range(1,10): if a_dict[i] != 0 and b_dict[num-i] != 0: return i,num-i
999,646
d8ac7030260ac0f30ab55947e5e75dea1f582e9c
students = [ {'name': 'Rezso', 'age': 9.5, 'candies': 2}, {'name': 'Gerzson', 'age': 10, 'candies': 1}, {'name': 'Aurel', 'age': 7, 'candies': 3}, {'name': 'Zsombor', 'age': 12, 'candies': 5} ] # create a function that takes a list of students and prints: # - Who has got more candies th...
999,647
f264612b85678c423b5cafec0c4d128ddf9a9b7f
#!/usr/bin/env python # -*- coding: utf-8 -*- """Utility functions used for training a CNN.""" import keras as ks import os import numpy as np from keras import backend as K from input_utilities import * from generator import * from plot_scripts import plot_input_plots from plot_scripts import plot_traininghistory fr...
999,648
3e6a39875bd27ce4f9762a0ced2fc0a8cc0fee3d
#!/usr/bin/env python import os os.environ['DJANGO_SETTINGS_MODULE'] = 'socialchan.settings' import django django.setup() import pika from pickle import loads, dumps from base64 import b64decode, b64encode import functions #parameters = pika.URLParameters('amqp://empifJS6:JLdttxhTIzSoZSsgWvbPf8PFTRySIifY@leaping-marjo...
999,649
88915163509c9b81f059cb917e76a9e4cfc2b281
# -*- coding: utf-8 -*- """ Created on Mon Sep 11 11:46:21 2017 @author: Philipp """ import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint #import colorcet as cc #from datetime import datetime #import matplotlib.collections as collections from scipy.signal import argrelextrema, hilber...
999,650
034c6678f4cdbf5e305ccd11ba0fc42f5dacc403
# Generated by Django 2.0.3 on 2018-04-17 18:03 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('projects', '0007_auto_20180325_1605'), ] operations = [ migrations.CreateModel( name='Column', ...
999,651
a77314b3ef00f3a35076c3a995db677cb20f1a49
import logging from matplotlib import pyplot as plt from scipy.stats import binom import config from utils import get_json_from_file, SECONDS_IN_MONTH def prompt_tech_selection(technologies=config.TECHNOLOGIES): """ Ask user to select a technology from the list, return selection """ print("Select te...
999,652
bf1824be116e29cc383b901615791ddc76298936
from django import template from django.conf import settings import datetime register = template.Library() @register.simple_tag def requirejs_version(): version_str = '' if settings.JS_BUILD_VERSION: version_str = settings.JS_BUILD_VERSION elif settings.DEBUG: version_str = datetime.datetime.now().str...
999,653
cdec42e5e3f4f9a914f5b2d2a4fbff5ec44b83b2
k = input().split() n1 = int(k[0]) n2 = int(k[1]) ans = n1 * n2 print(ans)
999,654
fe979a65bce5a25ea8e2585971ca0b94694e35c3
import cv2 import numpy as np import matplotlib.pyplot as plt BLUE, GREEN, RED = (255, 0, 0), (0, 255, 0), (0, 0, 255) WHITE_LOWER, WHITE_UPPER = (200, 200, 200), (255, 255, 255) BLACK_LOWER, BLACK_UPPER = (0, 0, 0), (10, 10, 10) def create_trackbar(): def nothing(): pass cv2.namedWindow("Trackbar") cv2.creat...
999,655
23d978bad36233873ffddbc0cc24925be0f677c2
#imports import pymysql #functions def create(data): connection = pymysql.connect("localhost","root","helloworld","lifesaver") cursor = connection.cursor() query = "INSERT INTO donors VALUES('{}','{}','{}','{}','{}','{}','1998-07-08');".format(data['name'],data['city'],data['email'],data['phone'],data['bloodgroup...
999,656
6789a3578556d8c40d341ab3010a3fadfaf3e315
import json import operator import os #input file filepath = "../Data/tokenized/" #output file lpath = "../Data/all_labels.json" max_index = 10 fw = open(lpath,'w') labels = dict() def getLabels(fil): fin = open(fil,'r') data = json.load(fin) for row in data: for each in row["tags"]: ...
999,657
1888c0128cfb80efad93875e343b22eee7d2c900
import numpy as np x = [[10, 20], [14, 18]] X = np.array(x) y = [[1.7], [1.4]] y = np.array(y) def sigmoid(x, deriv = False): if deriv == True: return sigmoid(x)*(1 - sigmoid(x)) return 1/(1 + 2.718281**(-x)) class NeuralNetwork: def __init__(self, X, hidden1, hidden2, hidden3, num_class): ...
999,658
f8f34bdbbe39b188b92542a91dc28f04cc5004bd
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import sys from ast import literal_eval from textwrap import dedent from typing import List, Set from unittest import skipIf import libcst ...
999,659
646d5eb158ec122f71dba04b0676e646bf0c04a3
from tutorialpress.core.views.categoria import CategoriaViewSet from tutorialpress.core.views.publicacao import PublicacaoViewSet
999,660
6fa14cf56759263bfa5410e87688b5e7c8384cd6
from .base import * import os DEBUG = False DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'blogdb', 'USER': 'admin', 'PASSWORD': 'Rhoden5130!', #いつかRDSに分けた時用 'HOST': 'blogdb.caa7627qv4ac.ap-northeast-1.rds.amazonaws.com', 'HOST': 'ip-172-31...
999,661
49f2fd91ec73dfa54baef8bc5efd6d1073db36c3
#!/usr/bin/env python # -*- coding: utf-8 -*- # @author: 'orleven' import os from lib.core.data import paths from lib.utils.connect import ClientSession from lib.core.enums import VUL_LEVEL from lib.core.enums import VUL_TYPE from lib.core.enums import SERVICE_PORT_MAP from script import Script class POC(Script): ...
999,662
584b17176691594cbd32fb0ed9208c0971dfe646
''' Created on Sep 28, 2011 @author: Arif ''' import xmlrpclib if __name__ == '__main__': s = xmlrpclib.ServerProxy('http://localhost:8080') print "test()" print ">>", s.test()
999,663
4897fabae99941264f29fc56ed430ebfb29e3725
__author__ = 'will' import pickle import numpy as np data = pickle.load( open( "trainingdata.p", "rb" ), encoding="latin1" ) n_images = len(data) test, training = data[0:int(n_images/3)], data[int(n_images/3):] def get_training_data(): trX = np.array([np.reshape(a[2],a[2].shape[0]**2) for a in training]) pr...
999,664
81694c64fa592a374d06e9bd0bc8fcd634197f4e
cases = int(input()) for a in range (cases): flower, distance = [int(x) for x in input().split()] currentX = 0 currentY = 0 counter = 0 for b in range(flower): fx, fy = [int(x) for x in input().split()] distance -= (abs(currentX-fx)**2 + abs(currentY-fy)**2)**0.5 currentX = fx currentY = fy if distance ...
999,665
fe6bb4a1b18fda23275f51c568bad66b8e3657d7
#!/usr/bin/env python # # 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.0OA # # Authors: # - Wen Guan, <wen.guan@cern.ch>, 2020 - 2021 import copy im...
999,666
435e0e42171adf5e98cd88d0397c475c408320d7
from .point_wise_feed_forward import PositionwiseFeedForward from .squeeze_embedding import SqueezeEmbedding from .attention import Attention from .bert_aen import BERTAEN from .bert_spc import BERTSPC
999,667
289ead22655b067efce3559bc6610eec44d2b291
import numpy as np def pca(x,k): u=np.mean(x,axis=0) #计算均值 x=x-u #均值归一化 sigma=np.cov(x,rowvar=0) #计算协方差矩阵 w,v=np.linalg.eig(sigma) #w为特征值 v为特征向量 index=np.argsort(-w) #特征值从大到小排序,返回索引 index_change=index[:k] #取前k个 v_change=v[:,index_change] z=x.dot(v_change) return z
999,668
ddf61398be8d3022c7b3994460c725dc2613da64
from twisted.internet.protocol import Factory from twisted.internet import reactor, protocol from network.UOPacketRx import * from config.uopy import UoPYConfig import globals uoConfig = UoPYConfig() class UOServerProtocol(protocol.Protocol): def __init__(self, factory): self.factory = factory def c...
999,669
400c9ea2fe642a135b842f5487ce70b0b73730c3
>>> items = ['aaa', 111, (4,5),2.01] >>> tests = [(4,5),3,14] >>> for key in tests: ... for item in items: ... if key == item: ... print(key,'was found') ... break #替代方案: for key in tests: if key in items: print(key,'was found') else: prin...
999,670
346244590108c675cac278de7ab88f89623e5a87
import requests from datetime import datetime import config class FriendsParser: client_id = 7881208 client_secret = config.client_secret display = 'page' scope = 'friends' def __init__(self): print('Parser object was created...') self.token = '' self.access_token = '' ...
999,671
04309b3aebed9ad2e254500c878082c411874de8
# # Copyright (C) 2013 Andrian Nord. See Copyright Notice in main.py # from ljd.util.log import errprint import ljd.bytecode.instructions as ins import ljd.rawdump.constants import ljd.rawdump.debuginfo import ljd.rawdump.code FLAG_HAS_CHILD = 0b00000001 FLAG_IS_VARIADIC = 0b00000010 FLAG_HAS_FFI = 0b00000100 FLAG...
999,672
fac9546a48ef3f3c0f1fda2c6770429b43ff35db
def judge(string, head, tail): if head >= tail: return True if string[head] == string[tail]: return judge(string, head + 1, tail - 1) else: return False if __name__ == '__main__': string = input("input your string: ") if judge(string, 0, len(string)-1): print("{} 是回...
999,673
d17ebbd9a57ddc4d34445531aaaf510de6af6d4c
""" Database calls """ from app.util.mssql import MSSQL def get_user_etrade_params(userId): with MSSQL() as db: sql = """ SELECT * FROM dbo.Users_Etrade_Session WHERE UserID = ? """ return db.query_one(sql, (userId,)) def save_auth_request(token, s...
999,674
31115626675943b41e17f8630d0289057c8635e9
from threading import Lock class RWLock(object): """ RWLock class; this is meant to allow an object to be read from by multiple threads, but only written to by a single thread at a time. Original Source Code: https://gist.github.com/tylerneylon/a7ff6017b7a1f9a506cf75aa23eacfd6 Credit: Tyl...
999,675
70c1239bbbab7d7cccbeaaceaa16c9cd891bd235
from cx_Freeze import setup, Executable copyDependentFiles=True silent = True includes = ["lxml", "lxml._elementpath", "lxml.etree", "pyreadline", "pyreadline.release", "gzip"] excludes = ["tcl", "tk", "tkinter"] setup( name = "The Mole", version = "0.3", description = "The Mole: Digging up your data", ...
999,676
b99fe97ca5d2d529c670a89ebc266e574e163fc9
#!/usr/bin/env python3.7 # FULL LINE COMMENT print("Hello, World!") # Trailing Comment
999,677
67f79944a0d8db49d6c6226e9f115f6cd9f1e628
#this is static load balancing for the mobile back haul # Copyright (C) 2011 Nippon Telegraph and Telephone Corporation. # # 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://ww...
999,678
0676a10180068ddaa4c0ec2a5c36e0901e31fa1b
import django_userhistory.models as models from django.contrib import admin try: admin.site.register(models.UserAction) admin.site.register(models.UserHistory) admin.site.register(models.UserTrackedContent) except Exception, e: pass
999,679
2e261ddb9df959ead1419419ae64135536fa83ea
# -*- coding: utf8 -*- import inspect import os import sys import random import time import multiprocessing import logging import socket import select import unittest BASE_TEST_PATH = os.path.join('test', 'data') RANDOM_SEED = 42 NUM_DIRS = 10 NUM_SUBDIRS = 10 FILES_PER_DIR = 10 FILE_SIZE = 1024*8 RANDOM_DATA_BUF_SIZE...
999,680
55c8bdc42efd0affdc0e57c77816b66a38ce931d
import csv def write_to_csv(list,mode): fieldnames = ['id', 'title', 'year', 'runtime', 'genre', 'director', 'cast', 'writer', 'language', 'country', 'awards', 'imdb_rating', 'imdb_voutes', 'box_office'] with open('Backend_movies.csv', mode, encoding='utf-8' ) as nn: csvwriter = csv.DictWrit...
999,681
3e87984bf8590f3d9ce0482e0b1a6cd3b22c8dad
# -*- coding: utf-8 -*- import asyncio import structlog from async_timeout import timeout from sanic import response import ujson from ..typedefs import HTTPRequest from ..typedefs import HTTPResponse from ..utils import async_include_methods from ..utils import async_nowait_middleware logger = structlog.get_logger...
999,682
959aafc23368084c7abb27d183f3699ad1736740
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/8/2 17:57 # @Author : LiangJiangHao # @Software: PyCharm import os import sys import requests from lxml import html import json import time import bs4 from selenium import webdriver driver=webdriver.Chrome() f=open('url.txt','a+') for x in range(1,50): p...
999,683
ee8cb5f01eb461710e1f5cd4ed76621c48c3d204
import getpass from netmiko import ConnectHandler import smtplib from email.mime.text import MIMEText uname = raw_input("Enter your username: ") pswd = getpass.getpass(prompt="Enter your Password: ") result = [] test def sendemail(mes): fromaddr = "TCAMStatus@abc.com" toaddr = ['Network@abc.com'] message ...
999,684
337eefa85cfe4d2bccfaac4f73de6b336e933ed5
from pui_tk import Application from pui_tk.types import Side from pui_tk.widgets import Label if __name__ == '__main__': app = Application('Packing examples') app.pack(Label(app, text='pack-left'), side=Side.LEFT) app.pack(Label(app, text='pack-right'), side=Side.RIGHT) app.pack(Label(app, text='pack-...
999,685
736168a20f252d034df9bc4ee88a7e610779bebc
#!/usr/bin/env python # coding: utf-8 # In[8]: #付録14.A get_ipython().run_line_magic('matplotlib', 'inline') import matplotlib.pyplot as plt from datetime import datetime, date import pandas as pd import csv import numpy as np def readcsv(file_name): trades=[] with open(file_name,'r') as f: series=c...
999,686
a66c9149c80063830351addee889d194ec8034ab
import pandas as pd import numpy as np import matplotlib.pyplot as plt # Loading the raw dataset rawMovieData = pd.read_excel('2014 and 2015 CSM dataset.xlsx') # Start cleaning # ---> Start with missing values rawMovieData.isnull().sum() # ---> In 'Budget' only 1 row is NA so we can drop it rawMovieData.dropna(subse...
999,687
3c8c67ee5eefa44cc0957428adafc90cb63d5eb1
""" Created on Thu Oct 25 15:54:19 2018 General function script to load from @author: alexschw """ import itertools import numpy as np def Gaussian2D(Amp, Shape, Sig): """ Computes a 2D gaussian with given amplitude, shape and width (sigma) """ Sig = np.array(Sig) # If one or both of the shape val...
999,688
9e98d65560f6e2a8cc3ecbcf655d236433effb3d
fun main() { val x = "${String::class.toString()}" println("${x}.hello") println("${x.toString()}.hello") println("${x}hello") println("${x.length}.hello") println("$x.hello") }
999,689
15c7e2b5bc98c45c069fca2e4a42e174a8f5526c
class Computer: def __init__(self): self.on = True def are_you_on(self): if self.on: return 'Yes' else: return 'No' def is_computer_on(): computer = Computer() return computer.are_you_on()
999,690
1740fbf4212e6cd9ac45122b7fac25b33305a1d2
from mpi4py import MPI import numpy as np comm = MPI.COMM_WORLD rank = comm.rank num_procs = comm.Get_size() if rank == 0: num_trials = 2 trial_seed_list = list(zip(range(num_trials),0.03 + 0.04*np.random.rand(num_trials))) trial_chunk = np.array_split(trial_seed_list, num_procs) else: trial_chunk = N...
999,691
2ab983da96fd130e1df8b3405d2596731cc05240
import socket, ssl import threading from connectionHandler import handleConn useSsl = False def serverInit(host, port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, port)) s.listen(5) return s def serverLoop(): s = serverInit('', 5777) while True: conn, addr ...
999,692
f6f120d71abbea56709c0d7e1dada22fd1e5b8c5
from TournamentResults import * import random import time class Ranking(TournamentResults): def __init__(self, results, ranking, ks=None): self.ranking = ranking self.results = results if ks: self.ks = ks else: self.ks = self.calculate_ks() # Calculates...
999,693
02db92d5561cfd0546fde59d90cd0438a52eef26
from django.apps import AppConfig class MyblogApiConfig(AppConfig): name = 'myblog_api'
999,694
915e8064b13acd9f49ea78ca363b6f007bdb017f
import time import nomad # Create a Nomad client client = nomad.Nomad() # Create a batch of jobs to submit to Nomad jobs = [{ "Name": "stress-test-job", "Type": "batch", "Datacenters": ["dc1"], "TaskGroups": [{ "Name": "stress-test-task-group", "Tasks": [{ "Name": "stress-t...
999,695
d0b8a95fce0dd466c7eea507f75746b12bc57fc8
from setuptools import setup, find_packages cemba_data_version = '0.1.2' setup( name='cemba_data', version=cemba_data_version, author='Hanqing Liu', author_email='hanliu@salk.edu', packages=find_packages(), description='A package for processing and analyzing single cell sequencing data.', ...
999,696
cc79f47cd1e97eb8522821fade3a6d86369f853a
# DSP functions such as applying noise, RIRs, or data representation conversions import numpy as np import pandas as pd import random as rnd import librosa as lr import time import os import os.path as osp import scipy from libs.colored_noise import powerlaw_psd_gaussian # generate seed from the time at which this sc...
999,697
83b86ee46f2a03a242b3a72bfaaf742bbc7224aa
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import mean_squared_error, mean_absolute_error from sklearn.model_selection import RandomizedSearchCV from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_score, KFold from sklearn....
999,698
35caf5c5e07f279a21549105e0fd5485420e8b67
import sys (python_ver, _, _, _, _) = sys.version_info import os from setuptools import setup, find_packages name = 'querycontacts' description = "Query network abuse contacts on the command-line for a given ip address on abuse-contacts.abusix.org" long_description = description cur_dir = os.path.abspath(os.path.dirn...
999,699
b41d1f9969f42b30a61a7dcfb5c211b716c45ac4
''' Vendored version of django-easymoney. Putting directly in otree-core because PyCharm flags certain usages in yellow, like: c(1) + c(1) Results in: "Currency does not define __add__, so the + operator cannot be used on its instances" If "a" is a CurrencyField, then self.a + c(1) PyCharm warns: 'Currency ...