index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
992,100 | 1f80f42bd74137e9d599cd33b4955383a332d61f | """
Created on 2/6/2019
@author: Jingchao Yang
Table join for one-to-one match post time and coordinates with tid
"""
from psqlOperations import queryFromDB
import csv
dbConnect = "dbname='harveyTwitts' user='postgres' host='localhost' password='123456'"
tb_join1 = "original_credibility_power"
tb_join2 = "original_... |
992,101 | 7ae42fc565ce68cf27db143413a7878536d75903 | /Users/jieqianzhang/anaconda3/lib/python2.7/sre_parse.py |
992,102 | 47a0d37834e16553b6590e01b94e3580228bda8f | #!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as pyplot
import imag_manip_gen3 as g
import fitness_ext as f
IMG_SHAPE = (240, 300, 3)
indfactory = g.IndividualFactory(120)
def draw_in_grid(img, shape, row, col):
pyplot.subplot(shape[0], shape[1], shape[1]*row + col + 1)
pyplot.axis("off... |
992,103 | c3bd013e280943adfbd919904aa574139d38974d | #!/usr/bin/python3
# Simple wrapper for some command line NTLM attacks
import argparse
import sys
import os.path
import subprocess
from urllib.parse import urlparse
import re
import time
import signal
def test_login( username, password, url, http1_1 = False ):
global args, found, foundusers
username = username.st... |
992,104 | e59daaf3a88854a7d38453d7db64453214b93e99 | import pytesseract
import numpy as np
from . import ImageAnalyser as ia
import logging, importlib
from .settings.Point import Point
from .settings.Rectangle import Rectangle
logger = logging.getLogger("ZombidleBotLogger")
timesReadArea = 0
def reloadModules():
importlib.reload(ia)
def checkShard(img, settings):
... |
992,105 | 068245f83279975e17d709f532374d4a91cf065a | from django.db import models
from django.conf import settings
# Create your models here.
from django.db.models.signals import post_save
from tweets.models import Tweet
class UserProfileManager(models.Manager):
use_for_related_fields=True
def all(self):
qs = self.get_queryset().all()
#excludi... |
992,106 | f4e6a9f1e7cb328613ddaaac0674bbe11f4cdc46 | import numpy
from math import log2, sqrt
from scipy.linalg import solve
from decimal import Decimal
def pi(k):
a = Decimal(2) ** Decimal(0.5)
for i in range(0, int(log2(k / 4))):
a = ((a / 2) ** 2 + (1 - (1 - (a / 2) ** 2).sqrt()) ** 2).sqrt()
return float(k * a / 2)
def pi1(k):
b = 1
fo... |
992,107 | d72a4ffee20cb96880166e88a5be550a37eebc2c | import time
import sys
import requests
from bs4 import BeautifulSoup
from splinter import Browser
mainUrl = "http://www.supremenewyork.com/shop/all"
baseUrl = "http://supremenewyork.com"
#productUrl = "http://www.supremenewyork.com/shop/t-shirts/morrissey-tee/white"
checkoutUrl = "https://www.supremenewyork.com/checko... |
992,108 | c9547dc6342c0b0109f74e5d716a4965f206225b | # -*- coding: utf-8 -*-
print('some string')
print('I\'m lovin\' it')
print('C:\some\name')
print(r'C:\some\name')
print("I'm lovin' it")
print('some\n string')
print("some\n string")
|
992,109 | 62bde232ee96318ddbec85d863eb0661a8eed2d3 | from algorithms.primitive_algorithm_v3 import PrimitiveAlgorithm_v3
from algorithms.algorithm_v2 import Algorithm_v2
from metrics.parser_result_levenstein_metric import ParserResultLevensteinMetric
from parsers.ideal_parser import IdealParser
def get_max_distance(algorithm, golden_set):
path = "../golden/" + gold... |
992,110 | 35bf8969f763b6acab55d15b008effe989762d48 | from django.db import models
class companies(models.Model):
#Serial ID automatically created by django
company_name = models.CharField(max_length=500, blank = False, unique = True, primary_key = True)
def __str__(self):
return self.company_name
class headlines(models.Model):
#question = model... |
992,111 | b5dd76d8590a9964804665d5ffce7d6101c4c474 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#from setuptools import setup, find_packages
with open("README.md") as f:
long_description = f.read()
with open('mahstery/__init__.py', 'r') as f:
for line in f:
if line.startswith('__author__'):
author = line.split('=')[-1]
if line.st... |
992,112 | a45e87c478785a880227bc64c1f7d853112c196f | import streamlit as st
import pandas as pd
import numpy as np
import tweepy
from textblob import TextBlob
from wordcloud import WordCloud
import pandas as pd
import numpy as np
import re
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
def extractTweet(number, sname, api):
posts = api.user_timel... |
992,113 | e3b14c6b22157d4504db870bf38f7311b4a479b1 | g = sns.JointGrid(x="total_bill", y="tip", data=tips)
g = g.plot(sns.regplot, sns.distplot)
|
992,114 | 68f9f5dbcacb2b11ca64878e7b7c32ed3af9daf4 | # Рекурсивная функция для чисел Фибоначчи
def fib(n):
# Условия выхода из рекурсии
if n == 1:
return 1
elif n == 0:
return 0
else:
# Рекурсивный вызов
return fib(n-1) + fib(n-2)
# Ввод кол-ва чисел
n = int(input())
# Список для чисел
nums = []
# Открываем файл
f = open(... |
992,115 | 1e62cfb4a71af196cb4a4c011f7c7e5a6f1416c5 |
class Db:
DEPTH_PARAM_NAME = 'depth'
def __init__(self, conn, sql):
self.conn = conn
self.cursor = conn.cursor()
self.sql = sql
self.depth = None
def setup(self, depth):
self.depth = depth
self.cursor.execute(self.sql.create_word_table_sql(depth))
self.cursor.execute(self.sql.create_index_sq... |
992,116 | 38ebe623c99052bc0726048e10fe3735788e00b0 | from typing import Callable, List
from dataset_specific.ists.parse import iSTSProblemWChunk
def get_similarity_table(problem: iSTSProblemWChunk,
score_chunk_pair: Callable[[str, str], float]) -> List[List[float]]:
n_chunk1 = len(problem.chunks1)
n_chunk2 = len(problem.chunks2)
ta... |
992,117 | a37e043abe4afc2c17bd5066ca08c174fd842577 | from plasmapy.classes.sources import openpmd_hdf5
from plasmapy.utils import DataStandardError
from plasmapy.data.test import rootdir
from astropy import units as u
from typing import Union, Tuple, List
import os
import pytest
class TestOpenPMD2D:
"""Test 2D HDF5 dataset based on OpenPMD."""
# Downloaded fro... |
992,118 | 9979b99235b5a290576e6cacb1649026353fea4e | import unittest
class Solution:
# The largest rectangle can be obtained by iterating over all height[i], finding heights[r] and heights[l],
# where l < i and heights[l] is the first bar < heights[i], and r > i and height[r] is the first bar < heights[i],
# then multiplying the height (h = height[i]) by th... |
992,119 | 61b134d6fbcbf9efff18abb863ccdba0af2ba6e5 | import random
score = 0
sys_score = 0
print('''Yapacağınız hamleyi girin:
1)Taş
2)Kağıt
3Makas''')
while True:
if score == 3:
print("Maçı sen kazandın")
break
if sys_score == 3:
print("Maçı system kazandı")
break
hamle = int(input("Hamlenizi giriniz:"))
sys... |
992,120 | 682998b2ef695b01e6992e1576ba1508f8f96995 | def read_file(fnm):
fp=open(fnm,'r')
t=[]
for line in fp:
line=line.strip().split(',')
t.append(line)
print(t)
def main():
x="vet.txt"
read_file(x)
main()
|
992,121 | cc3e8b6a5d142c896438c8da736a57462fbd476f | #!/usr/bin/env python
#-*- coding: utf-8 -*-
"""
=============
Main
=============
Aquest mòdul és el que s'haurà d'inicialitzar per obtenir tota la funcionalitat.
Per començar es crearà una instancia de la :class:`iTICApp.iTICApp` i de :class:`Interpret.Interpret`. Al inicialitzar
l'intèrpret se li passarà unes quant... |
992,122 | be529d177f2550a63848ebd91c294039d9e297bf | # created by KUMAR SHANU
# 1. Binary Search
# https://leetcode.com/problems/binary-search/
class Solution:
def search(self, nums: List[int], target: int) -> int:
# find boundaries
l, r = 0, len(nums) - 1
while l <= r:
# find middle element
mid = l + (r - l) // 2
... |
992,123 | ad3dac92d738288460ce0c2091d4e46b27b3e768 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 31 16:23:50 2019
@author: Luke
"""
class Ipython():
@staticmethod
def run_from_ipython():
try:
__IPYTHON__
return True
except NameError:
return False
class timing():
import threading
from datetim... |
992,124 | 7ed6b06464645ddd5c4ee98952e8746b16cbc691 | import requests
r = requests.get('http://0.0.0.0:8000/get_stock/DOCU')
print(r.json())
|
992,125 | 9672eecf7143e7926a2ef2617dae4e58b70b3b78 | import sys
p1 = 0
p6 = 42195
somatoria = 0
msg1 = "Marquinhos termina a prova"
msg2 = "Marquinhos nao termina"
msg3 = "Valor invalido"
p2 = int(input("posicao 2: "))
if p2 <= p1:
print(msg3)
sys.exit()
else:
d = p2 - p1
if d <= 10000:
somatoria = somatoria + d
p3 = int(input... |
992,126 | 1de95c6d05f07a5b3a08a9c71e977ae340e26cf1 | import os
class Config:
def __init__(self):
self.SQLALCHEMY_DB_URI = os.getenv("SQLALCHEMY_DB_URI", "sqlite:////data/db/tools.db")
self.SQLALCHEMY_ECHO = os.getenv("SQLALCHEMY_ECHO") == "True"
self.DEBUG = os.getenv("DEBUG") == "True"
self.SENTRY_DSN = os.getenv("SENTRY_DSN", "")
... |
992,127 | b2707e621a7d6dcdeea42654cd713f24f56ff162 | import socket
from _thread import *
server = "ip_address"
port = 5555
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
s.bind((server,port))
except socket.error as e :
print(str(e))
s.listen()
print("Server Initialized....\n\nWaiting FOr Connections..\n")
def readpos(str):
str... |
992,128 | 7fbf90d8d17d2de65a55409d85a78818ba0dbc87 | import json
#open twitter data
with open('/Users/maddie/Desktop/twitter-2020-02-11-a78b07526621ffada3b98a8686afc07c4602cbde62e511b321765432f525f2e7/tweet.js', 'r') as f:
data = json.loads(f.read())
"""
extract from the data:
1. percentage of my tweets which were retweets of other users content
2... |
992,129 | c8820ec3e606b6b65253606ac4eff08026d3c036 | from copy import deepcopy
from abc import ABC, abstractmethod
from ..models import Dealer, PlayerAction
from ..game_controller import *
class BaseAI(ABC):
"""
The abstract base class of all AI classes.
"""
def __init__(self, dealer_id, total_money):
self.dealer_id = dealer_id
self.i... |
992,130 | a439f7b1da6fced7c66884f02c697326cbc289b2 | #!/usr/bin/python
#_*_coding:utf-8_*_
import sys
def load_users_jobroles_and_studyFields(file):
userBasicFeature = dict()
userJobrole = dict()
userStudyField = dict()
with open(file, "r") as fin:
for line in fin:
segs = line.strip().split(" ")
user = segs[0]
jobroles = []
studyFields = []
if s... |
992,131 | a4b78303ba485dd0e85b9357088716f8310e0714 | from collections import defaultdict
class River(object):
def __init__(self, numOfElements=100):
self.rank = [0 for _ in range(numOfElements)]
self.parents = [0 for _ in range(numOfElements)]
self.n = numOfElements
def init (self, numOfElements):
self.makeSet()
def makeSet... |
992,132 | e9824ab0d47279c78d3029487d9b5c93f8c004f9 | from ._stream import Stream
from ._hoverlabel import Hoverlabel
from plotly.graph_objs.heatmap import hoverlabel
from ._colorbar import ColorBar
from plotly.graph_objs.heatmap import colorbar
|
992,133 | 47e045d634924761b2f6073155b174b1c55666d1 |
#TODO: inheritate from bluecopper base class
class TFT_Experimen(Base):
__tablename__ = 'tft_experiment'
exp_id = Column('exp_id', String)
schema_id = Column('schema_id', String)
# @validates()
def __repr__ (self):
return "<TFT_Experiment(exp_id='%s', schema_id='%s')>" % (
... |
992,134 | f0c19a53683b0e8779713748b3beac6d9925575d | from socket import *
server_port = 12000
server_socket = socket(AF_INET, SOCK_DGRAM)
server_socket.bind(("localhost", server_port))
print(f"* Server started at port {server_port}")
while True:
message, client_address = server_socket.recvfrom(2048)
print(client_address, message.decode())
modified_message =... |
992,135 | 1165693ee6a0049a5c2b1a2639e153056abed6b7 | import shlex
import subprocess
def exec_command(cmd: str):
command = shlex.split(cmd)
result = subprocess.Popen(command, stdout=subprocess.PIPE, universal_newlines=True)
return result.stdout.read()
def query_number_gpus():
output = exec_command('nvidia-smi --query-gpu=gpu_name,gpu_bus_id,vbios_vers... |
992,136 | f04bf1eb2b87e257386e6bfef4ea3ce7b5203fe1 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: alfred_yuan
# Created on 2019-01-28
import threading
import time
class Box(object):
lock = threading.RLock()
def __init__(self):
self.total_items = 0
def execute(self, n):
Box.lock.acquire()
self.total_items += n
Box.loc... |
992,137 | 0dfeb683cbca8ff5d2e7278ed82a8a93f1f7c320 | """ Task 3
Создать два списка с различным количеством элементов.
В первом должны быть записаны ключи, во втором — значения.
Необходимо написать функцию, создающую из данных ключей и значений словарь.
Если ключу не хватает значения, в словаре для него должно сохраняться
значение None. Значения, которым не хватило ключей... |
992,138 | 8a64037d01157dab1b6c574190b13e279d6140c1 | import zacks #1
import bloomberg #2
import cnbc #3
import investing #4
import fidelity #5
import yahoo #6
import json
import threading
import datetime
from datetime import timedelta
from datetime import datetime
def ZACKS(start_date, stop_date,output_path):
zacks.func(start_date, stop_date,output_p... |
992,139 | 3846d4250f5f43cdc8311b3a2f6008e61acfeb9a | '''
This file will hold logic for n-fold cross validation.
Methods:
*generateCrossValidationSets(X, Y, k=5, trainingMethod=None) normal creation of cross validation sets.
*leaveOneOutCrossValidation(X,Y, trainingMethod=None) has test set of length 1. All others become part of training set.
'''
... |
992,140 | 53b6ed510d2c0b1205c33203bfab3844a01662e3 | from __future__ import annotations
from typing import Dict, Union
import requests
from pvaw.constants import VEHICLE_API_PATH
from pvaw.results import Results, ResultsList
class Manufacturer(Results):
def __init__(self, man_id: Union[str, int], results_dict: Dict[str, str]):
super().__init__(man_id, resul... |
992,141 | c9867ed99f456907f88f3a1a923c51360ca08d9b | import pymongo
import Twitter_Request
import requests as r
import json
import Twitter_Token_Utils
import hashlib
import time
def check_update(file_hash):
f = open("user_ids.txt",'rb')
hashed_file = hashlib.md5(f.read()).hexdigest()
f.close()
return hashed_file == file_hash
def update_search_terms(search_terms):
... |
992,142 | d66d7afd3545e0f292a4c28898890b85e6ed2b46 | from utils.mappers import *
from utils.scn_libs import *
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
import xml.dom.minidom
import xml.dom
import collections
import types
import os
class start_rpc_server:
def __init__(self):
serv... |
992,143 | 938301a65e55e44aa4f2d5190d66952414875028 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 28 09:58:47 2016
@author: Eli Van Cleve
"""
import numpy as np
#import csv
import pandas as pd
#dir = '/mnt/g/Eli/RadiaBeam/SQF/'
dir = 'G:/Eli/RadiaBeam/SQF/'
filename = input ("Enter File Name: ")
save = filename[:-4]+'-clean.csv'
print (dir+filename)... |
992,144 | 35bc20269914b5396650fac7b79e8cf342c4e47c | # -*- coding: utf-8 -*-
"""Configuration parameters for each dataset and task."""
import logging
from math import ceil
import os
from os import path as osp
from colorlog import ColoredFormatter
from common.config import Config
class ResearchConfig(Config):
"""
A class to configure global or dataset/task-sp... |
992,145 | 29de1381e54377baefb11e5bf74dc8e6bd2b8f5b | '''
거스름돈 그리드 알고리즘
n원을 500,100,50,10원 중 최소 동전 개수 구하기
단 n원은 항상 10의 배수이다.
'''
N = int(input('N원을 입력하시오(단 N는10의 배수) : '))
money = [500,100,50,10]
cnt = 0
for money in money:
cnt += N//money
N%=money
print(cnt) |
992,146 | 64394ea4654d8477355f1337e0bb5906e4c7202f | from unittest import TestCase, mock
from unittest.mock import patch
from core.httpoperation import HttpOperation
from tests.core.replicatortest import ReplicatorTest
def mock_request_get(url, params=None, headers=None):
pass
def mock_request_post(url, data=None, json=None, headers=None):
pass
def mock_re... |
992,147 | da26d6bb422c06c66c887601abfb5cc88ed7351f | # -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# All rights reserved.
#
# 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 notice, this
# ... |
992,148 | b487bf9ebc81fb0ccda4bb4d990ce890ce9ac724 | #!/usr/bin/python3
"""
===============
cwexport module
===============
Module for exporting cloudwatch metrics to a pure text Prometheus exposition format
To DocTest: python3 cwexporter.py -v
Example usage:
>>> region='us-east-1'
>>> namespace='AWS/EC2'
>>> type(listmetrics(Region_name=region, names... |
992,149 | ddeb81c46b60d5f8aea5e274dbc3748a806e0b64 | # -*- coding: utf-8 -*-
"""
This is the PVcircuit Package.
pvcircuit.Junction() # properties and methods for each junction
"""
import math #simple math
import copy
import os
from time import time
from datetime import datetime
from functools import lru_cache
import numpy as np #arrays
import pandas as pd
imp... |
992,150 | ee18b3aa22cc758872a3e8061e9180be1748fb94 | from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms
class CreateUserForm(UserCreationForm):
password1 = forms.CharField(widget=forms.PasswordInput(
attrs={"name": "password1", 'placeholder': 'Mot de passe'}))
password2 = forms.Ch... |
992,151 | 35275ec2302cb0adab48400b25a5d32de5a6d132 | import threading
from time import sleep, time
from curl import request
successfull_requests_count = 0
un_successfull_requests_count = 0
class Requester(threading.Thread):
def __init__(self, uri, name, requests_count, headers={}, user_agent="PostmanRuntime/7.15.2", verbose=False):
super().__init__()
... |
992,152 | f78ec134eb5298bd4813f7b2486989d458ccd51d | #!/usr/local/python2711/bin/python
# *-* coding:utf-8 *-*
import re
import os
import sys
import time
import datetime
import subprocess
from time import clock as now
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
import socket
i... |
992,153 | 788e87d5962b75d7ed7190d7e5c66940b7657ec0 | import numpy as np
from scipy.integrate import odeint
def get_pendulum_data(n_training_ics, n_validation_ics, n_test_ics):
t,u,du,ddu,v = generate_pendulum_data(n_training_ics)
training_data = {}
training_data['t'] = t
training_data['x'] = u.reshape((n_training_ics*t.size, -1))
training_data['dx']... |
992,154 | 3371afa1f2a520d8b37268acb13f554e91108a25 | import gzip
import os
import tkFileDialog
import xlsxwriter
import Tkinter as tk
import numpy as np
class TemporalMeanFrame(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
... |
992,155 | 80ce028646bd5c22e3dd790c18490923f352f629 | import sh
def main(fname_pair_list):
for source_url, target_url in fname_pair_list:
if source_url.endswith('.zst'):
sh.zstd('-d', source_url, '-o', target_url)
else:
sh.cp('-v', source_url, target_url)
if __name__ == '__main__':
assert len(snakemake.input) == len(snak... |
992,156 | 9bf4bffdacbfb4d88c8073ad4b5ea96fed06d23d | class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
return self.common_prefix(strs)
def common_prefix(self, strs: List[str]) -> str:
min_str = len(min(strs, key=len))
N = len(strs)
lo = 0
hi = min_str - 1
prefix = ''
while (lo<=hi):
... |
992,157 | c1a3801ea5c05ae65f796a061c36fb675ee9027b | import numpy as np
import os
import random
import torch
from torch.utils.tensorboard import SummaryWriter
from model import RNNActorCriticNetwork
from env import create_train_env
from config import get_args
def main():
args = get_args()
device = torch.device('cuda' if args.cuda else 'cpu')
env = cr... |
992,158 | 7d3edac42df95953ac4c578c4e9a3dff09a7cb0e | from typing import Any
def add_operation(
dn, attributes, auto_encode, schema: Any | None = ..., validator: Any | None = ..., check_names: bool = ...
): ...
def add_request_to_dict(request): ...
def add_response_to_dict(response): ...
|
992,159 | bd68a43353a539b997c53162ae785ca4efb5a247 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
URL_QUERY = 'http://60.190.19.138:7080/stu/sel_result.jsp'
REGEX_TR = r'<tr>[\s\S]*?<\/tr>'
REGEX_TH = r'<th[\s\S]*?>[\s\S]*?<\/th>'
REGEX_TD = r'<td[\s\S]*?>([\s\S]*?)<\/td>'
REGEX_NUM = r'[\d\.]+'
REGEX_TIME = r'The above information up to ([\s\S]*?)<\/'
REGEX_BACK = r'hi... |
992,160 | 480acc91a85ff8c67923d801a40012ad744c78ee | # -*- coding: utf-8 -*-
# from odoo import http
# class SaleAnticipo(http.Controller):
# @http.route('/sale_anticipo/sale_anticipo/', auth='public')
# def index(self, **kw):
# return "Hello, world"
# @http.route('/sale_anticipo/sale_anticipo/objects/', auth='public')
# def list(self, **kw):
#... |
992,161 | 6262aa40e1855f02015da462646a699d762d9ed3 | import pytest
from feathr import Feature, TypedKey, ValueType, INT32
def test_key_type():
key = TypedKey(key_column="key", key_column_type=ValueType.INT32)
assert key.key_column_type == ValueType.INT32
with pytest.raises(KeyError):
key = TypedKey(key_column="key", key_column_type=INT32)
def test... |
992,162 | 716105f3330f230b3cde15f0dc692083745e1c49 | '''class Result:
def __init__(self, value):
self.value = value
def __str__(self):
return f'{self.__class__.__name__}(value={self.value})'
def add_value(self, value: int) -> 'Result':
self.value += value
return self
@classmethod
def get(cls, value) -> 'Result':
... |
992,163 | 6d267460a8401a769354177356cd7cc7ac1c4956 | from setuptools import setup, find_packages
with open('README.md') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(
name='long_range_convolutions',
version='0.1.0',
description='Efficient Long Range Convolutions for Point Clouds',
long_description=readme,
auth... |
992,164 | e5ce6b873af2584396d5746ecca76554dec190db | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2019-03-05 10:24
from __future__ import unicode_literals
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('idgo_admin', '0102_auto_20190225_1622'),
]
operations = [
migr... |
992,165 | 63b191cd1513b0510da9c358c75a0ba685aae615 | from jetee.base.config_factories_manager import ConfigManager
from jetee.base.config_factory import AnsibleTaskConfigFactory, AnsibleRoleConfigFactory
class TestConfigManager(object):
def test_config_manager_manages_config_factories(self):
config_manager = ConfigManager(
parent=u'', # this wo... |
992,166 | bb4d020b26d41be13720d85f24e945ba8ea67700 | def batas():
print("----------------------------------")
def star(x):
star=''
for _ in range(x):
star+=' * '
print(star)
star(5)
batas()
def star_reverse(x):
#star=' * '
k = x
for _ in range(x):
star=' * '*k
print(star)
k -= 1
star_reve... |
992,167 | 19956d3274e5e6ac818ed2b5b763834502744e17 | def stones(N: int, S: str)->int:
# 左から見た黒石の個数の累積和と
# 右から見た白石の個数の累積和を保持し
# その和が最小となる位置を探す。
black, white = [0] * (N+1), [0] * (N+1)
for i, c in enumerate(S):
black[i+1] = black[i]
if c == '#':
black[i+1] += 1
for i, c in enumerate(S[::-1]):
white[N-i-1] = whit... |
992,168 | f0719024bc29e76e787c14957588569b9c508fa2 | """Dask-based and dask oriented variants of physt histogram facade functions."""
from __future__ import annotations
from typing import TYPE_CHECKING, cast
import dask
import numpy as np
from dask.array import Array
from physt._facade import h1 as original_h1
from physt._facade import histogramdd as original_hdd
if ... |
992,169 | 767a0c7c227adbb7d693174c555fd432a7a092a6 | from s3ros import s3ros
|
992,170 | fc06599a0724d122a3af99e163820ec3f4a0c327 | # makeArray.py
# 배열 생성하는 여러 가지 방법
import numpy as np
# zeros : 요소가 0인 배열/행렬을 생성해주는 함수
print(np.zeros(3))
arr = np.zeros((2, 2))
print(arr)
arr2 = np.ones((3, 2))
print(arr2)
# 연립 방정식을 풀고자 할 때 사용(가우스 소거법)
# 크기가 3인 단위 행렬을 만들어 줍니다.
# 정방 행렬 : 행과 열의 크기가 같은 행렬
arr3 = np.eye(3)
print(arr3)
# 모든 요소의 값이 5인 2행 2열의 행렬을 생성
ar... |
992,171 | fb35f238e1981e0e9b4f46ab66a71c7de59dd01e | # Copyright 2016-2023 Swiss National Supercomputing Centre (CSCS/ETH Zurich)
# ReFrame Project Developers. See the top-level LICENSE file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
#
# Generic fallback configuration
#
site_configuration = {
'systems': [
{
'name': 'generic',
... |
992,172 | 63524ad454d1559ef2c06d8d8577a0b6cc3edf98 | from flask import Flask, render_template, request
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/more", methods = ["POST"])
def more():
name = request.form.get("name")
return render_template("more.html", name=name)
@app.route("/list")
def list():
list=["o... |
992,173 | c31762d21c8088d5d50b4d4e4dda9349899c5c96 | #!/usr/bin/env python3
import json
import base64
import unittest
import requests
import random
import time
#DOMAIN = "http://127.0.0.1:11501/"
DOMAIN = "http://webapplication:80/"
BASE_URL = f"{DOMAIN}api"
USERNAME = "simulator"
PWD = "super_safe!"
CREDENTIALS = ":".join([USERNAME, PWD]).encode("ascii")
ENCODED_CRED... |
992,174 | 9bd99c1c28570f9ba27cc8e45646d7dae73a4b51 |
from flask import Flask
import os
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
import api |
992,175 | df93dea41e853ebda0acb87d355ff305cc44be9e | #列表list
score=[90,80,60,20,95]
score1=90
scoere=80
scoere=60
scoere=20
scoere=95
print(score)
frined=["黑","黃","綠"]
things=[90,"黑",True]
print(things)
#{} []裡面順序會反過來
print(score[0])
print(score[3])
print(score[-1])
print(score[-2])
#位子0開始取到第2位不包刮第2位
print(score[0:2])
print(score[1:4])
print(score[0:])
print(score[:4])... |
992,176 | 28dc97541eb52424ebf708adfe4769f43dbabce9 | import numpy
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import LSTM
from keras.callbacks import ModelCheckpoint
from keras.utils import np_utils
import os
import re
import json
# I've used this tutorial: http://machinelearningmastery.com/text-g... |
992,177 | 48b3c92cc5934f7a7f72e6119122f30731987528 | from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
def plot():
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
xs =[1,2,3,4,5,6,7,8,9,10]
ys =[5,6,2,3,13,4,1,2,4,8]
zs =[2,3,3,3,5,7,9,11,9,10]
xt =[-1,-2,-3,-4,-5,-6,-7,8,-9,-10]
yt =[-5,-6,-2,-... |
992,178 | 9f1bcfe1ec918658010281069d56e45cdab2dd90 | from socket import * # for python Socket API
import time # for timestamp data
from threading import Thread # for handling multiple requests
# a method for creating UDP client threads in order to send data to servers
def client(ipv4, port, targetNode):
# an IPv4 socket is created with UDP
# AF_INET is Internet ... |
992,179 | f51bffc70cff988ad09a18ef472456b578bcf54a | # arguments, parameter, variable scope and return values
def myFunction(name):
print("You're name is: " + name)
def getName():
name = input("What is your name:")
return name
def runit():
print("Start the app ...")
myFunction(getName())
# run the program
runit()
# global variable scope
name ... |
992,180 | cda45da293c74d94aeb84380d1a5eee3e4a1edbb | """
ACEScg color space.
https://www.oscars.org/science-technology/aces/aces-documentation
"""
from ..channels import Channel
from ..spaces.srgb import sRGB
from .. import algebra as alg
from ..types import Vector
from typing import Tuple
AP1_TO_XYZ = [
[0.6624541811085053, 0.13400420645643313, 0.15618768700490782... |
992,181 | 3c6d1ed2cc1635bc0fb8ca728723eba732af9b45 | from django.contrib import admin
# Register your models here.
from .models import Bahagian
from .models import Tatatertib
#from .models import Zon
# Register your models here.
admin.site.register(Bahagian)
admin.site.register(Tatatertib)
#admin.site.register(Zon) |
992,182 | 0ddfd52211394fa4456993986f4b894ced711ee8 | import string
class Solution:
def uniqueLetterString(self, s: str) -> int:
pos = {l: [-1, -1] for l in string.ascii_uppercase}
res = 0
for i, c in enumerate(s):
j, k = pos[c]
res += (k - j) * (i - k)
pos[c] = [k, i]
for c in pos:
j, k = pos[c]
res += (k - j) * (len(s) - ... |
992,183 | fc08a72127b10c701b7648e6c1e6250d2f748383 | # -*- encoding: utf-8 -*-
import ConfigParser
import string, os, sys
cf = ConfigParser.ConfigParser()
cf.read("test.conf")
# 返回所有的section
s = cf.sections()
print 'section:', s
o = cf.options("db")
print 'options:', o
v = cf.items("db")
print 'db:', v
v = dict(cf.items("db"))
print 'db:', v
|
992,184 | d53cf8fa7927381604284e10d762e6fdfd3ce5f8 | def is_reverse(first_word, second_word):
""" Verify that the first word is the same as the second word reversed """
if len(first_word) != len(second_word):
return "Not the same as the first word !"
fwd_count = 0
bckwd_count = len(second_word) - 1
while bckwd_count > 0:
if first_wor... |
992,185 | 1777109bf5808d4a88cfef2aff4e676bb2849e26 | def last2(str):
str1 = str[-2:]
n = len(str)
count1 = 0
for i in range(n-1):
# only check substring with length 2 from far left to two to far right in the string.
if i+2 <= n-1:
if str[i:(i+2)] == str1:
count1 = count1 + 1
return(count1)
|
992,186 | 6a465f0a811421155537b1cfd2096145f316e245 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import random
import time
from threadpool.threadpool import ThreadPool
from network.network_msg import LocalAuthMsg
from dispatcher.login_service import LoginService
def test_for_client():
"""A function to test."""
def queryAction4Test(sock):
i = r... |
992,187 | 0c5352321deda86013dfd09a473ea9da04a4a680 | import pyglet
import time
notif = pyglet.media.load("voice/warningMasker1.mp3",streaming = False)
def mainkan():
notif.play()
time.sleep(5)
mainkan()
|
992,188 | b4683a60d3ebfd5eb3062bccd666e670e5923cbc | # from a given list of 4 letter words, check using dictionary if changing
# one letter produces a new valid word
import copy
dictionary=set()
for word in open("output_ex1.txt", "r"):
dictionary.add(word[:-1])
endict = [line[:-2] for line in open("english_dictionary.txt", "r") if len(line)==6] # 4 character words i... |
992,189 | d80d77bf0119590c86439c0f2775e0c6d1580f3e | __author__ = 'anthonymcclay'
__project__ = 'botoExamples'
__date__ = '7/27/17'
__revision__ = '$'
__revision_date__ = '$'
import boto3
import argparse
import textwrap
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description=textwrap.dedent('''\
... |
992,190 | 7f5bd8723f736989aa6a3b946d61a0852278a389 | from pydub import AudioSegment
import numpy as np
import math
attenuate_db = 0
accentuate_db = 2
# https://github.com/paarthmadan/bass-boost/blob/0b58e27049a8ad8d171dae7535384981c741fd58/index.py#L11
def boost(sample):
"""
Yields None, so you can update informations.
:param sample:
:return:
"""
... |
992,191 | 7a8aa12d23825bd5753d687d418e7c3459e0524b | from setuptools import setup
import sys
try:
from setuptools_rust import RustExtension, Binding
except ImportError:
import subprocess
errno = subprocess.call([sys.executable, "-m", "pip", "install", "setuptools-rust"])
if errno:
print("Please install setuptools-rust package")
raise Sys... |
992,192 | d8aeecf1626fbf8dd29c584be063600293f0cfdc | import pytest
@pytest.fixture
def fixture_example():
print("Setup phase")
yield
print("Teardown phase")
def test_one(fixture_example):
print("Inside test") |
992,193 | 3372ee9b416e9f553a6f291fe3c00172b1433edb | import Helpers as hlp
from Javis_algorithms import Merge_sort as mrg
"""
BINARY TREE IMPLEMENTATION + RANDOM TREE GENERATOR
All the tree nodes have leaves, so the final nodes are full of None leaves
"""
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = d... |
992,194 | c96ad0e72852efc26c1a4d1228c7163f0674559b | """Version 1 of the Frustum PointNet model used to train models for 3D object detection."""
# Partially based on the following works:
# (1) Charles R. Qi (https://github.com/charlesq34/frustum-pointnets)
# The main author of the Frustum PointNet paper. The source code was shared with Apache Licence v2.0.
# (ii)... |
992,195 | 4711ecaea8167651534033c86eda87f8fa0b51cb | # Generated by Django 2.2.7 on 2019-12-02 10:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('needs', '0010_auto_20191202_1201'),
]
operations = [
migrations.AlterField(
model_name='needs',
name='needsBeginTime... |
992,196 | 87d302bb672b9459e05e850895de0593f502197a | """cac URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based vie... |
992,197 | 6c6f03c6f8f386bf2b51cbe8595c48d1fe62c447 | from Game import Game, getch
import random
def main():
game = Game()
game.new_game()
moves = ['up', 'left', 'down', 'right']
while(game.get_sum() != 8):
while(game.get_sum() < 8):
game.play_move(random.choice(moves))
while(game.get_sum() > 8):
game.play_move('und... |
992,198 | 58bcc7743e533d49b1873cf000bc0a484900d9dc | import HDLC_communication
import struct
import time
import helpers
LTC5800IPR_PROTOCOL_VERSION = 4
RC_OK = 0
RC_INVALID_COMMAND = 1
RC_INVALID_ARGUMENT = 2
RC_END_OF_LIST = 11
RC_NO_RESOURCES = 12
RC_IN_PROGRESS = 13
RC_NACK = 14
RC_WRITE_FAIL = 15
RC_VALI... |
992,199 | 70839af7463a5fdb732e656b087202301495a2f5 |
phone = input("Please enter a 10 digit number: ")
print(phone[0:3] + '-' + phone[3:6] + '-' + phone[6:])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.