repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
chuter/wechat-requests | src/wechat/message/crypto.py | <filename>src/wechat/message/crypto.py
# -*- encoding: utf-8
"""
微信开放平台的公众号消息加密解密实现
具体文档参见:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1434696670
"""
import base64
import string
import random
import hashlib
import time
import struct
from Crypto.Cipher import AES
import socket
from bs4 import BeautifulSo... |
chuter/wechat-requests | tests/message/conftest.py | <filename>tests/message/conftest.py
# -*- encoding: utf-8
import pytest
@pytest.fixture(scope='session', autouse=True)
def received_message_str():
return """<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>1348831860</CreateTime>
<Ms... |
chuter/wechat-requests | tests/test_request_result.py | # -*- encoding: utf-8
import pytest
import six
from wechat import result
from wechat.compat import json
class TestRequestResult:
@pytest.mark.parametrize("ret_json", [
{},
{"openid": "openid", "age": 33, "time": "2018-04-28 18:41:00"},
{
"users": [{"openid": "openid", "age":... |
chuter/wechat-requests | src/wechat/api.py | <gh_stars>1-10
# -*- encoding: utf-8
import re
import logging
from urllib3.util.retry import Retry
import requests
from requests.adapters import HTTPAdapter
from .result import build_from_response
from .compat import bytes
from .settings import (DEFAULT_HEADERS, TIMEOUT, RETRYS,
RETRY_BACKOF... |
chuter/wechat-requests | tests/compat.py | <reponame>chuter/wechat-requests<filename>tests/compat.py
# -*- coding: utf-8 -*-
"""
This module handles import compatibility issues between Python 2 and
Python 3.
"""
# flake8: noqa
import sys
_ver = sys.version_info
#: Python 2.x?
is_py2 = (_ver[0] == 2)
#: Python 3.x?
is_py3 = (_ver[0] == 3)
if is_py2:
... |
chuter/wechat-requests | src/wechat/message/builder.py | <filename>src/wechat/message/builder.py
# -*- coding: utf-8 -*-
import time
from wechat.utils import serialize_dict_to_xml
from .models import XMLMessage
def _build_reply_msg_bytes(receive_message, **kwrags):
unicode_msg = serialize_dict_to_xml(
ToUserName=receive_message.FromUserName,
FromUse... |
chuter/wechat-requests | src/wechat/message/pipeline.py | <reponame>chuter/wechat-requests
# -*- coding: utf-8 -*-
from importlib import import_module
from wechat.compat import basestring
from . import MessageProcessException
from .context import Context
from .builder import XMLMessageBuilder
__all__ = ['new_pipeline']
class Pipeline(object):
def __init__(self, han... |
chuter/wechat-requests | tests/message/test_builder.py | # -*- encoding: utf-8
from wechat.message import XMLMessageBuilder
class TestXMLMsgParse:
def test_textmsg_parse(self):
message = XMLMessageBuilder.parse(
"""<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
... |
chuter/wechat-requests | src/wechat/__version__.py | __version__ = '1.4.6'
__name__ = 'wechat-requests'
|
chuter/wechat-requests | src/wechat/mpapi.py | # -*- encoding: utf-8
from copy import copy
from .api import Api
from .exceptions import RequestException
from .settings import AUTH_EXPIRED_CODES
__all__ = ['formp']
class MpApi(Api):
AUTH_QS_KEY = 'access_token'
def __init__(self, mp_access_token, auth_update_callback=None, **kwargs):
if mp_a... |
chuter/wechat-requests | src/wechat/message/__init__.py | <filename>src/wechat/message/__init__.py<gh_stars>1-10
# -*- coding: utf-8 -*-
# flake8: noqa
from .context import Context
from .exceptions import MessageProcessException, MessageCryptoProcessError
from .pipeline import new_pipeline
from .builder import XMLMessageBuilder
from .crypto import build_message_crypto_for
|
chuter/wechat-requests | src/wechat/exceptions.py | <filename>src/wechat/exceptions.py
# -*- coding: utf-8 -*-
from requests.exceptions import RequestException # noqa
|
chuter/wechat-requests | src/wechat/message/context.py | <reponame>chuter/wechat-requests
# -*- coding: utf-8 -*-
from six import iteritems
class Context(dict):
def __init__(self, **kwargs):
dict.__init__(self, kwargs)
@property
def message(self):
return self.get('message', None)
@property
def raw_message(self):
return self.g... |
chuter/wechat-requests | tests/message/test_pipeline.py | <filename>tests/message/test_pipeline.py<gh_stars>1-10
# -*- encoding: utf-8
import pytest
import mock
from wechat.compat import range
from wechat.message import new_pipeline, MessageProcessException
@pytest.fixture
def process_fail_handler(mocker):
fake_handler = mocker.MagicMock()
fake_handler.handle.si... |
chuter/wechat-requests | tests/test_sign.py | # -*- encoding: utf-8
import pytest
import string
from wechat import sign
class TestRandomNonceStrGenerate:
@pytest.mark.parametrize("length", [-1, 0])
def test_invalid_length(self, length):
with pytest.raises(ValueError):
sign.random_nonce_str(length)
@pytest.mark.parametrize("le... |
chuter/wechat-requests | tests/message/test_crypto.py | <filename>tests/message/test_crypto.py<gh_stars>1-10
# -*- encoding: utf-8
import re
import mock
import pytest
from wechat.message import build_message_crypto_for
from wechat.message.exceptions import InvalidSignature, InvalidAppid
from bs4 import BeautifulSoup
@pytest.fixture(scope='module', autouse=True)
def to... |
bladnor/sentiment-workshop | 05_pytorch_seq.py | import warnings
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from torchtext import data, data... |
bladnor/sentiment-workshop | 07_pytorch_lstm_fulldata.py | import warnings
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from torchtext import data, data... |
bladnor/sentiment-workshop | TwitterPipeline.py | <filename>TwitterPipeline.py
import warnings
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
import math
import numpy as np
import pandas as pd
import spacy
from torchtext import data
class TwitterHandleMatcher(object):
d... |
bladnor/sentiment-workshop | 00_base_nbsvm.py | <filename>00_base_nbsvm.py
import os
import math
import numpy as np
import pandas as pd
import argparse
from collections import Counter
import spacy
# inspired by https://github.com/mesnilgr/nbsvm
nlp = spacy.load('de')
def tokenize(sentence, grams):
words = [t.text for t in nlp(sentence)]
tokens = []
... |
mauriciopaiva12/Information-Collector-v1.4 | program/project.py | #------ IMPORTS OF LIBRARIES ------#
import socket
import sys
import dns.resolver
import time
import requests
#------------#
#------ GLOBAL VARIABLES ------#
port_pattern = [21, 22, 23, 25, 53, 80, 110, 135, 136, 137, 138, 139, 143, 443, 631, 3306, 3389]
all_ports = range(65535)
#------------#
#------ PRESENTATIO... |
faetos/binkdogcoin | contrib/sprledgerxfr/utxo.py | <filename>contrib/sprledgerxfr/utxo.py<gh_stars>0
#! /usr/bin/env python3
import unittest
import os
from datetime import datetime, timedelta, tzinfo
import json
import re
# import sqlite3
import psycopg2
import requests
import time
ecoin = dict(
name="Spreadcoin",
symbol="SPR",
url="http://spreadcoin.info"... |
dkatz23238/dabitup | dabitup/__main__.py | import argparse
from dabitup import make_docker_config, insert_tables_to_SQL, insert_records_to_mongo
import time
import subprocess
import os
import glob
import yaml
parser = argparse.ArgumentParser()
parser.add_argument("Database", type=str,
help="Database to spin up: mongo or SQL")
parser.add_arg... |
dkatz23238/dabitup | dabitup/__init__.py | import yaml
import os
import glob
import pprint
import argparse
import pandas as pd
import pymongo
import json
from sqlalchemy import create_engine
from sqlalchemy.engine.base import Connection
import docker
# import psycopg2
# import pg8000
# import docker
def make_docker_config(DATABASE, DATA_SOURCE, USERNAME, PASSWO... |
guhur/PREVALENT_R2R | tasks/NDH/utils.py | ''' Utils for io, language, connectivity graphs etc '''
import os
import sys
import re
import string
import json
import time
import math
from collections import Counter
import numpy as np
import networkx as nx
# padding, unknown word, end of sentence
base_vocab = ['<PAD>', '<UNK>', '<EOS>', '<NAV>', '<ORA>', '<TAR>'... |
guhur/PREVALENT_R2R | tasks/NDH/model.py |
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from r2rmodel import BertImgEncoder
class EncoderLSTM(nn.Module):
''' Encodes navigation instructions, returning hidden state context (fo... |
guhur/PREVALENT_R2R | tasks/NDH/ndhtrain.py | <filename>tasks/NDH/ndhtrain.py
import argparse
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch import optim
import torch.nn.functional as F
import os
import time
import numpy as np
import pandas as pd
from collections import defaultdict
from utils import read_vocab,write_vocab,buil... |
guhur/PREVALENT_R2R | r2r_src/param.py | import argparse
import os
import torch
def create_folders(path):
""" recursively create folders """
if not os.path.isdir(path):
while True:
try:
os.makedirs(path)
except:
pass
time.sleep(1)
else:
break
... |
guhur/PREVALENT_R2R | r2r_src/agent.py | <gh_stars>0
import json
import os
import sys
import numpy as np
import random
import math
import time
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch import optim
import torch.nn.functional as F
from env import R2RBatch
from utils import padding_idx, add_idx, Tokenizer
import utils
... |
guhur/PREVALENT_R2R | tasks/NDH/r2ragent.py | ''' Agents: stop/random/shortest/seq2seq '''
import json
import os
import sys
import numpy as np
import random
import time
import pickle
import torch
import torch.nn as nn
import torch.distributions as D
from torch.autograd import Variable
from torch import optim
import torch.nn.functional as F
import copy
from env ... |
guhur/PREVALENT_R2R | tasks/NDH/vilmodel.py | <gh_stars>1-10
from __future__ import absolute_import, division, print_function, unicode_literals
import json
import logging
import math
import os
import sys
from io import open
import torch
from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss
from modeling_utils import (WEIGHTS_NAME, CONFIG_NAME, Pr... |
guhur/PREVALENT_R2R | tasks/NDH/env.py | <filename>tasks/NDH/env.py
''' Batched Room-to-Room navigation environment '''
import sys
sys.path.append('build')
import MatterSim
import csv
import numpy as np
import math
import base64
import json
import random
import networkx as nx
import itertools
import pdb
from utils import load_datasets, load_nav_graphs
csv.... |
AmirHoseinTangsiriNET/SSQAuto | SSQAuto/SSQAuto.py | from __future__ import absolute_import
from __future__ import print_function
import splunklib.client as client
import splunklib.results as results
#Splunk Server IP Address Or HostName
HOST = "127.0.0.1"
#Splunk Mgmt Port (Default = 8089)
PORT = "8089"
#Splunk UserName
USERNAME = "admin"
#Splunk Password
PASSWORD = "<... |
hengwang322/lights_out | src/get_data.py | """This script fetches the original Street Lighting Assets data and cleans it.
"""
import os
import numpy as np
import geopandas as gpd
LIGHT_GEOJSON = 'https://opendata.arcgis.com/datasets/3bda41b12bbc4753b240b4866088080a_0.geojson'
def get_watt(watt_string):
watt_list = [s for s in watt_string.split('_') if... |
hengwang322/lights_out | app.py | <reponame>hengwang322/lights_out
import os
from PIL import Image
import streamlit as st
import pandas as pd
import plotly.express as px
from src.plot import plot_cost, plot_lighting_map, plot_lamp_hist, plot_solar
MAPBOX_TOKEN = os.environ['MAPBOX_TOKEN']
def update_style():
BACKGROUND_COLOR = "rgb(50,50,50)"
... |
hengwang322/lights_out | src/plot.py | import os
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
MAPBOX_TOKEN = os.environ['MAPBOX_TOKEN']
def plot_cost():
lamp_type = ['mercury-vapour lamp', 'compact fluorescent lamp',
'light-emitting diode', 'high pressure sodium']
total_cos... |
sonucr7/Similarity_Score_Module | Similarity_Score_Module/app.py | <gh_stars>0
import pandas as pd
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import CountVectorizer
import neattext.functions as nfx
import json
def check_similarity_score(data, column_name, _id, num_of_recommendations = 5):
data_idea = dat... |
sonucr7/Similarity_Score_Module | setup.py | <reponame>sonucr7/Similarity_Score_Module
# from distutils.core import setup
from setuptools import setup
# read the contents of your README file
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description... |
ganzinotti/cookie-cutter | project/brain.py | <gh_stars>0
import numpy as np
from project.other_module import constant
def add_number(a, b):
"""
This is a very complex function
:param a:
:param b:
:return: int
"""
return a + b
def multiple_number(a, b):
return np.array(constant * b)
|
ganzinotti/cookie-cutter | project/other_module.py | constant = "16"
|
ganzinotti/cookie-cutter | setup.py | import os
from setuptools import find_packages, setup
from project import settings
with open("README.md", "r") as fh:
long_description = fh.read()
def convert_requirements_to_list(fname):
with open(os.path.join(os.path.dirname(__file__), fname), "r") as f:
packages = [line.strip("\n") for line in f... |
ganzinotti/cookie-cutter | project/settings.py | <gh_stars>0
PACKAGE_NAME = "project"
PACKAGE_VERSION = "0.0.1"
PACKAGE_DESCRIPTION = "put your description here"
PACKAGE_AUTHOR = "Name"
PACKAGE_URL = "https://<not available>"
|
ganzinotti/cookie-cutter | tests/unit/test_brain.py | import pytest
from project.brain import add_number
def test_add_number():
result = add_number(2, 3)
assert 5 == result |
suneelkanthala/olympics-data-analysis | Code_Analysis.py | #Importing header files
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Path of the file is stored in the variable path
data = pd.read_csv(path)
#Code starts here
# Data Loading
data = data.rename(columns={"Total": "Total_Medals"})
#print(data.head(10))
# Summer or Winter
data['Better_Event'... |
daramousk/feature_expiration | models/module_expiration.py | <gh_stars>0
# -*- coding: utf-8 -*-
from odoo import models, fields
from datetime import datetime
from odoo.tools.misc import DEFAULT_SERVER_DATETIME_FORMAT
import logging
logger = logging.getLogger(__name__)
class module_expiration(models.Model):
_name = 'module.expiration'
module_name = fields.Many2on... |
daramousk/feature_expiration | __manifest__.py | # -*- coding: utf-8 -*-
{
'name': "Feature Expiration",
'summary': """
Set expiration dates for your modules""",
'description': """
This module will give you (the developer) the opportunity to set expiration dates on your modules.
""",
'author': "<NAME>",
'website': "https://g... |
rampasek/pyKuLGaP | setup.py | from setuptools import setup, find_packages
with open("README.md") as fh:
readme = fh.read()
setup(name='pykulgap',
version='0.0.13',
description="Functions for statistical analysis of treatment response curves in patient derived xenograph (PDX) models of cancer.",
long_description=readme,
... |
rampasek/pyKuLGaP | pykulgap/io.py | <gh_stars>0
import numpy as np
import pandas as pd
import re
import io
from pykulgap.classes import TreatmentResponseExperiment, CancerModel, ExperimentalCondition
def read_pdx_data(file_path):
"""
Reads in data from a file containing anonymized PDX data
:param file_path: [string] The path to the data f... |
rampasek/pyKuLGaP | pykulgap/__init__.py | from . import classes
from . import io
from . import pipelines
from . import helpers
from . import plotting
|
rampasek/pyKuLGaP | pykulgap/classes/TreatmentResponseExperiment.py | from .CancerModel import CancerModel
from ..plotting import create_measurement_dict
import pandas as pd
import numpy as np
# ---- TreatmentResponseExperimentObject
class TreatmentResponseExperiment:
"""
This class contains all CancerModel objects for a given treatment response experiment.
Attributes:
... |
rampasek/pyKuLGaP | pykulgap/classes/ExperimentalCondition.py | import itertools
# Logging
import logging
from collections import Counter
# plotting dependencies
import matplotlib.pyplot as plt
import statsmodels.api as sm
# GPy dependencies
from GPy import plotting
from GPy.kern import RBF
from GPy.models import GPRegression
from scipy.integrate import quad
from scipy.stats impo... |
rampasek/pyKuLGaP | scripts/test.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 14 09:07:30 2020
@author: ortmann_j
"""
from pykulgap.io import read_pdx_data
from pykulgap.plotting import plot_everything, create_and_plot_agreements, get_classification_df, \
create_and_plot_FDR, create_and_save_KT, plot_histograms_2c
resul... |
rampasek/pyKuLGaP | pykulgap/classes/CancerModel.py | <reponame>rampasek/pyKuLGaP<gh_stars>0
from .ExperimentalCondition import ExperimentalCondition # , ExpCondIterator
from ..helpers import compute_response_angle, centre, relativize, calculate_AUC
class CancerModel:
"""
A `CancerModel` represents one or more samples with the same source. For example, in PDX m... |
rampasek/pyKuLGaP | pykulgap/classes/__init__.py | <filename>pykulgap/classes/__init__.py<gh_stars>0
from .CancerModel import CancerModel # , CancerModelIterator
from .ExperimentalCondition import ExperimentalCondition # , ExpCondIterator
from .TreatmentResponseExperiment import TreatmentResponseExperiment # , TREIterator
|
rampasek/pyKuLGaP | pykulgap/plotting.py | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from math import atan
from math import pi
import statsmodels.formula.api as smf
import statsmodels.api as sm
from matplotlib import pylab as pl, patches as mp
from matplotlib.backends.backend_pdf import PdfPages
from scipy impo... |
rampasek/pyKuLGaP | pykulgap/helpers.py | import numpy as np
import pandas as pd
import statsmodels.api as sm
from scipy.integrate import quad
import sklearn.metrics
def p_value(l1, l2):
"""
returns p-value for each variable in l1, based on l2
:param l1: The list of variable for which the p-value is to be computed
:param l2: The list of value... |
rampasek/pyKuLGaP | pykulgap/pipelines.py | import gc
from collections import defaultdict
import numpy as np
import pandas as pd
import statsmodels.api as sm
from .plotting import plot_everything, create_and_plot_agreements, get_classification_df, \
plot_experimental_condition, plot_gp, plot_histogram, \
create_and_plot_FDR, create_and_save_KT, plot_hi... |
shepard2333/ATISproject | GUI.py | <reponame>shepard2333/ATISproject<filename>GUI.py
from base64 import decode
from tkinter import *
import tkinter
import sys
import os
# Create an instance of tkinter window
win = Tk()
win.geometry("800x350")
win.title("AWOS tool")
def save_text():
text_file = open("ICAO.txt", "w")
text_file.write(my_... |
shepard2333/ATISproject | ATIS.py | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import csv
import time
from bs4 import BeautifulSoup
import requests
import numpy as np
from numpy import genfromtxt
from PIL import Image, ImageDraw, ImageFont
with open('ICAO.txt','r') as f:
lines = f.readlines()
content = f.readlines()
for line in l... |
leocadioandre/Machine_learning_deploys | webapp_sistema_de_recomendacao/deploy/util.py | import numpy as np
import pandas as pd
# <=============================================== del_rows ========================================================>
def del_rows(df, features):
'''Deleta as linhas onde a variável especificada é zero
ARG:
df(dataframe): O dataframe que irá ser proce... |
leocadioandre/Machine_learning_deploys | webapp_sistema_de_recomendacao/deploy/get_data.py | import re
import time
import requests as rq
import bs4 as bs4
import json
import os
# <================================================= GET DATA ==========================================================>
#indicando o ano e as marcas que está procurando.
makers = ["ford", "vw-volkswagen", "gm-chevrolet"]
year... |
leocadioandre/Machine_learning_deploys | webapp_sistema_de_recomendacao/deploy/backend.py | <gh_stars>1-10
from get_data import *
from ml_models import *
import time
import numpy as np
#indicando o ano e as marcas que está procurando.
makers = ["ford", "vw-volkswagen", "gm-chevrolet"]
year_1 = "31" # 2013
year_2 = "38" # 2020
urll = "https://pr.olx.com.br/autos-e-pecas/carros-vans-e-utilitarios/{maker}/fle... |
leocadioandre/Machine_learning_deploys | webapp_sistema_de_recomendacao/deploy/app_flask.py | import numpy as np
import os.path
from flask import Flask, render_template
import os
import json
import backend
import time
from datetime import datetime
app = Flask(__name__)
def get_predictions():
cars = []
novos_carros_json = "novos_carros.json"
if not os.path.exists(novos_carros_json):... |
leocadioandre/Machine_learning_deploys | webapp_sistema_de_recomendacao/deploy/ml_models.py | <gh_stars>1-10
import pandas as pd
import re
import joblib as jb
import numpy as np
import json
from scipy.sparse import hstack, csr_matrix
# <================================================= MODEL =====================================================>
#Load models
model_rf = jb.load('model/model_rf.pk... |
leocadioandre/Machine_learning_deploys | webapp_sistema_de_recomendacao/deploy/starter_db.py | import backend
backend.update_db() |
leocadioandre/Machine_learning_deploys | webapp_sistema_de_recomendacao/deploy/app_stream.py | <reponame>leocadioandre/Machine_learning_deploys<gh_stars>1-10
import pandas as pd
import matplotlib.pyplot as plt
import streamlit as st
import altair as alt
import webbrowser
from utils import *
def main():
st.image("static\logo_andre.png")
st.write("# Sistema de recomendação - Dashboard ")
opcoes = ['... |
leocadioandre/Machine_learning_deploys | webapp_sistema_de_recomendacao/deploy/utils.py | import streamlit as st
from util import *
import altair as alt
import pandas as pd
# <=============================================== load_df ========================================================>
def load_data():
path = "dashboard_cars.json"
car_data = pd.read_json(path, lines = True)
add_ex... |
speechpro/speechpro-cloud-tts-examples | python/tts_streaming.py | import wave
import asyncio
import argparse
import logging
import datetime
import concurrent.futures
import os
import websockets
import pyaudio
from cloud_client.models.auth_request_dto import AuthRequestDto
from cloud_client.api.session_api import SessionApi
from cloud_client.api.synthesize_api import Synthesize as S... |
speechpro/speechpro-cloud-tts-examples | python/cloud_client/__init__.py | # coding: utf-8
# flake8: noqa
"""
TTS documentation
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 1.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolu... |
speechpro/speechpro-cloud-tts-examples | python/cloud_client/api/synthesize_api.py | <reponame>speechpro/speechpro-cloud-tts-examples
# coding: utf-8
"""
TTS documentation
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 1.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
""... |
Welzin/advent-of-code | 2020/08/part1.py | <gh_stars>0
#! /usr/bin/env python3
with open("input", "r") as fd :
instructions = [x.split(' ') for x in fd.read().split('\n')]
acc = 0
done = [False] * len(instructions)
i = 0
while 0 <= i < len(instructions) and not done[i] :
done[i] = True
instruction, value = instructions[i]
if instruction ... |
Welzin/advent-of-code | 2020/01/part1.py | <reponame>Welzin/advent-of-code
#! /usr/bin/env python3
import os
fd = open("input", "r")
entries = []
for line in fd.readlines() :
entries.append(int(line))
# Naive - O(n^2) solution :
for i in range(len(entries)) :
for j in range(i + 1, len(entries)) :
if entries[i] + entries[j] == 2020 :
... |
Welzin/advent-of-code | 2020/17/part2.py | <gh_stars>0
#! /usr/bin/env python3
from typing import List
class Cube :
def __init__(self, state, x, y, z, w) -> None :
self.x = x
self.y = y
self.z = z
self.w = w
self.isAlive = state
def __repr__(self) :
return f"({self.x}, {self.y}, {self.z}, {self.w}): {se... |
Welzin/advent-of-code | 2020/04/part1.py | #! /usr/bin/env python3
def isValid(passport) :
needed = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"]
for required in needed :
if required not in passport :
return False
return True
fd = open("input", "r")
info = fd.read()
passports = info.rstrip().split("\n\n")
count = 0
for pa... |
Welzin/advent-of-code | 2021/24/d24.py | #! /usr/bin/env python3
import re
from time import time
def fun(div, add_x, add_y, w, z) :
if (z%26)+add_x != w :
return (26*(z//div))+w+add_y
else :
return z//div
MONAD = open("24.txt").read().split('\n')
div, add_x, add_y = -1, -1, -1
to_apply = []
for i in range(len(MONAD)) :
if 'd... |
Welzin/advent-of-code | 2021/02/part1.py | #! /usr/bin/env python3
entries = [(line.split()[0], int(line.split()[1])) for line in open("input")]
print(sum(x for d, x in entries if d == 'forward') * sum(x*(d == 'down')-x*(d == 'up') for d, x in entries)) |
Welzin/advent-of-code | 2020/07/part1.py | <filename>2020/07/part1.py
#! /usr/bin/env python3
def getBag(line) :
words = line.split()
return " ".join((words[0], words[1]))
import re
content = open("input", "r").read().split('\n')
bags = [getBag(x) for x in content if re.search(r"\d shiny gold", x) != None]
total = len(bags)
found = bags
while... |
Welzin/advent-of-code | 2021/10/part1.py | <reponame>Welzin/advent-of-code
#! /usr/bin/env python3
def process(queue, char) :
entry = {
']' : '[',
'}' : '{',
')' : '(',
'>' : '<'
}
if char in '[{(<' :
return queue + [char]
else :
if queue.pop() != entry[char] :
raise RuntimeError(char... |
Welzin/advent-of-code | 2021/23/d23.py | #! /usr/bin/env python3
import re, collections
def completed(game_map) :
return game_map[(1, 2)] == game_map[(2, 2)] == game_map[(3, 2)] == game_map[(4, 2)] == 'A' and \
game_map[(1, 4)] == game_map[(2, 4)] == game_map[(3, 4)] == game_map[(4, 4)] == 'B' and \
game_map[(1, 6)] == game_map[(2,... |
Welzin/advent-of-code | 2020/02/part2.py | #! /usr/bin/env python3
import re
fd = open("input", "r")
valid = 0
for line in fd.readlines() :
i, j, char, string = re.search(r"(\d+)-(\d+) (.): (.*)", line).groups()
a = string[int(i) - 1] == char
b = string[int(j) - 1] == char
if bool(a) ^ bool(b) :
valid += 1
print(valid)
|
Welzin/advent-of-code | 2020/13/part2.py | #! /usr/bin/env python3
# This solution uses Chinese Remainder.
# I found that the problem wanted us to find the least common multiple
# of a range of numbers with remainders.
# The first link google gave me when typing this was a forum, which talked
# about the Chinese Remainder. It looked like it fit the problem, so... |
Welzin/advent-of-code | 2021/06/part2.py | #! /usr/bin/env python3
def process(population, days) :
total = [population.count(i) for i in range(days)]
for day in range(days - 7) : total[day + 7] += total[day] + total[day - 2] * (day >= 2)
return sum(total) + sum(population.count(i) for i in range(days))
print(process(list(map(int, open("input").rea... |
Welzin/advent-of-code | 2020/20/part1.py | #! /usr/bin/env python3
import copy
from typing import List
from math import sqrt
class Tile :
id: int
tile: List[List[chr]]
edges: List[List[List[chr]]]
def __init__(self, tile: List[str]) -> None :
self.id = int(tile[0][tile[0].rfind(' '):-1].strip())
self.tile = [[c for c in w]... |
Welzin/advent-of-code | 2020/19/part2.py | <gh_stars>0
#! /usr/bin/env python3
import re, collections
from typing import List, Dict, T
def readRules(rules: List[str]) -> Dict[int, T] :
res = {}
for rule in rules :
match = re.match(r"(\d+): ([\d |]+)", rule)
if match != None :
rule, do = match.groups()
if rule ==... |
Welzin/advent-of-code | 2020/16/part1.py | <reponame>Welzin/advent-of-code
#! /usr/bin/env python3
import re
def getValidValues(fields) :
valid = []
for field in fields :
match = re.match(r"^.*: (\d+-\d+) or (\d+-\d+)$", field).groups()
valid += [match[0].split('-'), match[1].split('-')]
return valid
with open("input", "r") as fd... |
Welzin/advent-of-code | 2021/08/part2.py | #! /usr/bin/env python3
def analyse_pattern(ls) :
corresponds = {2:1,7:8,4:4,3:7}
dct = {corresponds[len(i)]:i for i in ls if len(i) in [2, 3, 4, 7]}
for i in range(10) :
s = len(ls[i])
if s == 6 : #0 6 9
if sum(ls[i][j] in dct[4] for j in range(s)) == 3 :
if sum... |
Welzin/advent-of-code | 2021/12/part1.py | <gh_stars>0
#! /usr/bin/env python3
def add_verticle(a, b) :
global verticles
if a in verticles : verticles[a].append(b)
else : verticles[a] = [b]
return verticles
def all_paths_util(u, path = []) :
global verticles
if u in path and not u.upper() == u : return []
path.append(u)
... |
Welzin/advent-of-code | 2021/16/part2.py | <gh_stars>0
#! /usr/bin/env python3
import math
def solve(N, i=0) :
T = int(N[i+3:i+6], 2)
i += 6
if T == 4 :
value = ''
while N[i] == '1' :
value += N[i+1:i+5]
i += 5
return int(value+N[i+1:i+5],2), i+5
else :
I, Vs = N[i], []
i += 1
... |
Welzin/advent-of-code | 2021/25/d25.py | <filename>2021/25/d25.py
#! /usr/bin/env python3
from copy import deepcopy
from time import time
def print_board(T) :
print('\n'.join([''.join(T[i]) for i in range(len(T))]), end='\n\n')
T = []
for line in open("25.txt").readlines() :
T.append([c for c in line.strip()])
st = time()
n, m = len(T), len(T[0])
... |
Welzin/advent-of-code | 2020/06/part1.py | <filename>2020/06/part1.py
#! /usr/bin/env python3
content = [x.replace('\n', '') for x in open("input", "r").read().rstrip().split('\n\n')]
# Sum the length of the different characters in each group answers
total = sum([len(set(answer)) for answer in content])
print("Sum : ", total) |
Welzin/advent-of-code | 2021/14/part1.py | #! /usr/bin/env python3
def step(polymer, transformations) :
res = ""
for i in range(len(polymer) - 1) :
res += polymer[i] + transformations[polymer[i] + polymer[i + 1]]
res += polymer[-1]
return res
lines = [line.strip() for line in open("input")]
polymer = lines[0]
transfos = dict([line.spl... |
Welzin/advent-of-code | 2021/03/part1.py | #! /usr/bin/env python3
entries = [line.strip() for line in open("input")]
print(g:=sum(2**(len(entries[0]) - i - 1)*int(max(lst:=[entry[i] for entry in entries], key=lst.count)) for i in range(len(entries[0])))*((2**(len(entries[0]))-1)^g)) |
Welzin/advent-of-code | 2020/05/part1.py | #! /usr/bin/env python3
fd = open("input", "r")
max = 0
for line in fd.readlines() :
# Convert to binary
row = int(line[:7].replace('B', '1').replace('F', '0'), 2)
col = int(line[7:].replace('R', '1').replace('L', '0'), 2)
# Calculate ID
id = row * 8 + col
if id > max :
max = id
pri... |
Welzin/advent-of-code | 2021/01/part1.py | <reponame>Welzin/advent-of-code<filename>2021/01/part1.py
#! /usr/bin/env python3
entries = [int(n) for n in open("input")]
print(sum([entries[i-1] < entries[i] for i in range(1, len(entries))])) |
Welzin/advent-of-code | 2020/15/part2.py | #! /usr/bin/env python3
with open("test", "r") as fd :
startNumbers = [int(x) for x in fd.read().strip().split(',')]
numbers = {num: i + 1 for i, num in enumerate(startNumbers[:-1])}
last = startNumbers[-1]
for i in range(len(startNumbers), 30000000) :
numbers[last], last = i, (i - numbers[last]) if last i... |
Welzin/advent-of-code | 2021/05/part1.py | #! /usr/bin/env python3
def add_points(a, b, points) :
incr_x, incr_y = (a[0] != b[0]) * (-2 * (a[0] > b[0]) + 1), (a[1] != b[1]) * (-2 * (a[1] > b[1]) + 1)
x, y = a[0], a[1]
while (x, y) != (b[0] + incr_x, b[1] + incr_y) :
if (x, y) in points : points[(x, y)] += 1
else : points[(x, y)] = 1... |
Welzin/advent-of-code | 2020/22/part1.py | <gh_stars>0
#! /usr/bin/env python3
from typing import List, T
class Queue:
data: List[T]
def __init__(self, ls: List[T]) -> None :
self.data = ls
def queue(self, element: T) -> None :
self.data.append(element)
def dequeue(self) -> T :
return self.data.pop(0)
def peek(s... |
Welzin/advent-of-code | 2021/22/d22.py | #! /usr/bin/env python3
import re, collections
def solve(lines, part1 = True) :
cubes = collections.Counter()
for line in lines :
shall_turn_on = line.split()[0] == "on"
xmin, xmax, ymin, ymax, zmin, zmax = map(int, re.findall("-?\d+", line))
if part1 and not(-50 <= xmin <= 50 and -50... |
Welzin/advent-of-code | 2020/14/part2.py | #! /usr/bin/env python3
import itertools
with open("input", "r") as fd :
content = [x.split('=') for x in fd.read().strip().split('\n')]
values = dict()
mask = content[0][1].strip()
for k, v in content :
k, v = k.strip(), v.strip()
if k == 'mask' :
mask = v
else :
k, v = k[k.find('... |
Welzin/advent-of-code | 2020/21/part1.py | <reponame>Welzin/advent-of-code
#! /usr/bin/env python3
import re
from typing import List
def intersection(l1: List[str], l2: List[str]) -> List[str] :
return [v for v in l1 if v in l2]
with open("input", "r") as fd :
content = fd.read().strip().split('\n')
ingredients, allergens = {}, {}
for line in cont... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.