blob_id stringlengths 40 40 | language stringclasses 1 value | repo_name stringlengths 5 133 | path stringlengths 2 333 | src_encoding stringclasses 30 values | length_bytes int64 18 5.47M | score float64 2.52 5.81 | int_score int64 3 5 | detected_licenses listlengths 0 67 | license_type stringclasses 2 values | text stringlengths 12 5.47M | download_success bool 1 class |
|---|---|---|---|---|---|---|---|---|---|---|---|
ca6cfab61d0a7078719bbe3ce170aac1bfd31fed | Python | huanyushis/Hand-drawing-recognition-based-on-flask-and-keras | /draw/train.py | UTF-8 | 2,452 | 2.5625 | 3 | [] | no_license | import numpy as np
import cv2
import os
from sklearn.model_selection import train_test_split
from keras.utils import to_categorical
from keras.models import Model, Input
from keras.layers import Conv2D, MaxPool2D, Flatten, Dropout, Dense
from keras.losses import categorical_crossentropy
from keras.optimizers import Adadelta
from keras.callbacks import ModelCheckpoint
from keras.models import load_model
import random
def get_data():
path = r'C:\Users\admin\Desktop\123'
sum = 0
datas = []
labels = []
classes = []
lists = os.listdir(path)
for i, j in enumerate(lists):
data = np.load(path + "\\%s" % (j)).astype('uint8')
datas.extend(data)
classes.append(j[18:-4])
labels.extend([i]*data.shape[0])
datas = np.array(datas).reshape(-1, 28, 28, 1)
labels = np.array(labels)
return datas, labels, classes
train_x, train_y, classes = get_data()
train_x = train_x.astype('float32')
train_x /= 255
train_y = to_categorical(train_y, len(classes))
train_x, test_x, train_y, test_y = train_test_split(train_x, train_y, test_size=0.1,random_state=1)
train_x, val_x, train_y, val_y = train_test_split(train_x, train_y, test_size=0.15,random_state=1)
inputs = Input(shape=(28, 28, 1))
outputs1 = Conv2D(64, (3, 3), activation='relu')(inputs)
drop1=Dropout(0.5)(outputs1)
outputs2 = Conv2D(256, (3, 3), activation='relu')(drop1)
maxpool1 = MaxPool2D((2, 2))(outputs2)
outputs3 = Conv2D(256, (3, 3), activation='relu')(maxpool1)
drop2=Dropout(0.5)(outputs3)
outputs4 = Conv2D(64, (3, 3), activation='relu')(drop2)
maxpool2 = MaxPool2D((2, 2))(outputs4)
flatten = Flatten()(maxpool2)
outputs = Dense(len(classes), activation='softmax')(flatten)
model = Model(inputs=inputs, outputs=outputs)
print(model.summary())
model.compile(loss=categorical_crossentropy,
optimizer=Adadelta(),
metrics=['accuracy'])
checkpoint = ModelCheckpoint(filepath="ep{epoch:03d}-loss{loss:.3f}-acc{acc:.3f}-val_acc{acc:.3f}.h5",
monitor='val_acc',
verbose=1,
save_best_only='True',
mode='max',
period=1)
batch_size = 1000
epochs = 200
model.fit(train_x, train_y,
batch_size=batch_size,
epochs=epochs,
validation_data=(val_x, val_y),
callbacks=[checkpoint],
verbose=1)
model.save('123.h5')
| true |
e35d59a879599ef45df9527023cd48eae35a7c15 | Python | QuantumQuadrate/Instrument_Servers | /instruments/analogout.py | UTF-8 | 11,243 | 2.546875 | 3 | [] | no_license | """
AnalogOutput class for the PXI Server
SaffmanLab, University of Wisconsin - Madison
"""
# TODO: could use nidaqmx task register_done_event, which can pass out and allow
# error handling if a task ends unexpectedly due to an error
## modules
import nidaqmx
from nidaqmx.constants import Edge, AcquisitionType, Signal
from nidaqmx.errors import DaqError
from nidaqmx.error_codes import DAQmxErrors
import numpy as np
import xml.etree.ElementTree as ET
import csv
from io import StringIO
import logging
from recordclass import recordclass as rc
## local imports
from instruments.instrument import Instrument
from trigger import StartTrigger
from pxierrors import XMLError, HardwareError
class AnalogOutput(Instrument):
ExportTrigger = rc('ExportTrigger', ('exportStartTrigger', 'outputTerminal'))
ExternalClock = rc('ExternalClock', ('useExternalClock', 'source', 'maxClockRate'))
def __init__(self, pxi):
super().__init__(pxi, "AnalogOutput")
self.physicalChannels = ""
self.minValue = -10
self.maxValue = 10
self.sampleRate = 0
self.waveforms = None
self.exportTrigger = self.ExportTrigger(False, None)
self.externalClock = self.ExternalClock(False, '', 0)
self.startTrigger = StartTrigger()
self.task = None
@staticmethod
def wave_from_str(wave_str: str, delim: str = ' ') -> np.ndarray:
"""
Efficiently build return waveform as a numpy ndarray from a string
Args:
'wave_str': (str) a (possibly multi-line) string of space-delimited
float-convertable values.
'delim': (str, optional) the value delimiter. ' ' by default
Returns:
'wave_arr': (np.ndarray, float) the waveform with one row per line
in wave_str, and one column per value in a line. The shape for
of the output is (samples, channels per sample)
"""
with StringIO(wave_str) as f:
reader = csv.reader(f, delimiter=delim)
cols = len(next(reader))
try:
rows = sum([1 for row in reader]) + 1
except StopIteration:
rows = 1
wave_arr = np.empty((rows, cols), float)
with StringIO(wave_str) as f:
reader = csv.reader(f, delimiter=delim)
for i,row in enumerate(reader):
wave_arr[i,:] = row
return wave_arr
def load_xml(self, node: ET.Element):
"""
Initialize AnalogOutput instance attributes with xml from CsPy
Args:
'node': type is ET.Element. tag should be "HSDIO". Expects
node.tag == "AnalogOutput"
"""
self.is_initialized = False
assert node.tag == self.expectedRoot, "expected node"+\
f" <{self.expectedRoot}> but received <{node.tag}>"
if not (self.exit_measurement or self.stop_connections):
for child in node:
if self.exit_measurement or self.stop_connections:
break
try:
if child.tag == "enable":
self.enable = Instrument.str_to_bool(child.text)
elif child.tag == "physicalChannels":
self.physicalChannels = child.text
elif child.tag == "minimum":
self.minValue = float(child.text)
elif child.tag == "maximum":
self.maxValue = float(child.text)
elif child.tag == "clockRate":
self.sampleRate = float(child.text) # samples per second in LabVIEW
elif child.tag == "waveform":
self.waveforms = self.wave_from_str(child.text)
elif child.tag == "waitForStartTrigger":
self.startTrigger.wait_for_start_trigger = Instrument.str_to_bool(child.text)
elif child.tag == "exportStartTrigger":
self.exportTrigger.exportStartTrigger = Instrument.str_to_bool(child.text)
elif child.tag == "triggerSource":
self.startTrigger.source = child.text
elif child.tag == "exportStartTriggerDestination":
self.exportTrigger.outputTerminal = child.text
elif child.tag == "triggerEdge":
try:
self.startTrigger.edge = StartTrigger.nidaqmx_edges[child.text.lower()]
except KeyError as e:
raise KeyError(f"Not a valid {child.tag} value {child.text} \n {e}")
elif child.tag == "useExternalClock":
self.externalClock.useExternalClock = Instrument.str_to_bool(child.text)
elif child.tag == "externalClockSource":
self.externalClock.source = child.text
elif child.tag == "maxExternalClockRate":
self.externalClock.maxClockRate = float(child.text)
else:
self.logger.warning(f"Unrecognized XML tag \'{child.tag}\' in <AnalogOutput>")
except (KeyError, ValueError):
raise XMLError(self, child)
def init(self):
"""
Create and initialize an nidaqmx Task object
"""
if not (self.stop_connections or self.reset_connection):
if self.enable:
# Clear old task
if self.task is not None:
try:
self.close()
except DaqError as e:
if e.error_code == DAQmxErrors.INVALID_TASK.value:
self.logger.warning("Tried to close AO task that probably didn't exist")
else:
self.logger.exception(e)
try:
self.task = nidaqmx.Task()
self.task.ao_channels.add_ao_voltage_chan(
self.physicalChannels,
min_val=self.minValue,
max_val=self.maxValue)
if self.externalClock.useExternalClock:
self.task.timing.cfg_samp_clk_timing(
rate=self.externalClock.maxClockRate,
source=self.externalClock.source,
active_edge=Edge.RISING, # default
sample_mode=AcquisitionType.FINITE, # default
samps_per_chan=1000) # default
if self.startTrigger.wait_for_start_trigger:
self.task.triggers.start_trigger.cfg_dig_edge_start_trig(
trigger_source=self.startTrigger.source,
trigger_edge=self.startTrigger.edge) # default
if self.exportTrigger.exportStartTrigger:
self.task.export_signals.export_signal(
Signal.START_TRIGGER,
self.exportTrigger.outputTerminal)
self.logger.info("AO Triggers setup")
except DaqError:
# end the task nicely
self.stop()
self.close()
msg = '\n AnalogOutput hardware initialization failed'
raise HardwareError(self, task=self.task, message=msg)
self.is_initialized = True
def update(self):
"""
Update the Analog Output hardware
"""
if not (self.stop_connections or self.exit_measurement) and self.enable:
channels, samples = self.waveforms.shape
try:
self.task.timing.cfg_samp_clk_timing(
rate=self.sampleRate,
active_edge=Edge.RISING, # default
sample_mode=AcquisitionType.FINITE, # default
samps_per_chan=samples)
# Auto-start is false by default when the data passed in contains
# more than one sample per channel
self.task.write(self.waveforms)
self.logger.info("AO Waveform written")
except DaqError:
# end the task nicely
self.stop()
self.close()
msg = '\n AnalogOutput hardware update failed'
raise HardwareError(self, task=self.task, message=msg)
def is_done(self) -> bool:
"""
Check if the tasks being run are completed
Return:
'done': True if tasks completed, connection was stopped or reset, or
self.enable is False. False otherwise.
"""
done = True
if not (self.stop_connections or self.exit_measurement) and self.enable:
try:
# check if NI task is done
done = self.task.is_task_done()
except DaqError:
# end the task nicely
self.stop()
self.close()
msg = '\n AnalogOutput check for task completion failed'
raise HardwareError(self, task=self.task, message=msg)
return done
def start(self):
"""
Start the task
"""
if not (self.stop_connections or self.exit_measurement) and self.enable:
try:
self.task.start()
except DaqError:
# end the task nicely
self.stop()
self.close()
msg = '\n AnalogOutput failed to start task'
raise HardwareError(self, task=self.task, message=msg)
def stop(self):
"""
Stop the task
"""
if self.task is not None:
try:
self.task.stop()
except DaqError as e:
if not e.error_code == DAQmxErrors.INVALID_TASK.value:
msg = f'\n {self.__class__.__name__} failed to stop current task'
self.logger.warning(msg)
self.logger.exception(e)
except DaqWarning as e:
if e.error_code == DAQmxWarnings.STOPPED_BEFORE_DONE.value:
pass
def close(self):
"""
Close the task
"""
if self.task is not None:
self.is_initialized = False
try:
self.task.close()
except DaqError as e:
if not e.error_code == DAQmxErrors.INVALID_TASK.value:
msg = '\n AnalogOutput failed to close current task'
self.logger.warning(msg)
self.logger.exception(e) | true |
47d4cdff8602180596382b5a208a7e839fb72a0e | Python | 4knigc12/COM404 | /1-basics/4-Repetition/1-While-loop/3- Ascii/bot.py | UTF-8 | 256 | 3.609375 | 4 | [] | no_license | # While loop Ascii Art
count= 0
charging= 0
bars= int( input("How many bars should be charged ?"))
while charging < bars:
count += 1
print("Charging: " + str(count*"█"))
charging = charging +1
print()
print("The battery is fully charge")
| true |
bc528e13f717b00c3a8003c1d9f871e0c341c6da | Python | the-roth/HNAARGHBot | /games/game.py | UTF-8 | 10,777 | 2.953125 | 3 | [] | no_license | """
Created on Jun 20, 2017
@author: Rudy Laprade (penguin8r) and the_roth
"""
import threading
import time
import re
from enum import Enum # install via pip install enum34
from commands.command import Command, SubCommand
DEFAULT_SIGNUP_TIME = 130
DEFAULT_PRINT_SPEED = 30
TIMER_COOLDOWN_DURATION = 60
Status = Enum('Status', 'inactive signup results running on_cooldown signups_full')
class Game(Command):
"""
This class is the building block for implementing games. It follows a
multi-phase design with statuses defined by the Enum above.
1. Inactive: The game is not running nor on cooldown. Ready to be played
if no other games are going on.
2. Signup: The game was started by !<game_name>. In this phase other
users can signup with the command
3. Running: The game is now running. Players may interact with
the game in some format.
4. Results: Results of the game are printed out. This is distinguished from
the Running phase in that no user interaction should be occurring.
5. On_cooldown: Only once the game is completed (end of Results phase) does
the game go on cooldown. Querying the game instead will
print a message saying how long until the game is available.
Currently, only one game is allowed to be running at a time.
!game is hidden from !info but the actual games such as !meateo are not.
See the __init__ method for initialization notes. Other points to note are:
TIMER_COOLDOWN_DURATION = This variable stops the bot from responding to
game commands when they've just been played.
"""
def __init__(
self,
name,
on_cooldown_message,
signup_time=DEFAULT_SIGNUP_TIME,
running_duration=0,
print_speed=DEFAULT_PRINT_SPEED,
has_rank=True,
*args, **kwargs):
"""
Constructor
Only one game is allowed to be running at a time
:param name: Name of the game, the word/phrase used to start the game
:param duration: Duration of the game in seconds
:param on_cooldown_message: Message to display when someone tries to
play the game but it is on cooldown
:param signup_time: How long users are given to signup for the game
(in seconds)
:param print_speed: Print speed of game (Outback game is variable speed)
:param has_rank: Boolean indicating whether this game should have a
Rank command
"""
super(Game, self).__init__(name, disabled_on_game=True, *args, **kwargs)
self._on_cooldown_message = on_cooldown_message
# Following 2 timer variables could at least be named better
self._timer_last_used = time.time()
self._timer = 0
self._signup_time = signup_time
self._running_duration = running_duration
self._print_speed = print_speed
self.status = Status.inactive
self._player_list = set()
if has_rank:
self._subcommands.append(Game.Rank(self))
##### Methods you should implement in Games #####
def introduction(self, user):
"""
Returns a string introducing this game
Call when someone starts the game
This method should be overridden by any Game
:param user: User who started the game
"""
raise NotImplementedError()
def results(self):
"""
Returns a list of strings that the bot should print out for the results
of the game.
Called during the Results phase
This method should be overridden by any Game
"""
raise NotImplementedError()
##### Methods you might want to override #####
def initialize_game(self):
"""
Does any variable initialization and starting actions for the game.
This is a separate function so that it can be easily overridden
"""
pass
def rank(self, users):
"""
Not sure if all Games should have rank commands, but as of now they do.
Should be overridden if you want to allow a rank command (!<game>rank)
:param users: Users whom have requested their rank
"""
pass
def running_phase_initialization(self):
"""
Called at the start of the running phase
"""
pass
def action_when_running(self, user, message):
"""
Behavior to respond to a message when the game is in the running phase
:param user:
:param message:
"""
pass
def signup_player(self, user):
"""
Signs up the user to play the game
By default adds the user to the player list
Can be overriden for more complex behavior
Note that player list is a set so will not have duplicates
"""
self._player_list.add(user)
def deploy_printout(self, result):
"""
Prints out the results of the game, line by line.
Separated from start_results_phase so that each game can customize how
it prints out results
:param result: List of lines to print in the results.
"""
for i in range(len(result)):
threading.Timer(self._print_speed * i, self.line_print, (result[i],)).start()
def matches(self, user, message):
"""
Determines whether the message sent by the user should be used by this game
Overrides default matching to depend on state
By default, accepts any message when running so that the game can
process anything users say
Can be overridden for more customized behavior
"""
if self.status is Status.running:
return True # Could just write the whole thing as an OR but I think this is more readable
return super(Game, self).matches(user, message)
##### End of methods that you should likely need to override #####
def respond(self, user, message):
# If game is on cooldown, tells users how long until it can be played.
if (self.status is Status.on_cooldown
and self._timer > 0
and time.time() - self._timer_last_used > TIMER_COOLDOWN_DURATION):
# self._timer redundant here? Last part compares current time
# to last used time to see if allowed
time_to_go = int(round((self._cooldown_duration - time.time() + self._timer)/60))
time_printout = ('shortly!' if time_to_go <= 2
else 'in about ' + str(time_to_go) + ' min!')
self._bot.send_message(self._on_cooldown_message + time_printout)
self._timer_last_used = time.time()
elif self.status is Status.inactive:
self._timer = 0
# Start the game
self.start_game(user)
elif self.status is Status.signup:
self.signup_player(user)
elif self.status is Status.running:
self.action_when_running(user, message)
def can_be_used(self):
"""
Returns True iff this game can be used
"""
return (self.is_active()
or (not (self._disabled_on_game and self._bot.has_active_game)))
def cooldown_switch(self):
"""
Overridden to disable, because cooldown works differently for games.
We now use class attributes instead of dictionary switches
(see previous bot version)
"""
pass
def put_game_on_cooldown(self):
self.status = Status.on_cooldown
threading.Timer(self._cooldown_duration, self.cooldown).start()
def cooldown(self):
super(Game, self).cooldown();
self.status = Status.inactive
self._bot.send_message('The ' + self._name.capitalize() + ' game (!' + self._name
+ ') can be played once any current games are complete!')
def is_active(self):
"""
Tells you whether the game is currently running
"""
return self.status in set((Status.signup, Status.running, Status.results, Status.signups_full))
def line_print(self, line):
"""
This doesn't really need to be here.
We could just have things call send_message directly.
"""
self._bot.send_message(line)
def start_game(self, user):
"""
Initiates the game. Sets status variables and such appropriately.
Starts signups for the game. Do not override this method.
Going into this, player_list should be an empty set unless you
have been messing with things you shouldn't have.
:param user: The user who initiated the game
"""
self._bot.has_active_game = True
self.signup_player(user)
self.initialize_game()
self.game_intro(user)
self.start_signup_phase()
def game_intro(self, user):
opening_speech = self.introduction(user)
for i in range(len(opening_speech)):
threading.Timer(10*i + 2, self._bot.send_message, [opening_speech[i]]).start()
def start_signup_phase(self):
"""
Starts the signup phase of the game
Debatable whether this should be combined with start_game()
"""
self.status = Status.signup
threading.Timer(self._signup_time, self.start_running_phase).start()
def close_signups(self):
"""
Closes signups. Intermediate status where we are essentially just
waiting for the game to start.
"""
self.status = Status.signups_full
def start_running_phase(self):
"""
Starts the running phase of the game.
"""
self.status = Status.running
self.running_phase_initialization()
threading.Timer(self._running_duration, self.start_results_phase).start()
def start_results_phase(self):
"""
Starts the results phase of the game
Prints out the results of the game
Also sets a timer to end the game once all results are printed.
Perhaps there is a cleaner way to do this.
Make sure the total printing time is accurate for your game, or fix it somehow
"""
self.status = Status.results
result = self.results()
self._timer = time.time()
total_printing_time = self._print_speed * (len(result) - 1)
threading.Timer(total_printing_time, self.end_game).start()
self.deploy_printout(result)
def end_game(self):
"""
Does the cleanup when the game is over. Should be called somewhere in
the chain of events of the game.
Do not override this method.
"""
self._player_list = set()
self._bot.has_active_game = False
self.put_game_on_cooldown()
class Rank(SubCommand):
def __init__(self, main_command, *args, **kwargs):
"""
:param main_command: Should be an instance of a Game
"""
super(Game.Rank, self).__init__(main_command._name + "rank", main_command,
cooldown_duration=0, *args, **kwargs)
self._queued = False
self._users_requested = set()
self.RANK_QUERY_TIME = 10
def game(self):
"""
Convenience getter method
"""
return self._main_command
def matches(self, user, message):
return re.match("^!{}(rank|level)$".format(self._main_command), message.lower())
def respond(self, user, message):
if not self._queued:
self._queued = True
# Rank query executes after brief period (10 seconds by default)
threading.Timer(self.RANK_QUERY_TIME, self.rank_query).start()
self._users_requested.add(user)
def can_be_used(self):
"""
Returns True iff this command can be used
Overrides method from Command
Rank is inactive when the game is running
"""
return super(Game.Rank, self).can_be_used() and not self.game().is_active()
def rank_query(self):
"""
Executes any outstanding queries for ranks, sends the results, and resets state
"""
result = self.game().rank(self._users_requested)
self._bot.send_message(result)
self._queued = False
self._users_requested = set()
| true |
4d434edb7c399744bc036501dc110a36cfe817e7 | Python | vmiklos/dynamic.vmiklos.hu | /szihkcal/szihkcal.py | UTF-8 | 3,869 | 2.71875 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
import calendar
import cgi
import locale
import random
import sys
import time
locale.setlocale(locale.LC_ALL, "hu_HU.UTF-8")
sys = reload(sys)
sys.setdefaultencoding("utf-8")
class MyCalendar(calendar.LocaleHTMLCalendar):
def formatday(self, day, weekday):
"""
Return a day as a table cell, including a random task.
"""
if day == 0:
# Day is outside the month.
return '<td class="noday"> </td>'
else:
task = random.choice(tasks).decode('utf-8')
return '<td class="day">%d<br />%s</td>' % (day, task)
def formatmonthname(self, theyear, themonth, withyear=True):
"""
Return a month name as a table row.
"""
if withyear:
s = '%s %s' % (theyear, calendar.month_name[themonth])
else:
s = '%s' % month_name[themonth]
return '<tr><th colspan="7" class="month">%s</th></tr>' % s
def formatmonth(self, theyear, themonth, withyear=True):
"""
Return a formatted month as a table, including a visible border.
"""
v = []
a = v.append
a('<table class="month">')
a('\n')
a(self.formatmonthname(theyear, themonth, withyear=withyear))
a('\n')
a(self.formatweekheader())
a('\n')
for week in self.monthdays2calendar(theyear, themonth):
a(self.formatweek(week))
a('\n')
a('</table>')
a('\n')
return ''.join(v)
def formatweekday(self, day):
"""
Return a weekday name as a table header, but use day_name, not
day_abbr.
"""
name = calendar.day_name[day].decode('utf-8')
return '<th class="%s">%s</th>' % (self.cssclasses[day], name)
tasks = [
"Segítségnyújtés gyermekeinknek az érzéseik elfogadásában (35. o.)",
"Együttműködésre bírni gyermekeinket (79. o.)",
"Büntetés helyett (118. o.)",
"Az önállóság támogatása (151. o.)",
"Dicséret és önértékelés (182. o.)",
"Hogy ne kelljen gyermekeinknek szerepet játszaniuk (211. o.)"
]
def formatszihkcal():
"""
Return a complete HTML page, using MyCalendar().
"""
ret = []
cal = MyCalendar()
ret.append("""<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<!--
Source code: https://github.com/vmiklos/dynamic.vmiklos.hu
Usage: /?seed=value - seeds random with the provided value
-->
<style>
td.day {
text-align: center;
}
table, td, th {
border: 1px solid;
border-spacing: 0;
}
</style>
<title>SZIHK naptár</title>
</head>
<body>""".encode('utf-8'))
now = time.localtime()
html = cal.formatmonth(now.tm_year, now.tm_mon).encode('utf-8')
ret.append(html)
ret.append("""</body>
</html>""")
return "".join(ret)
def application(environ, start_response):
"""
This is used by mod_wsgi.
"""
status = '200 OK'
parameters = cgi.parse_qs(environ.get('QUERY_STRING', ''))
if 'seed' in parameters:
seed = parameters['seed'][0]
random.seed(seed)
output = formatszihkcal()
response_headers = [('Content-type', 'text/html')]
start_response(status, response_headers)
return [output]
if __name__ == '__main__':
from wsgiref.simple_server import make_server
srv = make_server('localhost', 8080, application)
srv.serve_forever()
# vim:set shiftwidth=4 softtabstop=4 expandtab:
| true |
0042b808aa74d657dd629114605538f9f1e91f5c | Python | Lakshmisudhakarreddy/fundamentals-of-python | /to find third angle of a triangle.py | UTF-8 | 199 | 3.921875 | 4 | [] | no_license | #write a program to enter two angles of triangle and find third angle
a=float(input("enter first angle value:"))
b=float(input("enter second angle value:"))
c=180-(a+b)
print("thrid angle is:",c) | true |
d09045a663ce28d1f958f39d49bd613dcf99e43e | Python | hjiang1/2hg-report | /utils/common.py | UTF-8 | 1,989 | 2.703125 | 3 | [] | no_license | import os
import matplotlib.pyplot as plt
import pandas as pd
from glob import glob
def parse_filename(file, scan_type):
roi, pipeline = file.split(f'{scan_type}')[-1].split('.')[0].split('-')
if (roi == ''):
roi = 'Lesion'
else:
roi = roi[1:]
return (roi, pipeline)
def compile_inputs(query_string):
query_results = glob(query_string, recursive=True)
if (len(query_results) == 0):
raise Exception(f'ERROR: No results found matching the following glob query: {query_string}')
else:
query_results.sort()
return query_results
def print_scan_info(scan_id, query_results, scan_type):
df = pd.DataFrame(columns=['ROI', 'Best Pipeline', 'File'])
best_pipelines = list(filter(lambda x: 'AllPipelines' not in x, query_results))
best_pipelines.sort()
for file in best_pipelines:
roi, pipeline = parse_filename(file, scan_type)
df = df.append({
'ROI': roi,
'Best Pipeline': pipeline,
'File': file
}, ignore_index=True)
print(f'Scan: {scan_id}')
pd.set_option('display.max_colwidth', -1)
display(df)
def generate_init(query_string, scan_id, scan_type):
query_results = compile_inputs(query_string)
print_scan_info(scan_id, query_results, scan_type)
print_delimiter(char='=')
return query_results
def get_2hg_gln_glu(ser, sigfig=None):
if (float(ser[' Glu']) == 0):
return -1
val = (ser[' 2HG']+ser[' Gln'])/ser[' Glu']
if (sigfig):
return round(val, sigfig)
else:
return val
def save_plot(plot, file):
directory = os.path.dirname(file)
if (not os.path.exists(directory)):
os.makedirs(directory)
plot.savefig(file)
return plot
def unpack_config(config):
return tuple(config.values())
def print_delimiter(char='-', num=50, end='\n'):
print(char * num, end=end)
| true |
898ce9e88fa614d718b2b1881069feb97d79215c | Python | mege330/pythondigital | /Python Labs/Test123.py | UTF-8 | 315 | 3.578125 | 4 | [] | no_license |
#This print will be Hallo World
print("Hallo World")
#This print will be Number
print (1)
#This print will be a Full Name
print ("Menahem Geller")
#this print will be autcam of Numbers
print (1+5)
print(9*4)
print(100/5)
print(10+35)
print(-1+60)
print(9 // 4)
print(9 % 4)
print(3 ** 2)
print(2 * (1/4))
print(5/9)-32))
| true |
32785e0d14c29422e01a401f71501a72c4ff1df8 | Python | GeneseLessa/buy_order_api | /applications/products/models.py | UTF-8 | 774 | 2.59375 | 3 | [] | no_license | from django.db import models
from django.core.validators import MinValueValidator
class Product(models.Model):
"""This class is responsible for modeling the ORM Product model.
The fields are:
name, price, minimum, amount_per_package, max_availability"""
name = models.CharField(max_length=150, unique=True)
price = models.DecimalField(
max_digits=10,
decimal_places=2,
validators=[MinValueValidator(0)])
minimum = models.PositiveIntegerField(validators=[MinValueValidator(0)])
amount_per_package = models.PositiveIntegerField(
validators=[MinValueValidator(0)])
max_availability = models.PositiveIntegerField(
validators=[MinValueValidator(0)])
def __str__(self):
return self.name
| true |
d636402e51958af6ce36979ce8dc22cf58888ae2 | Python | RW21/competitive-code | /atcoder/abc038/d_n.py | UTF-8 | 129 | 2.875 | 3 | [] | no_license | N = int(input())
wh = [[int(j) for j in input().split()] for i in range(N)]
wh.sort(key=lambda x: (x[0], -x[1]))
print(wh) | true |
c2577ab3f0c3243b6aef34ca64b142bb6f43d552 | Python | ushiko/AOJ | /ITP1/ITP1_10_C.py | UTF-8 | 322 | 2.984375 | 3 | [] | no_license |
from functools import reduce
import math
while True:
n = int(input())
if ( n == 0 ):
break
l = list(map(int,input().split()))
mean = float(reduce(lambda a,b:a+b,l)) / (len(l))
t = 0
for i in l:
t += pow((i - mean),2)
bunsan = float(t) / len(l)
print (math.sqrt(bunsan))
| true |
fac64c9ffe6b7d2753b365d223b4afc5d8f01749 | Python | vishnoiprem/pvdata | /lc-all-solutions-master/146.lru-cache/test.py | UTF-8 | 1,075 | 3.265625 | 3 | [] | no_license | from queue import Queue
class LRUCache(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.values_dictonary = {}
self.queue = Queue()
def set(self, key):
"""
:rtype: int
"""
if self.queue.full():
removed = self.queue.get()
values = self.values_dictonary[removed]
if values == 1:
del values_dictionary[removed]
else:
values_dictionary[removed] -= 1
else:
current = values_dictionary.get(removed, 0)
values_dictionary = current + 1
self.queue.put(key)
values_dictionary[key] = values_dictionary.get(key) + 1
def get(self, key, value):
"""
:type key: int
:type value: int
:rtype: nothing
"""
if key in self.values_dictonary:
inDict=True
else:
inDict=False
self.set(key)
if not inDict:
return -1
return key
| true |
050cf92a61d19d0cd9247625a5c56f9bcc02d3d7 | Python | avioXD/python_basic | /chapter_2/03_input.py | UTF-8 | 196 | 3.8125 | 4 | [] | no_license |
name = input('Enter your name: ')
print(name)
a = input('Enter any number: ')
print(a)
print('The sum of your input is: %d'%(int(input('Enter 1st num: '))+int(input('Enter second number: '))))
| true |
7f1f8fb524e6dd28b3ba3836297e7a56ec465ad2 | Python | cccccccccccccc/Myleetcode | /211/Design Add and Search Words Data Structure.py | UTF-8 | 1,208 | 3.8125 | 4 | [
"Apache-2.0"
] | permissive | from collections import defaultdict
class TrieNode:
def __init__(self):
self.node = defaultdict(TrieNode)
self.isword = False
class WordDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def addWord(self, word: str) -> None:
current = self.root
for i in word:
current = current.node[i]
current.isword = True
def search(self, word: str) -> bool:
def search_in_word(word,trie)->bool:
for i, w in enumerate(word):
if w not in trie.node.keys():
if w == ".":
for x in trie.node:
if search_in_word(word[i+1:],trie.node[x]):
return True
return False
else:
trie = trie.node[w]
return trie.isword
return search_in_word(word,self.root)
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)
A = WordDictionary()
print(A.addWord("add"))
print(A.search(".dd")) | true |
6c6bc9cbcc0a5ff9e68bc13676b686ba02f86c10 | Python | olerasmu/ButterflyMode | /src/root/nested/implementation.py | UTF-8 | 9,187 | 3.109375 | 3 | [] | no_license | '''
Created on 18. mars 2014
@author: olerasmu
'''
import math
import os
import timeit
import sys
from Crypto.Cipher import AES
from _hashlib import new
#===============================================================================
# This now works with files which have a number of blocks n that is a power of 2
#===============================================================================
class Butterfly(object):
def __init__(self, filepath=None):
self.filepath = filepath
#self.f = open(filepath, 'rb')
#print (filepath)
fileTab = []
butterflyTab = []
#Return the size of file in bytes
def fileSize(self):
tempFile = open(self.filepath, 'r')
tempFile.seek(0,2)
size = tempFile.tell()
tempFile.seek(0,0)
tempFile.close()
return size
#Slit the file into blocks of 128 bit (16*8 bytes)
def blockifyFile(self):
with open(self.filepath, 'rb') as newfile:
byte = newfile.read(16)
while byte:
self.fileTab.append(byte)
#print (byte)
byte = newfile.read(16)
#print ("File has been divided into blocks")
#print (self.fileTab)
fileTabTest = []
def blockifyFileTwo(self, filepath):
with open(filepath, 'rb') as newfile:
byte = newfile.read(16)
while byte:
self.fileTabTest.append(byte)
#print byte
byte = newfile.read(16)
#print ("File has been divided into blocks")
return self.fileTabTest
def fileifyBlocks(self, filepath, butterflyTab):
with open(filepath, 'ab') as hourglass_file:
for byte in butterflyTab:
hourglass_file.write(byte)
#Initialize the butterfly function. Variable j is controlled from here
def initiateButterfly(self, d, n):
self.butterflyTab = [None]*n
#print ("initiate")
for j in range(1, d+1):
#print "this is j: ", j
self.executeButterfly(j, n)
#count = 0
#Execute the butterfly algorithm
def executeButterfly(self, j, n):
#print ("execute")
#print ("this is j: ", j)
for k in range(0, int((n/math.pow(2, j))-1)+1):
#print ("this is k: ", k)
if j == 1:
for i in range(1, int(math.pow(2, j-1))+1):
indexOne = int(i+k*math.pow(2, j))-1
indexTwo = int(i+k*math.pow(2, j)+math.pow(2, j-1))-1
#self.count += 1
self.w(self.fileTab[indexOne], self.fileTab[indexTwo], indexOne, indexTwo)
#print indexOne, " ", indexTwo
else:
for i in range(1, int(math.pow(2, j-1))+1):
indexOne = int(i+k*math.pow(2, j))-1
indexTwo = int(i+k*math.pow(2, j)+math.pow(2, j-1))-1
#self.count += 1
self.w(self.butterflyTab[indexOne], self.butterflyTab[indexTwo], indexOne, indexTwo)
#print indexOne, " ", indexTwo
#print ("this is i: ", i)
#print ("this is index one: ", indexOne, " and this is index two: ", indexTwo)
#===============================================================
# temp = [int(i+k*math.pow(2, j))-1, int(i+k*math.pow(2, j)+math.pow(2, j-1))-1]
# print temp
#===============================================================
#print ("count: ", self.count)
#print (self.butterflyTab)
cipher_machine = AES.new(b'This is a key123', AES.MODE_ECB)
#Some cryptographic operation
def w(self, block_one, block_two, indexOne, indexTwo):
#=======================================================================
# #Uncomment this to deactivate interleaving and encryption
# print ("one ", indexOne, " two: ", indexTwo)
# print ("Before: ", self.butterflyTab[indexOne], " ", self.butterflyTab[indexTwo])
#=======================================================================
#=======================================================================
# self.butterflyTab[indexOne] = block_two
# self.butterflyTab[indexTwo] = block_one
#=======================================================================
#=======================================================================
# #Comment this to deactivate interleaving and encryption
# interleaved = "".join(str(i) for j in zip(block_one, block_two) for i in j)
# new_block_one, new_block_two = interleaved[:int(len(interleaved)/2)], interleaved[int(len(interleaved)/2):]
#=======================================================================
#=======================================================================
# #This part is for interleaving of blocks
# # #print block_one, block_two, len(block_one), len(block_two)
# interleaved = ''
# for i in range(0, len(block_one)):
# interleaved = interleaved + str(block_one[i]) + str(block_two[i])
# #print interleaved, len(interleaved)
#
# new_block_one = interleaved[:int(len(interleaved)/2)]
# new_block_two = interleaved[int(len(interleaved)/2):]
#=======================================================================
#This part is for splitting and combining blocks (alternative to interleaving)
new_block_one = block_one[len(block_one)/2:] + block_two[len(block_two)/2:]
new_block_two = block_one[:len(block_one)/2] + block_two[:len(block_two)/2]
#Comment out this to deactivate encryption
#print new_block_one, new_block_two, "rett for crypto, og lengden er:", len(new_block_one), len(new_block_two)
new_block_one = self.cipher_machine.encrypt(new_block_one)
new_block_two = self.cipher_machine.encrypt(new_block_two)
#print new_block_one, "rett etter crypto, og lengden er:", len(new_block_one)
#print "This is block one encrypted: ", new_block_one
self.butterflyTab[indexOne] = new_block_two
self.butterflyTab[indexTwo] = new_block_one
#===========================================================================
# def testOpen(self):
# for i in range(0, 1000):
# f = open("opentest.txt", 'a')
# f.write("Dette er en tekst")
# os.fsync(f)
# f.close()
#===========================================================================
def start(self, input_filepath):
bf = Butterfly(filepath=input_filepath)
#print os.path.getsize(bf.filepath)
#bf.testOpen()
start = timeit.default_timer()
bf.blockifyFile()
n = len(bf.fileTab)
#n = int(bf.fileSize()/16)
#print (int(math.pow(2, 1-1)))
#print (n)
d = int(math.log(n, 2))
bf.initiateButterfly(d, n)
#print ("This is d: ", d)
#===============================================================================
# print (len(bf.butterflyTab))
# print (len(bf.fileTab))
#===============================================================================
#Try to xor the blocks together
#temp = bf.w('a', 'b')
#bf.w(temp, 'b')
#Uncomment this to write the bf table to file.
bf.fileifyBlocks('bf_hourglass.txt', bf.butterflyTab)
stop = timeit.default_timer()
print ("Start: ", start, "\nStop: ", stop, "\nTime: ", stop - start)
writeable = "File: " + str(self.filepath) + " size: " + str(self.fileSize()) + " time: ", str(stop-start)
writeable = str(writeable)+"\n"
with open('resultfile.txt', 'a') as resultfile:
resultfile.write(writeable)
def input(self, input_filepath):
try_again = ''
if os.path.isfile(input_filepath):
bf.filepath = input_filepath
bf.start(input_filepath)
elif not os.path.isfile(input_filepath):
try_again = raw_input("Provided filepath did not exist, try again or write quit to exit...")
if try_again == 'quit':
sys.exit('You choose to quit')
else:
self.input(try_again)
bf = Butterfly()
input_filepath = raw_input("Provide filepath...")
bf.input(input_filepath)
#print (bf.fileTab)
#print bf.butterflyTab
#print len(bf.butterflyTab)
#print (bf.count)
#print bf.blockifyFileTwo('bf_hourglass.txt')
#===============================================================================
# for byte in bf.butterflyTab:
# print byte, " byte"
#===============================================================================
| true |
900b2e7a672bd7878d83b0f3184dd6a47e45899a | Python | supermitch/Advent-of-Code | /2017/15/fifteen.py | UTF-8 | 1,233 | 3.515625 | 4 | [] | no_license | import time
def part_a():
count = 0
val_a = 883
val_b = 879
for i in range(int(4e7)):
a_val = val_a * 16807 % 2147483647
b_val = val_b * 48271 % 2147483647
count += format(a_val, '016b')[-16:] == format(b_val, '016b')[-16:]
val_a, val_b = a_val, b_val
return count
def part_b():
count = 0
val_a = 883
val_b = 879
for i in range(int(5e6)):
while True:
a_val = val_a * 16807 % 2147483647
if a_val % 4 == 0:
break
val_a = a_val
while True:
b_val = val_b * 48271 % 2147483647
if b_val % 8 == 0:
break
val_b = b_val
count += format(a_val, '016b')[-16:] == format(b_val, '016b')[-16:]
val_a = a_val
val_b = b_val
return count
def main():
tic = time.time()
count_a = part_a()
print(f'Part A: {count_a} - Matching count')
print('Elapsed: {:0.2f} s'.format(time.time() - tic))
print('\n')
tic = time.time()
count_b = part_b()
print(f'Part B: {count_b} - Matching count for divisible')
print('Elapsed: {:0.2f} s'.format(time.time() - tic))
if __name__ == '__main__':
main()
| true |
aec5dc1304b7f237668590d13e13e1529feaec42 | Python | JJJMLiew/Project-Ideas | /street.py | UTF-8 | 1,314 | 3.546875 | 4 | [] | no_license | from riddle import *
from game import *
from guess import *
from ending import *
def street():
inventory=[]
print("\n\n\nIt is nighttime, you see a long street lit in darknessaaegfgbnergrthsrteh ")
print("\nAfter a glance around you notice a few things")
choice = input('\n>go upstreet\n>head towards the noisy alleyway\n>step into the brightly lit building\n>walk into the nightclub\n>check your inventory\n>look behind\n:')
if choice.lower() == 'go upstreet':
print('\nYou head up the street')
ending()
elif choice.lower() == 'head towards the noisy alleyway':
gameintro()
game()
elif choice.lower() == 'step into the brightly lit building':
riddleintro()
riddle()
elif choice.lower() == 'walk into the nightclub':
guessintro()
guess()
elif choice.lower() == 'other game':
print('LINK #guess GAME')
elif choice.lower() == 'check your inventory':
if len(inventory)==0:
print('\nYou carry nothing on you')
street()
else:
for item in inventory:
item.describe()
elif choice.lower() == 'look behind':
print('look bbaaaahd')
street()
else:
print('not an option')
street()
| true |
8c9c65e31cf8ede044e9f96139bc4daae97c0d42 | Python | Naughtyk/Python | /project11 - theory of games/Лабы Ване/labrab8.py | UTF-8 | 1,505 | 3.421875 | 3 | [] | no_license | """
Программа, вычисляющая вектор Шепли
Автор: Афанасьев И.Е.
Дата написания: 20.09.2020
"""
# импортируем перестановки
from itertools import permutations
# функция, вычисляющая факториал числа
def fact(i):
if i <= 1:
return 1
return i * fact(i - 1)
# Задаём расстояния до домов ("Малое Гадюкино")
X = [40, 90, 150, 240, 300, 500]
# Порядковые номера домов
X_i = [i for i in range(len(X))]
# Факториал от числа домов
factX = fact(len(X))
# Перестановки всех домов (И дублирование для номеров домов)
perm = permutations(X)
perm_i = list(permutations(X_i))
# Характеристическая функция
hf = []
for i in perm:
hf1 = []
for j in range(len(i)):
if j == 0:
hf1 += [i[j]]
else:
# Отражает вклад каждого жителя в постройку дороги
hf1 += [i[j] - max(i[:j]) if i[j] - max(i[:j]) > 0 else 0]
hf += [hf1]
# Инициализируем вектор Шепли
shapley = [0]*len(X)
# Пробегаемся по всем перестановкам
for i in range(factX):
for j in range(len(X)):
for k in range(len(shapley)):
if perm_i[i][j] == k:
shapley[k] += hf[i][j]
# Усредняем
for i in range(len(shapley)):
shapley[i] /= factX
print(shapley)
| true |
8a5582bfc51dac79e6b5482fe586bfd4a1f27426 | Python | comeeasy/study | /python/sw-academy-python2/oop/operator-overloading.py | UTF-8 | 2,008 | 4.125 | 4 | [] | no_license | #####################################################################
class Person :
count = 0
#####################################################################
def __init__(self, name, age) :
self.__name = name
self.__age = age
print(self.name, "이 생성")
Person.count += 1
def __del__(self) :
print(self.name, "이 제거")
#####################################################################
def to_str(self) :
return "{0}\t{1}".format(self.name, self.age)
@property
def name(self) :
return self.__name
@property
def age(self) :
return self.__age
@age.setter
def age(self, age) :
if age < 0 :
raise TypeError("나이는 음수가 아니야")
self.__age = age
@classmethod
def get_info(cls) :
return "현재 Person의 인스턴스는 {0}개이다".format(cls.count)
#####################################################################
# operator overloading
# >
def __gt__(self, other) :
return self.__age > other.__age
# >=
def __ge__(self, other) :
return self.__age >= other.__age
# <
def __lt__(self, other) :
return self.__age < other.__age
# <=
def __le__(self, other) :
return self.__age <= other.__age
#####################################################################
# !=
def __ne__(self, other) :
return self.__age != other.__age
# ==
def __eq__(self, other) :
return self.__age == other.__age
# str() 을 사용할 때 어떤 것을 return할 것인지 정의
def __str__(self) :
return "{0}\t{1}".format(self.__name, self.__age)
#####################################################################
people = [
Person("홍길동", 20),
Person("이순신", 45),
Person("강감찬", 35)
]
print(Person.get_info())
print(str(people[1])) | true |
b6789eaabee5f89afc17fa71f071b6391da2e8eb | Python | javisabalete/s3-sftp-replicator | /lib/sftp.py | UTF-8 | 2,916 | 2.84375 | 3 | [
"MIT"
] | permissive | import os.path
import paramiko
class SSHConnection(object):
def __init__(self, host, username, password, port=22):
self.sftp = None
self.sftp_open = False
self.transport = paramiko.Transport((host, port))
self.transport.connect(username=username, password=password)
def _openSFTPConnection(self):
if not self.sftp_open:
self.sftp = paramiko.SFTPClient.from_transport(self.transport)
self.sftp_open = True
def put(self, local_path, remote_path, key):
self._openSFTPConnection()
self.mkdir_recursive(remote_path+'/'+os.path.dirname(key))
self.sftp.put(local_path, remote_path+'/'+key)
print('Uploaded file '+key)
def close(self):
if self.sftp_open:
self.sftp.close()
self.sftp_open = False
self.transport.close()
def mkdir_recursive(self, remote_directory):
self._openSFTPConnection()
if remote_directory == '/':
self.sftp.chdir('/')
return
if remote_directory == '':
return
try:
self.sftp.chdir(remote_directory)
except IOError:
dirname, basename = os.path.split(remote_directory.rstrip('/'))
self.mkdir_recursive(dirname)
self.sftp.mkdir(basename)
self.sftp.chdir(basename)
return True
def rmdir_recursive(self, remote_path):
self._openSFTPConnection()
remote_directory = os.path.dirname(remote_path)
if remote_directory == '/':
self.sftp.chdir('/')
return
if remote_directory == '':
return
if remote_directory == remote_path:
return
try:
print('Removing dir.. '+remote_path)
self.sftp.rmdir(remote_path)
dirname, basename = os.path.split(remote_path.rstrip('/'))
if self.sftp.listdir(dirname) == []:
self.rmdir_recursive(dirname)
except IOError, e:
if 'No such file' in str(e):
return False
raise
def remove(self, remote_path, key):
self._openSFTPConnection()
try:
list_file = self.sftp.stat(remote_path+'/'+key)
except IOError, e:
if 'No such file' in str(e):
return False
raise
try:
self.sftp.remove(remote_path+'/'+key)
print('Removed file '+key)
try:
if self.sftp.listdir(os.path.dirname(remote_path+'/'+key)) == []:
self.rmdir_recursive(os.path.dirname(remote_path+'/'+key))
except IOError, e:
if 'No such file' in str(e):
return False
raise
except IOError, e:
if 'No such file' in str(e):
return False
raise | true |
38999419de94619e82fe9b9377f80465aac9508a | Python | devannair777/DistributedNFV-ResourceSynchronization | /Validator/extensions.py | UTF-8 | 2,539 | 2.625 | 3 | [] | no_license | import yaml
import sys
def meta_constructor(loader,node):
value = loader.construct_mapping(node)
return value
yaml.add_constructor(u'tag:yaml.org,2002:Orchestrator.Messages.OrchestratorResource',meta_constructor)
def addNetworkResource(nr):
f = open('resource.yaml','r')
yamlObj = yaml.load(f)
f.close()
resYaml = yamlObj
nwResources= yamlObj['NetworkResources']
nwResources.append(nr)
resYaml['NetworkResources'] = nwResources
g = open('resource.yaml','w')
yaml.dump(resYaml,g)
g.close()
print(resYaml)
def addServiceResource(sr):
f = open('resource.yaml','r')
yamlObj = yaml.load(f)
f.close()
resYaml = yamlObj
svResources= yamlObj['ServiceResources']
svResources.append(sr)
resYaml['ServiceResources'] = svResources
g = open('resource.yaml','w')
yaml.dump(resYaml,g)
g.close()
print(resYaml)
def delNetworkResource(nr):
f = open('resource.yaml','r')
yamlObj = yaml.load(f)
f.close()
resYaml = yamlObj
nwResources= yamlObj['NetworkResources']
i = nwResources.index(nr)
print("Element found at index",str(i))
nwResources.pop(i)
resYaml['NetworkResources'] = nwResources
g = open('resource.yaml','w')
yaml.dump(resYaml,g)
g.close()
print(resYaml)
def delServiceResource(sr):
f = open('resource.yaml','r')
yamlObj = yaml.load(f)
f.close()
resYaml = yamlObj
svResources= yamlObj['ServiceResources']
i = svResources.index(sr)
print("Element found at index",str(i))
svResources.pop(i)
resYaml['ServiceResources'] = svResources
g = open('resource.yaml','w')
yaml.dump(resYaml,g)
g.close()
print(resYaml)
if __name__=='__main__':
## print(sys.argv[0]) Just the name of the python file
## print(len(sys.argv)) Including name of file
#delNetworkResource("Nl2")
resrc = ""
for i in range(len(sys.argv)-3):
resrc += sys.argv[i+3]
resrc += ""
if(sys.argv[1] == '--add') :
if(sys.argv[2] == '--network') :
print('Adding Network Resource :',resrc)
addNetworkResource(resrc)
elif(sys.argv[2] == '--service') :
print('Adding Service Resource :',resrc)
addServiceResource(resrc)
elif(sys.argv[1] == '--del') :
if(sys.argv[2] == '--network') :
print('Deleting Network Resource :',resrc)
delNetworkResource(resrc)
elif(sys.argv[2] == '--service') :
print('Deleting Service Resource :',resrc)
delServiceResource(resrc)
| true |
c6c1a13b6772ef2d0eeab47c0ac96fab52de669c | Python | haggislea/python_intensive | /coding_bat/warm_up2.py | UTF-8 | 1,118 | 3.453125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 1 19:19:55 2019
@author: leann
"""
#-----
# warm up 2
#-----
# string times
def string_times(str, n):
return str * n
# string splosion
def string_splosion(str):
result = ''
for n in range(0,len(str)+1):
result += str[:n]
return result
# array front 9
def array_front9(nums):
for element in nums[:4]:
if element == 9:
return True
return False
# front times
def front_times(str, n):
if len(str) < 3:
return str * n
return str[:3] * n
# last2
def last2(str):
count = 0
for i in range(len(str)-2):
if str[i:i+2] == str[-2:]:
count += 1
return count
# array123
def array123(nums):
for i in range(len(nums)-2):
if nums[i:i+3] == [1,2,3]:
return True
return False
# string bits
def string_bits(str):
result = ''
for n in range(0, len(str)):
if n%2 == 0:
result += str[n]
return result
# string match
def string_match(a, b):
min_length = min(len(a), len(b))
count = 0
for i in range(min_length-1):
if a[i:i+2] == b[i:i+2]:
count += 1
return count | true |
6f7cd63aef72a5d3c253544193a4cc2cc43256f2 | Python | francescacairoli/WGAN_ModelAbstraction | /Dataset_Generation/src/MAPK/generate_dataset.py | UTF-8 | 10,223 | 2.53125 | 3 | [] | no_license | import numpy as np
from numpy.random import randint, random
import stochpy
import pandas as pd
import os
import shutil
from tqdm import tqdm
import pickle
import time
class AbstractionDataset(object):
def __init__(self, n_init_states, n_trajs, state_space_dim, param_space_bound, model_name, time_step, T):
self.n_init_states = n_init_states
self.n_trajs = n_trajs
self.n_training_points = n_init_states*n_trajs
self.state_space_dim = state_space_dim
self.stoch_mod = stochpy.SSA(IsInteractive=False)
self.stoch_mod.Model(model_name+'.psc')
self.directory_name = model_name
self.time_step = time_step
self.T = T # end time
self.param_space_bound = param_space_bound
self.param_space_dim = param_space_bound.shape[0]
def time_resampling(self, data):
time_index = 0
# Il nuovo array dei tempi
time_array = np.linspace(0, self.T, num=int(self.T / self.time_step+1))
# new_data conterrà i dati con la nuova scansione temporale
# la prima colonna contiene gli istanti di tempo, e quindi corrisponde a time_array
new_data = np.zeros((time_array.shape[0], data.shape[1]))
new_data[:, 0] = time_array
for j in range(len(time_array)):
while time_index < data.shape[0] - 1 and data[time_index + 1][0] < time_array[j]:
time_index = time_index + 1
if time_index == data.shape[0] - 1:
new_data[j, 1:] = data[time_index, 1:]
else:
new_data[j, 1:] = data[time_index, 1:]
return new_data
def set_initial_states(self, init_state):
list_of_species = ["M3K", "M3Kp", "M2K", "M2Kp", "M2Kpp", "MAPK", "MAPKp", "MAPKpp"]
for i in range(self.state_space_dim):
self.stoch_mod.ChangeInitialSpeciesCopyNumber(list_of_species[i], init_state[i])
def sample_initial_states(self, n_points=None):
if n_points == None:
n_points = self.n_init_states
set_of_init_states = np.empty((n_points, self.state_space_dim))
for i in range(n_points):
m3k = np.random.randint(low=0, high=100)
m2k = np.random.randint(low=0, high=300)
m2kp = np.random.randint(low=0, high=int(300-m2k))
mapk = np.random.randint(low=0, high=300)
mapkp = np.random.randint(low=0, high=int(300-mapk))
set_of_init_states[i] = np.array([m3k, 100-m3k, m2k, m2kp, 300-m2k-m2kp, mapk, mapkp, 300-mapk-mapkp])
return set_of_init_states
def set_parameters(self, V1):
self.stoch_mod.ChangeParameter("V1", V1)
def sample_parameters_settings(self, n_points = None):
if n_points == None:
n_points = self.n_init_states
set_of_params = (self.param_space_bound[1] - self.param_space_bound[0])*random(size=(n_points,))+self.param_space_bound[0]
return set_of_params
def sample_grid_config(self, n_points):
param_grid = np.linspace(self.param_space_bound[0], self.param_space_bound[1], n_points)
output_grid = np.linspace(0,300,n_points)
return param_grid, output_grid
def generate_training_set(self):
Yp = np.zeros((self.n_training_points,self.param_space_dim))
Ys = np.zeros((self.n_training_points,self.state_space_dim))
X = np.zeros((self.n_training_points, int(self.T/self.time_step), self.state_space_dim))
initial_states = self.sample_initial_states()
set_of_params = self.sample_parameters_settings()
count, avg_time = 0, 0
for i in tqdm(range(self.n_init_states)):
self.set_initial_states(initial_states[i,:])
self.set_parameters(set_of_params[i])
for k in range(self.n_trajs):
begin_time = time.time()
self.stoch_mod.DoStochSim(method="Direct", trajectories=3, mode="time", end=self.T)
if False:
self.stoch_mod.PlotSpeciesTimeSeries(species2plot =['MAPK', 'MAPKpp'])
stochpy.plt.savefig('NEW_V1={}_MAPK_{}{}.png'.format(set_of_params[i], i,k))
ntraj_time = time.time()-begin_time
self.stoch_mod.Export2File(analysis='timeseries', datatype='species', IsAverage=False, directory=self.directory_name, quiet=False)
avg_time += ntraj_time
datapoint = pd.read_table(filepath_or_buffer=self.directory_name+'/'+self.directory_name+'.psc_species_timeseries1.txt', delim_whitespace=True, header=1).drop(labels="Reaction", axis=1).drop(labels='Fired', axis=1).as_matrix()
new_datapoint = self.time_resampling(datapoint)
#print(new_datapoint)
#print(new_datapoint.shape)
X[count,:,:] = new_datapoint[1:,1:self.state_space_dim+1]
Ys[count,:] = initial_states[i,:self.state_space_dim]
Yp[count] = set_of_params[i]
count += 1
print("average time to gen 1 traj with SSA: ", avg_time/self.n_trajs)
self.X = X
self.Y_s0 = Ys
self.Y_par = Yp
self.Y = np.hstack((Yp,Ys))
def generate_validation_set(self, n_val_points, n_val_trajs_per_point):
Yp = np.zeros((n_val_points,self.param_space_dim))
Ys = np.zeros((n_val_points,self.state_space_dim))
X = np.zeros((n_val_points, n_val_trajs_per_point,int(self.T/self.time_step), self.state_space_dim))
initial_states = self.sample_initial_states(n_val_points)
set_of_params = self.sample_parameters_settings(n_val_points)
for ind in range(n_val_points):
self.set_initial_states(initial_states[ind,:])
self.set_parameters(set_of_params[ind])
Ys[ind,:] = initial_states[ind,:self.state_space_dim]
Yp[ind,:] = set_of_params[ind]
for k in range(n_val_trajs_per_point):
if k%100 == 0:
print(ind, "/", n_val_points, "------------------K iter: ", k, "/", n_val_trajs_per_point)
self.stoch_mod.DoStochSim(method="Direct", trajectories=1, mode="time", end=self.T)
self.stoch_mod.Export2File(analysis='timeseries', datatype='species', IsAverage=False, directory=self.directory_name, quiet=False)
datapoint = pd.read_table(filepath_or_buffer=self.directory_name+'/'+self.directory_name+'.psc_species_timeseries1.txt', delim_whitespace=True, header=1).drop(labels="Reaction", axis=1).drop(labels='Fired', axis=1).as_matrix()
new_datapoint = self.time_resampling(datapoint)
X[ind,k,:,:] = new_datapoint[1:,1:self.state_space_dim+1]
self.X = X
self.Y_s0 = Ys
self.Y_par = Yp
self.Y = np.hstack((Yp,Ys))
def generate_grid_validation_set(self, n_val_points, n_val_trajs_per_point):
Yp = np.zeros((n_val_points,self.param_space_dim))
Ys = np.zeros((n_val_points,self.state_space_dim))
X = np.zeros((n_val_points, n_val_trajs_per_point,int(self.T/self.time_step), self.state_space_dim))
initial_states = self.sample_initial_states(n_val_points)
set_of_params = self.sample_parameters_settings(n_val_points)
for ind in range(n_val_points):
self.set_initial_states(initial_states[ind,:])
self.set_parameters(set_of_params[ind])
Ys[ind,:] = initial_states[ind,:self.state_space_dim]
Yp[ind,:] = set_of_params[ind]
for k in range(n_val_trajs_per_point):
if k%100 == 0:
print(ind, "/", n_val_points, "------------------K iter: ", k, "/", n_val_trajs_per_point)
self.stoch_mod.DoStochSim(method="Direct", trajectories=1, mode="time", end=self.T)
self.stoch_mod.Export2File(analysis='timeseries', datatype='species', IsAverage=False, directory=self.directory_name, quiet=False)
datapoint = pd.read_table(filepath_or_buffer=self.directory_name+'/'+self.directory_name+'.psc_species_timeseries1.txt', delim_whitespace=True, header=1).drop(labels="Reaction", axis=1).drop(labels='Fired', axis=1).as_matrix()
new_datapoint = self.time_resampling(datapoint)
X[ind,k,:,:] = new_datapoint[1:,1:self.state_space_dim+1]
self.X = X
self.Y_s0 = Ys
self.Y_par = Yp
self.Y = np.hstack((Yp,Ys))
def save_dataset(self, filename):
dataset_dict = {"X": self.X, "Y_s0": self.Y_s0, "Y": self.Y, "Y_par": self.Y_par}
with open(filename, 'wb') as handle:
pickle.dump(dataset_dict, handle, protocol=pickle.HIGHEST_PROTOCOL)
def run_training(filename):
n_init_states = 5000
n_trajs = 10
state_space_dim = 8
time_step = 60
n_steps = 32
T = n_steps*time_step
param_space_dim = 1
param_space_bounds = np.array([0.1,2.5])
mapk_dataset = AbstractionDataset(n_init_states, n_trajs, state_space_dim, param_space_bounds, 'MAPK', time_step, T)
start_time = time.time()
mapk_dataset.generate_training_set()
print("Time to generate the training set w fixed param =", time.time()-start_time)
mapk_dataset.save_dataset(filename)
def run_validation(filename):
n_init_states = 0
n_trajs = 0
state_space_dim = 8
time_step = 60
n_steps = 32
T = n_steps*time_step
n_val_points = 100
n_trajs_per_point = 5000
param_space_dim = 1
param_space_bounds = np.array([0.1,2.5])
sir_dataset = AbstractionDataset(n_init_states, n_trajs, state_space_dim, param_space_bounds, 'EGF', time_step, T)
start_time = time.time()
sir_dataset.generate_validation_set(n_val_points, n_trajs_per_point)
print("Time to generate the validation set w fixed param =", time.time()-start_time)
sir_dataset.save_dataset(filename)
run_training("../../data/MAPK/MAPK_training_set_one_param.pickle")
#run_validation("../../data/MAPK/MAPK_validation_one_param.pickle")
| true |
f32fd651ed9420f0d018e6444c76d94a69214773 | Python | holland-backup/holland | /holland/core/backup/base.py | UTF-8 | 12,662 | 2.578125 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | """
Define how backup plugins will be called
"""
import errno
import logging
import os
import sys
import time
from holland.core.plugin import PluginLoadError, load_backup_plugin
from holland.core.spool import Backup
from holland.core.util.fmt import format_bytes, format_interval
from holland.core.util.path import directory_size, disk_free
MAX_SPOOL_RETRIES = 5
LOG = logging.getLogger(__name__)
class BackupError(Exception):
"""Error during a backup"""
class BackupPlugin(object):
"""
Define a backup plugin
"""
def __init__(self, name, config, target_directory, dry_run=False):
self.name = name
self.config = config
self.target_directory = target_directory
self.dry_run = dry_run
def estimate_backup_size(self):
"""
placeholder
"""
raise NotImplementedError()
def backup(self):
"""
placeholder
"""
raise NotImplementedError()
def info(self):
"""
placeholder
"""
raise NotImplementedError()
def configspec(self):
"""
placeholder
"""
raise NotImplementedError()
def load_plugin(name, config, path, dry_run):
"""
Method to load plugins
"""
try:
plugin_cls = load_backup_plugin(config["holland:backup"]["plugin"])
except KeyError:
raise BackupError("No plugin defined for backupset '%s'." % name)
except PluginLoadError as exc:
raise BackupError(str(exc))
try:
return plugin_cls(name=name, config=config, target_directory=path, dry_run=dry_run)
# commenting out the below in case we actually want to handle this one day
# except (KeyboardInterrupt, SystemExit):
# raise
except Exception as exc:
LOG.debug("Error while initializing %r : %s", plugin_cls, exc, exc_info=True)
raise BackupError(
"Error initializing %s plugin: %s" % (config["holland:backup"]["plugin"], str(exc))
)
class BackupRunner(object):
"""
Run backup
"""
def __init__(self, spool):
self.spool = spool
self._registry = {}
def register_cb(self, event, callback):
"""
create callback
"""
self._registry.setdefault(event, []).append(callback)
def apply_cb(self, event, *args, **kwargs):
"""
Catch Callback
"""
for callback in self._registry.get(event, []):
try:
callback(event, *args, **kwargs)
except (KeyboardInterrupt, SystemExit):
raise
except:
raise BackupError(str(sys.exc_info()[1]))
def backup(self, name, config, dry_run=False):
"""Run a backup for the named backupset using the provided
configuration
:param name: name of the backupset
:param config: dict-like object providing the backupset configuration
:raises: BackupError if a backup fails
"""
for i in range(MAX_SPOOL_RETRIES):
try:
spool_entry = self.spool.add_backup(name)
break
except OSError as exc:
if exc.errno != errno.EEXIST:
raise BackupError("Failed to create spool: %s" % exc)
LOG.debug("Failed to create spool. Retrying in %d seconds.", i + 1)
time.sleep(i + 1)
else:
raise BackupError("Failed to create a new backup directory for %s" % name)
spool_entry.config.merge(config)
spool_entry.validate_config()
if dry_run:
# always purge the spool
self.register_cb("post-backup", lambda *args, **kwargs: spool_entry.purge())
plugin = load_plugin(name, spool_entry.config, spool_entry.path, dry_run)
spool_entry.config["holland:backup"]["start-time"] = time.time()
spool_entry.flush()
self.apply_cb("before-backup", spool_entry)
spool_entry.config["holland:backup"]["failed"] = False
try:
estimated_size = self.check_available_space(plugin, spool_entry, dry_run)
LOG.info(
"Starting backup[%s] via plugin %s",
spool_entry.name,
spool_entry.config["holland:backup"]["plugin"],
)
plugin.backup()
except KeyboardInterrupt:
LOG.warning("Backup aborted by interrupt")
spool_entry.config["holland:backup"]["failed"] = True
raise
except BaseException as ex:
LOG.warning(ex)
spool_entry.config["holland:backup"]["failed"] = True
spool_entry.config["holland:backup"]["stop-time"] = time.time()
if not dry_run and not spool_entry.config["holland:backup"]["failed"]:
final_size = float(directory_size(spool_entry.path))
LOG.info("Final on-disk backup size %s", format_bytes(final_size))
if estimated_size > 0:
LOG.info(
"%.2f%% of estimated size %s",
(final_size / estimated_size) * 100.0,
format_bytes(estimated_size),
)
spool_entry.config["holland:backup"]["on-disk-size"] = final_size
spool_entry.flush()
start_time = spool_entry.config["holland:backup"]["start-time"]
stop_time = spool_entry.config["holland:backup"]["stop-time"]
if spool_entry.config["holland:backup"]["failed"]:
LOG.error("Backup failed after %s", format_interval(stop_time - start_time))
else:
LOG.info("Backup completed in %s", format_interval(stop_time - start_time))
if dry_run:
spool_entry.purge()
if sys.exc_info() != (None, None, None) or spool_entry.config["holland:backup"]["failed"]:
LOG.debug("sys.exc_info(): %r", sys.exc_info())
self.apply_cb("failed-backup", spool_entry)
raise BackupError("Failed backup: %s" % name)
self.apply_cb("after-backup", spool_entry)
def free_required_space(self, name, required_bytes, dry_run=False):
"""Attempt to free at least ``required_bytes`` of old backups from a backupset
:param name: name of the backupset to free space from
:param required_bytes: integer number of bytes required for the backupset path
:param dry_run: if true, this will only generate log messages but won't actually free space
:returns: bool; True if freed or False otherwise
"""
LOG.info(
"Insufficient disk space for adjusted estimated backup size: %s",
format_bytes(required_bytes),
)
LOG.info("purge-on-demand is enabled. Discovering old backups to purge.")
available_bytes = disk_free(os.path.join(self.spool.path, name))
to_purge = {}
for backup in self.spool.list_backups(name):
backup_size = directory_size(backup.path)
LOG.info("Found backup '%s': %s", backup.path, format_bytes(backup_size))
available_bytes += backup_size
to_purge[backup] = backup_size
if available_bytes > required_bytes:
break
else:
LOG.info(
"Purging would only recover an additional %s", format_bytes(sum(to_purge.values()))
)
LOG.info(
"Only %s total would be available, but the current backup requires %s",
format_bytes(available_bytes),
format_bytes(required_bytes),
)
return False
purge_bytes = sum(to_purge.values())
LOG.info(
"Found %d backups to purge which will recover %s",
len(to_purge),
format_bytes(purge_bytes),
)
for backup in to_purge:
if dry_run:
LOG.info("Would purge: %s", backup.path)
else:
LOG.info("Purging: %s", backup.path)
backup.purge()
LOG.info(
"%s now has %s of available space",
os.path.join(self.spool.path, name),
format_bytes(disk_free(os.path.join(self.spool.path, name))),
)
return True
def historic_required_space(self, plugin, spool_entry, estimated_bytes_required):
"""
Use size reported in 'newest' backup to predict backup size
If this fails return a value less than zero and use the estimated-size-factor
"""
config = plugin.config["holland:backup"]
if not config["historic-size"]:
return -1.0
historic_size_factor = config["historic-size-factor"]
old_backup_config = os.path.join(self.spool.path, spool_entry.backupset, "newest")
if not os.path.exists(old_backup_config):
LOG.debug("Missing backup.conf from last backup")
return -1.0
old_backup = Backup(old_backup_config, spool_entry.backupset, "newest")
old_backup.load_config()
if (
old_backup.config["holland:backup"]["estimated-size-factor"]
and old_backup.config["holland:backup"]["on-disk-size"]
):
size_required = old_backup.config["holland:backup"]["on-disk-size"]
old_estimate = old_backup.config["holland:backup"]["estimated-size"]
else:
LOG.debug(
"The last backup's configuration was missing the \
['holland:backup']['on-disk-size'] or ['holland:backup']['estimated-size']"
)
return -1.0
LOG.info(
"Using Historic Space Estimate: Checking for information in %s",
old_backup.config.filename,
)
LOG.info("Last backup used %s", format_bytes(size_required))
if estimated_bytes_required > (old_estimate * historic_size_factor):
LOG.warning(
"The new backup estimate is at least %s times the size of "
"the current estimate: %s > (%s * %s). Default back"
" to 'estimated-size-factor'",
historic_size_factor,
format_bytes(estimated_bytes_required),
format_bytes(old_estimate),
historic_size_factor,
)
return -1.0
LOG.debug(
"The old and new backup estimate are roughly the same size, "
"use old backup size for new size estimate"
)
return size_required * float(config["historic-estimated-size-factor"])
def check_available_space(self, plugin, spool_entry, dry_run=False):
"""
calculate available space before performing backup
"""
available_bytes = disk_free(spool_entry.path)
estimated_bytes_required = float(plugin.estimate_backup_size())
spool_entry.config["holland:backup"]["estimated-size"] = estimated_bytes_required
LOG.info("Estimated Backup Size: %s", format_bytes(estimated_bytes_required))
adjusted_bytes_required = self.historic_required_space(
plugin, spool_entry, estimated_bytes_required
)
config = plugin.config["holland:backup"]
if adjusted_bytes_required < 0:
adjustment_factor = float(config["estimated-size-factor"])
adjusted_bytes_required = estimated_bytes_required * adjustment_factor
if adjusted_bytes_required != estimated_bytes_required:
LOG.info(
"Adjusting estimated size by %.2f to %s",
adjustment_factor,
format_bytes(adjusted_bytes_required),
)
else:
adjustment_factor = float(config["historic-estimated-size-factor"])
LOG.info(
"Adjusting estimated size to last backup total * %s: %s",
adjustment_factor,
format_bytes(adjusted_bytes_required),
)
if available_bytes <= adjusted_bytes_required:
if not (
config["purge-on-demand"]
and self.free_required_space(
spool_entry.backupset, adjusted_bytes_required, dry_run
)
):
msg = ("Insufficient Disk Space. %s required, " "but only %s available on %s") % (
format_bytes(adjusted_bytes_required),
format_bytes(available_bytes),
self.spool.path,
)
LOG.error(msg)
if not dry_run:
raise BackupError(msg)
return float(estimated_bytes_required)
| true |
90b02e56b2ef4fbc2add03e6077dabdc9d28eee7 | Python | WookeyBiscotti/TgReminderBot | /reminder.py | UTF-8 | 8,813 | 2.8125 | 3 | [] | no_license | import datetime
import re
import pytz
from calendar import monthrange
date_re = re.compile("(?P<day>\d{1,2}|\*)\.(?P<month>\d{1,2}|\*).(?P<year>\d{2,2}(?:\d\d)?|\*|0)")
time_re = re.compile("(?P<hours>\d{1,2}|\*)\:(?P<minutes>\d{1,2}|\*)(?:\:(?P<seconds>\d{1,2}))?")
def number(str_num):
try:
return int(str_num)
finally:
return None
class Reminder:
def __init__(self, chat_id: str, utc: int, time_form):
self.time_form = time_form
self.chat_id = chat_id
self.utc = utc
if len(time_form) < 3:
raise RuntimeError(
"Current args: {}, len {}. Usage /add [date] [time] [name]".format(time_form, len(time_form)))
idx = 0
res, err = self._get_date(time_form[idx])
if not res: raise RuntimeError(err)
idx += 1
res, err = self._get_time(time_form[idx])
if not res: raise RuntimeError(err)
idx += 1
self.name = " ".join([time_form[i] for i in range(idx, len(time_form))])
self.near_ts = self._get_near_ts()
if self.near_ts == 0:
raise RuntimeError("User max date is lower then current: {}".format(datetime.datetime.now()))
def print(self):
def a(num) -> str:
return "*" if num == -1 else num
return "Name: {}, time: {}:{}:{}, date: {}.{}.{}, near: {}".format(self.name,
a(self.hour), a(self.minute), a(self.second),
a(self.day), a(self.month), a(self.year),
datetime.datetime.fromtimestamp(
self.near_ts, tz=pytz.FixedOffset(
self.utc * 60)).strftime(
"%H:%M:%S %d.%m.%Y"))
def id(self):
return str(self.chat_id) + " ".join(self.time_form)
def _get_time(self, time_str: str) -> (bool, str):
num = number(time_str)
if num is not None:
if 0 <= num < 24:
self.hour = num
self.minute = 0
self.second = 0
return True, ""
else:
return False, "Wrong hours number. Must be 0 <= hours < 24. Actually: {}".format(num)
m = re.match(time_re, time_str)
if m is not None:
self.hour = m.groupdict().get("hours")
self.minute = m.groupdict().get("minutes")
self.second = m.groupdict().get("seconds")
if self.second is None:
self.second = "0"
if self.hour == "*":
self.hour = -1
else:
self.hour = int(self.hour)
if self.hour > 24:
return False, "Wrong hours number. Must be 0 <= hours <= 24. Actually: {}".format(self.hour)
if self.minute == "*":
self.minute = -1
else:
self.minute = int(self.minute)
if self.minute > 59:
return False, "Wrong minutes number. Must be 0 <= minutes <= 59. Actually: {}".format(self.minute)
self.second = int(self.second)
if self.second > 59:
return False, "Wrong seconds number. Must be 0 <= seconds <= 59. Actually: {}".format(self.second)
else:
return False, "time format 19:00 or 17:* or *:00 or 01:02:03"
return True, ""
def _get_date(self, date_str: str) -> (bool, str):
num = number(date_str)
now = datetime.datetime.now(tz=pytz.FixedOffset(self.utc * 60))
if num is not None:
if num <= monthrange(now.date().year, now.date().month)[1]:
self.day = num
self.month = now.date().month
self.year = now.date().year
return True, ""
else:
return False, "Wrong day number. Must be 0 < day <= {}. Actually: {}".format(
monthrange(now.date().year, now.date().month)[1], num)
m = re.match(date_re, date_str)
if m is not None:
self.day = m.groupdict().get("day")
self.month = m.groupdict().get("month")
self.year = m.groupdict().get("year")
if self.year == "*":
self.year = -1
else:
self.year = int(self.year)
if self.year < now.date().year:
return False, "Wrong year number. Must be {} <= year. Actually: {}".format(now.date().year,
self.year)
if self.month == "*":
self.month = -1
else:
self.month = int(self.month)
if self.month > 12:
return False, "Wrong month number. Must be 1 <= month <= 12. Actually: {}".format(self.month)
elif self.year == now.date().year and self.month < now.date().month:
return False, "Wrong month number. Must be {} <= month <= 12. Actually: {}".format(now.date().month,
self.month)
if self.day == "*":
self.day = -1
else:
self.day = int(self.day)
days_in_month = 31 if self.year == -1 or self.month == -1 else monthrange(self.year, self.month)[1]
if self.day > days_in_month:
return False, "Wrong seconds number. Must be 0 < day <= {}. Actually: {}".format(days_in_month,
self.second)
elif self.day == now.date().year and self.month == now.date().month and self.day < now.date().day:
return False, "Wrong day number. Must be {} <= day <= {}. Actually: {}".format(now.date().day,
days_in_month,
self.second)
else:
return False, "date format 1.2.1991 or *.12.2021"
return True, ""
def update_near_ts(self):
self.near_ts = self._get_near_ts()
def _get_near_ts(self):
tzinfo = pytz.FixedOffset(self.utc * 60)
now = datetime.datetime.now(tz=tzinfo)
now_ts = now.timestamp()
near = datetime.datetime(self.year, 1, 1, tzinfo=tzinfo) if self.year != -1 else datetime.datetime(
now.year, 1, 1, tzinfo=tzinfo)
near = near.replace(second=59 if self.second == -1 else self.second)
near = near.replace(minute=59 if self.minute == -1 else self.minute)
near = near.replace(hour=23 if self.hour == -1 else self.hour)
near = near.replace(month=12 if self.month == -1 else self.month)
near = near.replace(day=monthrange(now.year, near.month)[1] if self.day == -1 else self.day)
if self.year == -1:
if near.timestamp() < now_ts:
near = near.replace(year=near.year + 1)
else:
if near.timestamp() < now_ts:
return 0
if self.month == -1:
while near.month > 1:
new_near = near.replace(month=near.month - 1, day=monthrange(now.year, near.month - 1)[1])
if new_near.timestamp() < now_ts:
break
near = new_near
if self.day == -1:
while near.day > 1:
new_near = near.replace(day=near.day - 1)
if new_near.timestamp() < now_ts:
break
near = new_near
if self.hour == -1:
while near.hour > 0:
new_near = near.replace(hour=near.hour - 1)
if new_near.timestamp() < now_ts:
break
near = new_near
if self.minute == -1:
while near.minute > 0:
new_near = near.replace(minute=near.minute - 1)
if new_near.timestamp() < now_ts:
break
near = new_near
if self.second == -1:
while near.second > 0:
new_near = near.replace(second=near.second - 1)
if new_near.timestamp() < now_ts:
break
near = new_near
return near.timestamp()
| true |
967e7ca7da9818365bb11c22030d7d30b0d76d22 | Python | avicse007/python | /ptrhonClass.py | UTF-8 | 546 | 3.96875 | 4 | [] | no_license | #!bin/python3
class Duck:
def __init__(self,color='white'):
self._color=color;
def setColor(self,color):
self._color=color
def getColor(self):
return self._color
def quack(self):
print("Quack quack !!!!!!!");
def walk(self):
print("Walk like a duck")
def main():
donald = Duck();
donald.quack()
donald.walk()
print("Color of donal is ",donald._color)
donald._color='red'
print("Color of donal is ",donald._color)
donald.setColor("Green")
print("Now the donald color is ",donald.getColor())
if __name__=='__main__':
main()
| true |
7fcd4989b572c615526409788922d6ade4dff476 | Python | marcovankesteren/MarcovanKesteren_V1B | /Les6/pe6_5.py | UTF-8 | 101 | 3.5625 | 4 | [] | no_license | for line in range(1,11):
for table in range(1,11):
print(line * table, '\t',)
print() | true |
192076e68e9ae7b0e7442cfd5ccea2f83e262fbc | Python | m13253/scripts | /rand | UTF-8 | 252 | 2.734375 | 3 | [] | no_license | #!/usr/bin/env python
import random
import sys
if len(sys.argv) >= 3:
print(random.randint(int(sys.argv[1]), int(sys.argv[2])-1))
elif len(sys.argv) >= 2:
print(random.randint(0, int(sys.argv[1])-1))
else:
print(random.randint(0, 32767))
| true |
2bfabb367adf0352854eab1f22d1597af8b771bc | Python | mahehere/Python-Tutorials | /Healthy_Pgmr.py | UTF-8 | 2,037 | 4.03125 | 4 | [] | no_license | # 7.Healthy Programmer
""" There should a reminder for the below exercise in the specified intervals
Work Duration 9-5pm
1. water - water.mp3 - 3.5l water - input drank - timestamp log
2. eyes - eyes.mp3 - done - run every 30 minutes
3. phys activity - phy.mp3 - every 45 minutes
Rules
use pygame module"""
import pygame # For playing the mp3 file
import datetime # Module for getting the system time in log
import time # Module to get set the sleep time for constant reminder
print("This is a Healthy Programmer S/W")
print("The Work duration is from 9AM to 5PM")
def getdate():
"""This function is for getting the current system date and log it in txt file"""
# return datetime.datetime.now()
return time.asctime()
def water():
"""This is the water function to remind programmer about drinking water"""
pygame.mixer.init()
pygame.mixer.music.load("Drinking-Water.mp3")
pygame.mixer.music.play(-1)
a = input(str("Please type 'done' after drinking 1 cup water: ")).capitalize()
while True:
if a != "Done":
pygame.mixer.music.play(-1)
a = input("Please type 'done' after drinking 1 cup water: ").capitalize() # Getting user input and
# capitalising first char
elif a == "Done":
pygame.mixer.music.stop()
print("Next Reminder is after 30 Minutes")
f = open("Water.txt", "a") # can also use file command using "with open("Harry.txt","w") as f:"
f.write("Last water intake for Programmer was at " + str(getdate()) + "") # calls and logs the time in txt file
f.write(" & The user input is: " + a + "\n")
f.close() # close the txt file
break
def eyes():
print("This is the Eye function")
f = open("Eyes.csv", "a")
print(datetime.datetime.now())
f.close()
def phy_exercise():
print("This is the Exercise function")
f = open("Physical Exercise.csv", "a")
print(datetime.datetime.now())
f.close()
time.sleep(5)
water()
| true |
45b350b41ead2b16c21bf386a81785c047aa0b5c | Python | meshyx/Delta-Arm | /ik.py | UTF-8 | 3,908 | 3.125 | 3 | [] | no_license | #!/usr/bin/env python
import math
class Ik:
'''Adapted from http://forums.trossenrobotics.com/tutorials/introduction-129/delta-robot-kinematics-3276/'''
def __init__(self, e = 75, f = 62, re = 155, rf = 88):
self.maxangle = 90
self.minangle = -75
self.e = e
self.f = f
self.re = re
self.rf = rf
self.sqrt3 = math.sqrt(3.0)
self.sin120 = self.sqrt3/2.0
self.cos120 = -0.5
self.tan60 = math.sqrt(3.0)
self.sin30 = 0.5
self.tan30 = 1.0 / self.sqrt3
def calcAngleYZ(self, x0, y0, z0):
'''internal helper function'''
y1 = -0.5 * 0.57735 * self.f
y0 = y0 - 0.5 * 0.57735 * self.e
a = (x0 * x0 + y0 * y0 + z0 * z0 + self.rf * self.rf - self.re * self.re - y1 * y1) / (2 * z0)
b = (y1 - y0) / z0;
d = -(a + b * y1) * (a + b * y1) + self.rf * (b * b * self.rf + self.rf)
if (d < 0):
return False # non-existing point
yj = (y1 - a * b - math.sqrt(d)) / (b * b + 1)
zj = a + b * yj
if yj > y1:
magic = 180.0
else:
magic = 0.0
theta = 180.0 * math.atan(-zj / (y1 - yj)) / math.pi + magic
return theta
def calcInverse(self, coords):
'''coords to angles'''
x0, y0, z0 = coords
theta1 = theta2 = theta3 = 0
theta1 = self.calcAngleYZ(x0, y0, z0)
if (theta1):
theta2 = self.calcAngleYZ(x0 * self.cos120 + y0 * self.sin120, y0 * self.cos120 - x0 * self.sin120, z0)
if (theta2):
theta3 = self.calcAngleYZ(x0 * self.cos120 - y0 * self.sin120, y0 * self.cos120 + x0 * self.sin120, z0)
if (theta3):
return self.applyLimits([theta1, theta2, theta3])
else:
return False
def applyLimits(self, angles):
for i in range(len(angles)):
if (angles[i] < self.minangle):
angles[i] = self.minangle
print "servo min angle out of range"
if (angles[i] > self.maxangle):
angles[i] = self.maxangle
print "servo max angle out of range"
return angles
def calcForward(self, angles):
'''angles to coords'''
theta1, theta2, theta3 = angles
t = (self.f - self.e) * self.tan30 / 2.0
dtr = math.pi / 180.0
theta1 = theta1 * dtr
theta2 = theta2 * dtr
theta3 = theta3 * dtr
y1 = - (t + self.rf * math.cos(theta1))
z1 = - self.rf * math.sin(theta1)
y2 = (t + self.rf * math.cos(theta2)) * self.sin30
x2 = y2 * self.tan60
z2 = - self.rf * math.sin(theta2)
y3 = (t + self.rf * math.cos(theta3)) * self.sin30
x3 = - y3 * self.tan60
z3 = - self.rf * math.sin(theta3)
dnm = (y2 - y1) * x3 - (y3 - y1) * x2
w1 = y1 * y1 + z1 * z1
w2 = x2 * x2 + y2 * y2 + z2 * z2
w3 = x3 * x3 + y3 * y3 + z3 * z3
a1 = (z2 - z1) * (y3 - y1) - (z3 - z1) * (y2 - y1)
b1 = - ((w2 - w1) * (y3 - y1) - (w3 - w1) * (y2 - y1)) / 2.0
a2 = - (z2 - z1) * x3 + (z3 - z1) * x2
b2 = ((w2 - w1) * x3 - (w3 - w1) * x2) / 2.0
a = a1 * a1 + a2 * a2 + dnm * dnm
b = 2 * (a1 * b1 + a2 * (b2 - y1 * dnm) - z1 * dnm * dnm)
c = (b2 - y1 * dnm) * (b2 - y1 * dnm) + b1 * b1 + dnm * dnm * (z1 * z1 - self.re * self.re)
d = b * b - 4.0 * a * c
if (d < 0):
return False # non-existing point
z0 = -0.5 * (b + math.sqrt(d)) / a
x0 = (a1 * z0 + b1) / dnm
y0 = (a2 * z0 + b2) / dnm
return ([x0, y0, z0])
if __name__ == '__main__':
ik = Ik()
for x in range(-12, 12):
print x, x, ik.calcInverse([x, x, -120])
| true |
464f51908f3df5dccc334197e9eedf57dd7d148b | Python | grey-area/advent-of-code-2017 | /day02/part2.py | UTF-8 | 341 | 2.828125 | 3 | [] | no_license | import numpy as np
from itertools import product
data = np.loadtxt('input', dtype=np.int64)
total = 0
for i in range(data.shape[0]):
for j1, j2 in product(range(data.shape[1]), repeat=2):
if j1 == j2:
continue
if data[i, j1] % data[i, j2] == 0:
total += data[i, j1] // data[i, j2]
print(total)
| true |
80285f101e9a7ccce8013bdd5f1e9d7b0f526a74 | Python | gas1121/JapanCinemaStatusSpider | /scrapyproject/models/showing_booking.py | UTF-8 | 1,064 | 2.609375 | 3 | [
"MIT"
] | permissive | from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy_utils import ArrowType
from sqlalchemy.orm import relationship
from scrapyproject.models.models import DeclarativeBase
from scrapyproject.models.showing import Showing
class ShowingBooking(DeclarativeBase):
__tablename__ = "showing_booking"
id = Column(Integer, primary_key=True)
showing_id = Column(Integer, ForeignKey("showing.id"))
showing = relationship("Showing")
book_status = Column('book_status', String, nullable=False)
book_seat_count = Column('book_seat_count', Integer, default=0,
nullable=False)
minutes_before = Column('minutes_before', Integer, nullable=False)
record_time = Column('record_time', ArrowType, nullable=False)
def from_item(self, item):
self.book_status = item['book_status']
self.book_seat_count = item['book_seat_count']
self.minutes_before = item['minutes_before']
self.record_time = item['record_time']
self.showing = Showing(**(item['showing']))
| true |
8d59df8a96cdaab9cab9bd7da569228d8aae3d74 | Python | AkumuYuma/images_classifier | /back_end/main_api/app.py | UTF-8 | 2,406 | 2.796875 | 3 | [] | no_license | from flask import Flask, render_template, request, abort, jsonify
from flask_cors import CORS
from Database_adaptor import Database_adaptor
app = Flask(__name__)
database = Database_adaptor(app, "images", "localhost")
# Permetto le richieste CORS
CORS(app)
# Main path (test)
@app.route('/')
def hello_world():
"""
Main page con html per il caricamento
"""
return render_template("home.html")
# Route per l'upload di un file
@app.route('/api/upload/input=<inputFile>', methods=["POST"])
def upload(inputFile):
"""
Path per l'upload di un file mandato tramite richiesta POST.
Il file viene salvato nel database Mongo.
:param: immagine
:return: json con id del file caricato
"""
file = request.files[inputFile]
if not file:
abort(
404,
description="No file Selected"
)
# stato del file. Metadati. Per il momento solo processato (dal ML) e permaSaved (nell'OS)
# Gli altri servizi andranno a cercare nel db tramite lo stato del file
# prenderanno i file di interesse, li processeranno e modificheranno lo stato del file nel db.
fileId = database.save_image(file.filename, file, processed=False, permaSaved=False, classification=None)
return jsonify({"id": str(fileId)})
# Route per fare la query allo stato del file nel db da parte degli altri servizi
@app.route('/api/get_state/id=<file_Id>')
def get_state(file_Id):
"""
:param: fileId -> Id del file da controllare.
:return: json con stato dell'oggetto, 404 se file inesistente
"""
file_Id = database.type_conversion(file_Id)
file_obj = database.find_one({"_id": file_Id})
if not file_obj:
abort(
404,
description="Invalid id"
)
res = {
"processed": file_obj["processed"],
"permaSaved": file_obj["permaSaved"],
"classification": file_obj["classification"]
}
return jsonify(res)
# get del file tramite il filename
# NOTA: questo metodo è di debug, il filename non è detto che sia unico
@app.route('/api/view_one/name=<file_name>')
def get_file(file_name):
"""
:param: fileName -> nome del file
:return: prima occorrenza dell'immagine con nome richiesto
"""
return database.send_image(file_name)
if __name__ == "__main__":
app.run(host="0.0.0.0", port = 443, debug=False)
| true |
779af78e99f3174ce03ab192998f5792ec209ed2 | Python | Devalekhaa/deva | /play26.py | UTF-8 | 48 | 2.71875 | 3 | [] | no_license | import re
s=input()
print (re.sub(' +', ' ',s))
| true |
c2d24e93f94348d63df7c1293382315d48b841b2 | Python | doduong0712/crawler-website | /crawldata/script.py | UTF-8 | 2,178 | 2.75 | 3 | [] | no_license | # Import
from selenium import webdriver
import csv
from bs4 import BeautifulSoup
driver = webdriver.Chrome(executable_path='.\Driver\chromedriver.exe')
url = 'https://www.agencyvietnam.com'
driver.get(url)
""" driver.find_element_by_id('5680').click() """
def GetURL():
page_source = BeautifulSoup(driver.page_source)
profile_agencys = page_source.find_all(
'a', class_='agency-card')
all_agency_URL = []
for profile_agency in profile_agencys:
agency_ID = profile_agency.get('href')
agency_URL = "https://www.agencyvietnam.com/" + agency_ID
if agency_URL not in all_agency_URL:
all_agency_URL.append(agency_URL)
return all_agency_URL
with open('output.csv', 'w', newline='') as file_output:
headers = ['Name Agency', 'Email', 'Personel']
writer = csv.DictWriter(file_output, delimiter=',',
lineterminator='\n', fieldnames=headers)
writer.writeheader()
URL_get_page = GetURL()
for agency_link in URL_get_page:
driver.get(agency_link)
page_source = BeautifulSoup(driver.page_source, "html.parser")
info_div = page_source.find(
'div', class_='col-12 col-sm-8 col-md-9 mt-10')
name = info_div.find('h1').get_text().strip()
infor_plus = info_div.find('div', class_='gap-items-1 gap-y')
infor_plusssss = infor_plus.find_all('div')
check_email = infor_plusssss[2].find('a')
if check_email is None:
email = "The value is not null"
else:
email = infor_plusssss[2].find('a').get_text().strip()
personal = page_source.find(
'div', class_='media-list media-list-divided media-list-sm')
personal_span = personal.find('span')
personal_spans = personal_span.find_all(
'span', class_='fw-600')
name_personal = []
for name_personalss in personal_spans:
name_personal.append(name_personalss.get_text().strip())
writer.writerow({headers[0]: name, headers[1]
: email, headers[2]: name_personal})
""" for namepersonal in personal_spans:
print(namepersonal) """
| true |
9bbd308008854206c57f4aefbdf8910ea86b89d6 | Python | ciprianprohozescu/georgia-tech-library | /Scripts/Setup/generate_volume.py | UTF-8 | 1,079 | 2.609375 | 3 | [
"MIT"
] | permissive | import random
random.seed()
f = open("populate_volume.sql", "w")
bookTotal = 10000
for i in range(1, bookTotal + 1):
volumeTotal = random.randint(0, 100)
if volumeTotal == 0:
continue
volumeTotal = random.randint(1, 5)
for j in range(1, volumeTotal + 1):
library = random.randint(0, 5)
acquiryDate = ''
if library != 0:
day = random.randint(1, 28)
month = random.randint(1, 12)
year = random.randint(1990, 2020)
acquiryDate = acquiryDate + str(year)
if month < 10:
acquiryDate = acquiryDate + '0'
acquiryDate = acquiryDate + str(month)
if day < 10:
acquiryDate = acquiryDate + '0'
acquiryDate = acquiryDate + str(day)
if library != 0:
f.write(f"insert into Volume (id, book_id, source_library_id, acquiry_date) values ({j}, {i}, {library}, '{acquiryDate}');\n")
else:
f.write(f'insert into Volume (id, book_id) values ({j}, {i});\n')
f.close() | true |
90887ab07ba62a7a414a990e05bc6558cc631a30 | Python | HyOsori/battle.ai | /game/pixels/PixelsParser.py | UTF-8 | 4,943 | 2.640625 | 3 | [
"MIT"
] | permissive | #-*-coding:utf-8-*-
import base64
import json
import sys
import zlib
sys.path.insert(0,'../')
from gamebase.client.AIParser import AIParser
class PixelsParser(AIParser):
def __init__(self):
pass
def parsing_data(self, decoding_data):
print("parsing_data is called")
base = super(PixelsParser, self).parsing_data(decoding_data)
print("super.parsing_data is called")
print("self.msg_type: " + self.msg_type)
ret = None
if self.msg_type == 'loop':
if self.game_data['enemy_chosen_color'] != None:
self.absorb(self.game_data['ruler_enemy'], self.game_data['enemy_chosen_color'])
ret = self.loop_phase()
print(ret)
print("before absorb")
self.absorb(self.game_data['ruler_self'], ret['chosen_color'])
print("after absorb")
if self.msg_type == 'notify_init_loop':
ret = self.notify_loop_init()
if self.msg_type == 'notify_change_round':
ret = self.notify_change_round()
if ret == None:
return base
else:
return self.make_send_msg(self.msg_type,ret)
def loop_phase(self):
'''
must override
:return:
'''
pass
def notify_loop_init(self):
print('notify_loop_init get!')
self.width = self.game_data['width']
self.height = self.game_data['height']
self.color_array = json.loads(self.game_data['color_array'])
self.ruler_array = [[0 for x in range(self.width)] for y in range(self.height)]
ys = self.game_data['start_point_y']
xs = self.game_data['start_point_x']
self.ruler_array[ys[0]][xs[0]] = 1
self.ruler_array[ys[1]][xs[1]] = 2
self.color_array_old = self.copy_array(self.color_array)
self.ruler_array_old = self.copy_array(self.ruler_array)
return None
def notify_change_round(self):
print('notify_change_round get!')
self.color_array = self.copy_array(self.color_array_old)
self.ruler_array = self.copy_array(self.ruler_array_old)
ys = self.game_data['start_point_y']
xs = self.game_data['start_point_x']
self.ruler_array[ys[0]][xs[0]] = 1
self.ruler_array[ys[1]][xs[1]] = 2
return None
def absorb(self, ruler, chosen_color):
ruler_array_copy = [[0 for x in range(self.width)] for y in range(self.height)]
for y in range(self.height): # Fill ruled area with chosen_color.
for x in range(self.width):
if self.ruler_array[y][x] == ruler:
self.color_array[y][x] = chosen_color
absorb_repeat = True
while absorb_repeat: # Absorb repeatedly for complete absorbing.
for y in range(self.height): # Copy ruler_array for repetitive absorbing.
for x in range(self.width):
ruler_array_copy[y][x] = self.ruler_array[y][x]
for y in range(self.height): # Absorb.
for x in range(self.width):
if self.ruler_array[y][x] == 0 and self.color_array[y][x] == chosen_color and (
# If the area isn't ruled and is filled with chosen color,
(x > 0 and self.ruler_array[y][x - 1] == ruler) # Check left side,
or (x < (self.width - 1) and self.ruler_array[y][x + 1] == ruler) # Check right side,
or (y > 0 and self.ruler_array[y - 1][x] == ruler) # Check up side,
or (y < (self.height - 1) and self.ruler_array[y + 1][x] == ruler) # Check down side,
): # If ruler's area is adjacent,
self.ruler_array[y][x] = ruler # Rule the area.
absorb_repeat = False
check_stop = False
# If ruler_array == ruler_array_copy, finish absorbing.
# = If there isn't any change after absorbing, absorbing is complete, so finish absorbing.
for y in range(self.height):
if check_stop:
break
for x in range(self.width):
if self.ruler_array[y][x] != ruler_array_copy[y][x]:
absorb_repeat = True
check_stop = True # To escape from outer for loop.
break
def copy_array(self, array):
retrun_array = [[array[y][x] for x in range(self.width)] for y in range(self.height)]
return retrun_array
def print_array(self, array):
'''
for debug
:param array:
:return:
'''
print('array print: ')
for y in range(self.height):
for x in range(self.width):
sys.stdout.write(str(array[y][x])+' ')
print('')
def ruler_setting(self, start_point_y, start_point_x):
pass | true |
92193c0d69ea6220994e4d56da3d81fde4db72b1 | Python | LokeshVarman/Python | /calci.py | UTF-8 | 412 | 4.3125 | 4 | [] | no_license | print("CALUCULATING TWO NUMBERS")
a=float(input())
b=float(input())
print("1.add \n 2.subtract \n 3.divide \n 4.multiply \n 5.modulo" )
choice=input("enter your choice")
if choice=="1":
ans=a+b
print(ans)
if choice=="2":
ans=a-b
print(ans)
if choice=="3":
ans=a/b
print(ans)
if choice=="4":
ans=a*b
print(ans)
if choice=="5":
ans=a%b
print(ans)
else:
print("Please enter the choice given")
| true |
a73c5de5f63813d1ea00ab7cb85ea8a705e8fcb8 | Python | psxvoid/idapython-debugging-dynamic-enrichment | /DDE/Common/memobject.py | UTF-8 | 1,111 | 3.21875 | 3 | [
"MIT"
] | permissive | class MemObject(object):
def __init__(self, addr, deepness = 0):
self.addr = addr
self.deepness = deepness
def __repr__(self):
return "<MemObject at 0x{:X}>".format(self.addr)
def __eq__(self, other):
if isinstance(other, MemObject):
return self.addr == other.addr
return False
def __ne__(self, other):
result = self.__eq__(other)
class NullObject(object):
def __init__(self, *args, **kwargs):
super(NullObject, self).__init__(*args, **kwargs)
def __repr__(self):
return "NULL"
class ConditionalFormat(object):
def __init__(self, value):
super(ConditionalFormat, self).__init__()
if type(value) == NullObject:
self.format = "{}"
self.repr = repr(value)
elif issubclass(type(value), MemObject):
self.format = "0x{:X}"
self.repr = value.addr
else:
self.format = "0x{:X}"
self.repr = value
def __repr__(self):
return "<ConditionalFormat format: %s, repr: %s>" % (self.format, self.repr) | true |
f94dc577740c31034a28f049fcbfe314acf3cc2a | Python | GrishaAdamyan/All_Exercises | /Statistics.py | UTF-8 | 553 | 3.53125 | 4 | [] | no_license | def print_statistics(arr):
arr.sort()
if len(arr) != 0:
erkarutyun = len(arr)
mijin = sum(arr) / len(arr)
minimum = min(arr)
maximum = max(arr)
if len(arr) % 2 == 1:
mijnativ = arr[len(arr) // 2]
else:
mijnativ = (arr[(len(arr) // 2) - 1] + arr[len(arr) // 2]) / 2
else:
erkarutyun = 0
mijin = 0
minimum = 0
maximum = 0
mijnativ = 0
print(erkarutyun, mijin, minimum, maximum, mijnativ, sep='\n')
print_statistics([1, 2, 3]) | true |
11d41b600ae5aaf0d16df22ca822940e80e4f484 | Python | jeen0404/Text-to-speech-python | /entertext.py | UTF-8 | 1,387 | 3.234375 | 3 | [] | no_license | from gtts import gTTS
from playsound import playsound
import playmp3
#here you can add wellcome sound
'''
wellcome=""
playsound(wellcome)
'''
#this function is use to take input from user
def entertext():
text=str(input("enter the text"))
return text
#this is our main function it convert string into mp3 file
def prosess(name):
a=name #it,s value of we passed from while loop
path=str(a+'.mp3')#here we add to string and .mp3 extention
print(path)
text=entertext()#here we call entertext function and take input from user
t=str("")#here we define empty string
if(text==t): #here we check user text is empty or not if condition is true we call again entertext function
print("enter ext first")
entertext()
else: #if user is write some text then we convert it into voice or mp3 usein gtts here
tts = gTTS(text=text, lang='en')
tts.save(path)
playmp3.speek(path) #here we call the function of other file name is playmp3 where it play and delete
#we defaine a and convert into string because if we use only one name then the gtts will give us error so we change the name of mp3 every time
a=0
while 1 :#we use while loop because we can't open file every time
a=a+1
b=str(a)
prosess(b)#were the value of a passed to prosess function
| true |
10c1deeb0339bfd4ef441d0ee63ff5d00cb09db5 | Python | pojem/PythonSelenium | /UdemySelenium/pytestDemo/test_demo2.py | UTF-8 | 650 | 2.828125 | 3 | [] | no_license | import pytest
@pytest.mark.smoke
@pytest.mark.skip
def test_firstProgram2():
msg = "hello"
assert msg == "hello", "test failed because condition is"
def test_secondProgram2():
a = 4
b = 6
assert a + b ==10, "addition do not match"
def test_CreditCard():
a = 4
b = 6
assert a + b == 10, "addition do not match"
@pytest.fixture()
def setup():
print("i will be executing first")
def test_fixtureDemo(setup):
print("i will execute steps in fixtureDemo method")
#run specific py file: pytest test_demo2.py
#run only test which contains word: pytest -k CreditCard -v -s
#run smoke tests pytest -m smoke -v -s
| true |
a2eee3464c694a8f43b7bfff83203a674609b498 | Python | RachitVargas/segmentacion_SO | /unidad.py | UTF-8 | 615 | 2.984375 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 20 23:36:23 2021
@author: antony.vargasulead.ac.cr
"""
class Unidad():
def __init__(self, disponible):
self.__unidad_disponible = disponible
self.__cola = []
@property
def unidad_disponible(self):
return self.__unidad_disponible
@unidad_disponible.setter
def unidad_disponible(self, unidad_disponible):
self.__unidad_disponible = unidad_disponible
@property
def cola(self):
return self.__cola
@cola.setter
def cola(self, valor):
self.__cola.append(valor) | true |
b0447875b660a63fe46083713315a1c0b1d02df8 | Python | ryantbvt/MotivationalTwitterBotPublic | /testing.py | UTF-8 | 1,546 | 2.796875 | 3 | [] | no_license | import tweepy
import time
print("Booting")
CONSUMER_KEY = 'yXM2wbNnSzYjDWmyjgSJx72I2'
CONSUMER_SECRET = 'vIU6koLTE1vUe4X4PycNYHONg4kViO02IgF3DU5P3cDvMrLW76'
ACCESS_KEY = '1247728862340972544-XXBsavSHzZPItSOTyNOUEmyhmy8ZSN'
ACCESS_SECRET = 'ZaURSeuvtT3t10K2F0pM8K8WNjHVwuuuAMomcBM80OZll'
#API commands
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
def newFollowers():
followers = tweepy.Cursor(api.followers).items(1)
#grabs the last user
for follower in followers:
#print(follower.screen_name)
lastUser = follower.id
if lastUser != retrieve_last_follower():
store_last_follower(lastUser)
return True
return False
def retrieve_last_follower():
f = open('follower_id.txt', 'r')
last_follower = int(f.read().strip())
f.close()
return last_follower
def store_last_follower(newFollower):
f = open('follower_id.txt', 'w')
f.write(str(newFollower))
f.close()
return
def dmInfo():
if newFollowers() == True:
api.send_direct_message(retrieve_last_follower(), 'Thank you for following the Motivational Bot, here are a list of commands:'
+ '\n#motivation : for a motivational quote'
+ '\n#addquote : to add a quote to the community'
+ '\n#communityquote : for a quote from the community'
+ '\n#hello : for a simple hello!')
dmInfo()
while True:
print('looking for new followers')
time.sleep(60) | true |
66e76c2ba97274dd8efbe9bb5e19f531b4a686c0 | Python | suyanzhe/291_take_home_final_code | /2.py | UTF-8 | 2,841 | 3.65625 | 4 | [] | no_license | import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# Line search on f(x)=x^4
def steepest_descent_x4(alpha, x):
derivative = 4 * np.power(x, 3)
return x - alpha * derivative
def compute_optimal_step_size(x):
derivative = 4 * np.power(x, 3)
return x / derivative if derivative else 0
def newton_x4(step_size, x):
derivative = 4 * np.power(x, 3)
second_derivative = 12 * np.power(x, 2)
return x - step_size * derivative / second_derivative
def iterate(x, function, num_of_iterations, alpha):
values = []
for i in range(num_of_iterations):
values.append(np.power(x, 4))
x = function(alpha, x)
values.append(np.power(x, 4))
return values
def iterate_with_optimal_step_size(x, num_of_iterations):
values = []
for i in range(num_of_iterations):
values.append(np.power(x, 4))
alpha = compute_optimal_step_size(x)
x = steepest_descent_x4(alpha, x)
values.append(np.power(x, 4))
return values
def draw_curves(data_group, num_of_iterations = 100, fig_name = None, colors = None):
plt.rcParams["font.family"] = "STIX"
plt.rcParams["mathtext.fontset"] = "stix"
iters = range(num_of_iterations + 1)
figure = plt.figure(figsize=(8, 2.5))
if colors is not None:
for data, c in zip(data_group, colors):
plt.plot(iters, data[1], label = data[0], color = c)
else:
for data in data_group:
plt.plot(iters, data[1], label = data[0])
plt.legend()
plt.title(r"How the function values of $f\left(x\right)=x^4$ change in the first " + str(num_of_iterations) + " iterations")
plt.xlabel("After iteration #")
plt.ylabel(r"Value of $x^4$")
plt.subplots_adjust(0.1, 0.175, 0.975, 0.9)
if fig_name is not None:
plt.savefig(fig_name + ".pdf", dpi = 3584)
plt.show()
def main(num_of_iterations):
c = ["#F44336", "#FF9800", "#000000", "#2196F3", "#00BCD4", "#4CAF50"]
x_0 = 1
data_group = [("Steepest descent, learning rate = " + str(alpha), iterate(x_0, steepest_descent_x4, num_of_iterations, alpha)) for alpha in [0.1, 0.01]]
draw_curves(data_group, num_of_iterations, fig_name = "steepestdescent", colors = c[:len(data_group)])
data_group.append(("Steepest descent with the optimal step size", iterate_with_optimal_step_size(x_0, num_of_iterations)))
draw_curves(data_group, num_of_iterations, fig_name = "optimalstep", colors = c[:len(data_group)])
data_group.extend([("Newton direction, step size = " + str(step_size), iterate(x_0, newton_x4, num_of_iterations, step_size)) for step_size in [1, 0.3, 0.1]])
draw_curves(data_group, num_of_iterations, fig_name = "Newton", colors = c[:len(data_group)])
if __name__ == "__main__":
main(100) | true |
4e8648c22b32bbaf2fe94e4d964df2509484cc60 | Python | charlesdaniels/teaching-learning | /data_structures/simple_fa/simple_fa.py | UTF-8 | 8,736 | 3.21875 | 3 | [
"BSD-3-Clause"
] | permissive | #!/usr/bin/env python3
# Copyright (c) 2018, Charles Daniels
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# Script that shows an example of simulating a finite automata in Python. This
# was originally part of a larger project, but has been stripped out for
# demonstration purposes, and a toy problem has been constructed to show off
# the functionality herein.
# For this example, we will parse tabular data which has been converted to an
# ordered list of strings. Consider a table with the columns
# STUDENT_ID,COURSE,GPA. Consider also that when a student has taken more than
# one course, the additional course is attached to the pertinent record by
# including a line of the format <empty string>,COURSE,GPA. For example, the
# input:
# jsmith,MATH101,3.0
# ,ENGL101,4.0
# Would imply a record attached to the student jsmith containing a score of 3.0
# for MATH101, and a score of 4.0 for ENGL101. An arbitrary number of scores
# might be attached to one record in this way.
# To simulate the original use case for this simulator, the input is read from
# standard in with one cell per line, so the example above would be input as
# follows:
# jsmith
# MATH101
# 3.0
#
# ENGL101
# 4.0
# A set of four sample files can be found in the same folder with this program.
# sample1.txt and sample2.txt show valid inputs, while sample3.txt and
# sample4.txt show invalid inputs.
# The automata in this program is made up of a table of transitions, such that
# the ith index in the table contains a list of transitions AWAY from that
# state. Transitions are ordered from highest priority to lowest priority.
# Each transition contains a regex which the current token must match, and the
# highest priority token where the regex matches the current token defines the
# next state of the DFA.
import argparse
import sys
import re
args = None
# This is the table of states. The nth item in the table is state n, and
# contains a list of tuples, each of which describe a transition. A transition
# contains a regex, which if matched by the input token will cause it to be
# taken, the target state to transition to, and the field which we must have
# been looking at before the transition. If more than one transition could be
# taken, then the first one is taken.
# pattern, transition, field
transition_table = [
[('[a-zA-Z0-9]', 1, "STUDENTID")],
[('[A-Z]{4}[0-9]{3}', 2, "COURSE")],
[('[0-9]{1,2}\.[0-9]{1,2}', 3, "GPA")],
[('[a-zA-Z0-9]', 1, "STUDENTID"),
('', 1, "NULL")],
]
def verbose(msg):
if not args.verbose:
return
msg = "{}\n".format(msg)
sys.stderr.write(msg)
sys.stderr.flush()
def next_state(current_state, text):
# consider all possible transitions away from the current state
for transition_tup in transition_table[current_state]:
# unpack the tuple into it's component parts
pattern, transition, field = transition_tup
# check if it matches the pattern
r = re.compile(pattern)
if r.match(text):
verbose("{} --- ('{}' matched '{}' => {}) ---> {}"
.format(current_state, text, pattern,
field, transition))
# extra debugging output for ERROR fields
if field == "ERROR":
verbose("error transition while matching " +
"'{}' which is {} from state {}"
.format(
text, ':'.join([hex(ord(x))[2:] for x in text]),
current_state))
verbose ("other transitions were: {}"
.format(transition_table[current_state]))
return (transition, field)
# if execution reaches this point, the transition table is invalid
sys.stderr.write("FATAL: invalid transition table\n")
exit(1)
def visualize_transitions():
from graphviz import Digraph
table = transition_table
dot = Digraph(comment='Transition Table')
for node_num in range(len(table)):
nodelabel = "({})\n".format(node_num)
transitions = table[node_num]
t_num = 0
for t in transitions:
pattern, target, field = t
# render epsilon transitions
if pattern == "":
pattern = "epsilon"
pattern = "{}: {}\n".format(t_num, pattern)
dot.edge("{}".format(node_num),
"{}".format(target),
label = pattern)
nodelabel += "{}: ".format(t_num) + field + "\n"
t_num += 1
dot.node("{}".format(node_num), label=nodelabel)
dot.render("table.dot")
def extractEntries(f):
err_trans = ('', 0, "ERROR")
# Every transition must also support the error transition, which is an
# epsilon-transition back to state zero. When this transition is taken, the
# field is marked as 'ERROR', and extractEntries() induces a crash.
for t in transition_table:
t.append(err_trans)
current_state = 0
counter = 1
field = None
last_field = None
records = []
accumulator = {}
for line in f:
line = line.strip()
# get the next state from the transition table
last_field = field
current_state, field = \
next_state(current_state, line)
# make sure the transition was valid
if field == "ERROR":
sys.stderr.write("FATAL: invalid transition while reading " +
"record {}\n".format(counter) )
exit(1)
# transition to parsing a new record
if last_field == "GPA" and field == "STUDENTID":
records.append(accumulator)
verbose("Finished parsing a record: {}".format(accumulator))
accumulator = {}
counter += 1
# insert the field into the accumulator
if field != "NULL":
if field not in accumulator:
accumulator[field] = []
accumulator[field].append(line)
# make sure we catch the last record
if len(accumulator) > 0:
if field == "GPA":
verbose("Finished parsing a record: {}".format(accumulator))
records.append(accumulator)
else:
sys.stderr.write("FATAL: incomplete record\n")
exit(1)
print("- - - finished parsing, dump of records - - -")
for rec in records:
print(rec)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--input", "-i", default=sys.stdin, help="Specify " +
"file (default: standard input")
parser.add_argument("--verbose", "-v", default=False, action="store_true",
help="Display verbose output")
parser.add_argument("--visualize", "-s", default=False, action="store_true",
help="Visualize the FA in a file table.gv.pdf")
global args
args = parser.parse_args()
if args.input is not sys.stdin:
args.input = open(args.input, "r")
extractEntries(args.input)
if args.visualize:
visualize_transitions()
if __name__ == "__main__":
main()
| true |
318962fb662e6234ac2a0718798aeb341e81f9c1 | Python | indunilLakshitha/Phthon- | /2.3 Dictionaries.py | UTF-8 | 141 | 2.953125 | 3 | [] | no_license | dict1={'name':'John','age':21,'maths':88,'chem':92,'phys':96,11:0}
dict1[11]=(dict1['maths']+dict1['chem']+dict1['phys'])/3.0
print(dict1)
| true |
79a1ba7a35ada26d5f1a6d1a9009d5340a811253 | Python | johnmapesjr/General | /Neural Net/nn2layer.py | UTF-8 | 1,836 | 3.390625 | 3 | [] | no_license | #!/usr/bin/python3
def g( x ): return x
class Node( ):
def __init__( self ):
self.value = 0.0
self.i_connections = [ ]
self.o_connections = [ ]
def update( self ):
summation = 0.0
for connection in self.i_connections:
summation += connection.weight * connection.node.value
self.value = g( summation )
class Layer( ):
def __init__( self, size ):
self.size = size
self.nodes = [ Node( ) for i in range( size ) ]
def __str__( self ):
return "Layer has %s nodes." % ( self.size )
class Connection( ):
def __init__( self, node ):
self.weight = 0.0
self.node = node
def FullyConnectNodes( Input_Nodes, Output_Nodes ):
for i_node in Input_Nodes:
for o_node in Output_Nodes:
o_node.i_connections.append( Connection( i_node ))
class Neural_Net( ):
def __init__( self ):
self.ipl = Layer( 5 )
self.opl = Layer( 5 )
FullyConnectNodes( self.ipl.nodes, self.opl.nodes )
def calculate( self ):
print( "Calculating..." )
for node in self.opl.nodes:
node.update( )
nn = Neural_Net( )
print ( "input" )
for node in nn.ipl.nodes:
print( node.value )
print ( "output" )
for node in nn.opl.nodes:
print( node.value )
print ( "weights" )
for node in nn.opl.nodes:
print( "-" )
for connection in node.i_connections:
print( connection.weight )
nn.ipl.nodes[0].value = 0.5
nn.ipl.nodes[1].value = 0.5
nn.ipl.nodes[2].value = 0.5
nn.opl.nodes[0].i_connections[0].weight = 0.5
nn.opl.nodes[0].i_connections[1].weight = 0.5
nn.opl.nodes[0].i_connections[2].weight = 0.5
nn.opl.nodes[0].i_connections[3].weight = 0.5
nn.calculate( )
print ( "input" )
for node in nn.ipl.nodes:
print( node.value )
print ( "output" )
for node in nn.opl.nodes:
print( node.value )
print ( "weights" )
for node in nn.opl.nodes:
print( "-" )
for connection in node.i_connections:
print( connection.weight )
| true |
c9b1b33cb1cb362d56c9b2f0a137184ae2c9029e | Python | WONJUNGHEE/algorithm_practice | /programmers/level2/다리를 지나는 트럭.py | UTF-8 | 633 | 2.625 | 3 | [] | no_license | def solution(bridge_length, weight, truck_weights) :
truck_weights = truck_weights[::-1]
n = len(truck_weights)
passing_weight = [0]*n
passed = []; passing = []
i = 0; j = -1
while len(passed)<n :
if len(truck_weights)>0 and sum(passing) + truck_weights[-1] <= weight :
passing.append(truck_weights.pop())
j+=1
passing_weight[:j+1] = [passing_weight[z]+1 for z in range(j+1)]
if passing_weight[i] == bridge_length :
passed.append(passing[0])
passing = passing[1:]
i+=1
return passing_weight[0]+1
| true |
7fabb5a1e468612e0a75011463c4ad840acedd3d | Python | eliotbush/super-duper-dollop | /echo_client2.py | UTF-8 | 387 | 3.140625 | 3 | [] | no_license | import socket
ip = "10.0.0.69"
port = 50149
# Connect to the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ip, port))
# Send the data
message = 'Hello, world'
print('Sending : "%s"' % message)
len_sent = s.send(message.encode('ascii'))
# Receive a response
response = s.recv(len_sent).decode('ascii')
print('Received: "%s"' % response)
# Clean up
s.close() | true |
3e78e946e0acc7a628dad75c895660db04133635 | Python | Yelp/Tron | /tests/utils/crontab_test.py | UTF-8 | 3,953 | 2.765625 | 3 | [
"Apache-2.0"
] | permissive | from unittest import mock
from testifycompat import assert_equal
from testifycompat import assert_raises
from testifycompat import run
from testifycompat import setup
from testifycompat import TestCase
from tron.utils import crontab
class TestConvertPredefined(TestCase):
def test_convert_predefined_valid(self):
expected = crontab.PREDEFINED_SCHEDULE["@hourly"]
assert_equal(crontab.convert_predefined("@hourly"), expected)
def test_convert_predefined_invalid(self):
assert_raises(ValueError, crontab.convert_predefined, "@bogus")
def test_convert_predefined_none(self):
line = "something else"
assert_equal(crontab.convert_predefined(line), line)
class TestParseCrontab(TestCase):
def test_parse_asterisk(self):
line = "* * * * *"
actual = crontab.parse_crontab(line)
assert_equal(actual["minutes"], None)
assert_equal(actual["hours"], None)
assert_equal(actual["months"], None)
@mock.patch("tron.utils.crontab.MinuteFieldParser.parse", autospec=True)
@mock.patch("tron.utils.crontab.HourFieldParser.parse", autospec=True)
@mock.patch("tron.utils.crontab.MonthdayFieldParser.parse", autospec=True)
@mock.patch("tron.utils.crontab.MonthFieldParser.parse", autospec=True)
@mock.patch("tron.utils.crontab.WeekdayFieldParser.parse", autospec=True)
def test_parse(self, mock_dow, mock_month, mock_monthday, mock_hour, mock_min):
line = "* * * * *"
actual = crontab.parse_crontab(line)
assert_equal(actual["minutes"], mock_min.return_value)
assert_equal(actual["hours"], mock_hour.return_value)
assert_equal(actual["monthdays"], mock_monthday.return_value)
assert_equal(actual["months"], mock_month.return_value)
assert_equal(actual["weekdays"], mock_dow.return_value)
class TestMinuteFieldParser(TestCase):
@setup
def setup_parser(self):
self.parser = crontab.MinuteFieldParser()
def test_validate_bounds(self):
assert_equal(self.parser.validate_bounds(0), 0)
assert_equal(self.parser.validate_bounds(59), 59)
assert_raises(ValueError, self.parser.validate_bounds, 60)
def test_get_values_asterisk(self):
assert_equal(self.parser.get_values("*"), list(range(0, 60)))
def test_get_values_min_only(self):
assert_equal(self.parser.get_values("4"), [4])
assert_equal(self.parser.get_values("33"), [33])
def test_get_values_with_step(self):
assert_equal(self.parser.get_values("*/10"), [0, 10, 20, 30, 40, 50])
def test_get_values_with_step_and_range(self):
assert_equal(self.parser.get_values("10-30/10"), [10, 20, 30])
def test_get_values_with_step_and_overflow_range(self):
assert_equal(self.parser.get_values("30-0/10"), [30, 40, 50, 0])
def test_parse_with_groups(self):
assert_equal(self.parser.parse("5,1,7,8,5"), [1, 5, 7, 8])
def test_parse_with_groups_and_ranges(self):
expected = [0, 1, 11, 13, 15, 17, 19, 20, 21, 40]
assert_equal(self.parser.parse("1,11-22/2,*/20"), expected)
class TestMonthFieldParser(TestCase):
@setup
def setup_parser(self):
self.parser = crontab.MonthFieldParser()
def test_parse(self):
expected = [1, 2, 3, 7, 12]
assert_equal(self.parser.parse("DEC, Jan-Feb, jul, MaR"), expected)
class TestWeekdayFieldParser(TestCase):
@setup
def setup_parser(self):
self.parser = crontab.WeekdayFieldParser()
def test_parser(self):
expected = [0, 3, 5, 6]
assert_equal(self.parser.parse("Sun, 3, FRI, SaT-Sun"), expected)
class TestMonthdayFieldParser(TestCase):
@setup
def setup_parser(self):
self.parser = crontab.MonthdayFieldParser()
def test_parse_last(self):
expected = [5, 6, "LAST"]
assert_equal(self.parser.parse("5, 6, L"), expected)
if __name__ == "__main__":
run()
| true |
428e92490512c182f123cae0be56ebc9dbe772d3 | Python | mars-project/mars | /mars/tensor/base/array_split.py | UTF-8 | 1,631 | 3.03125 | 3 | [
"BSD-3-Clause",
"MIT",
"ISC",
"Apache-2.0",
"CC0-1.0",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 1999-2021 Alibaba Group Holding Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from .split import _split
def array_split(a, indices_or_sections, axis=0):
"""
Split a tensor into multiple sub-tensors.
Please refer to the ``split`` documentation. The only difference
between these functions is that ``array_split`` allows
`indices_or_sections` to be an integer that does *not* equally
divide the axis. For a tensor of length l that should be split
into n sections, it returns l % n sub-arrays of size l//n + 1
and the rest of size l//n.
See Also
--------
split : Split tensor into multiple sub-tensors of equal size.
Examples
--------
>>> import mars.tensor as mt
>>> x = mt.arange(8.0)
>>> mt.array_split(x, 3).execute()
[array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7.])]
>>> x = mt.arange(7.0)
>>> mt.array_split(x, 3).execute()
[array([ 0., 1., 2.]), array([ 3., 4.]), array([ 5., 6.])]
"""
return _split(a, indices_or_sections, axis=axis)
| true |
b880eae365dc7d7994e1b6d4a10c33844d37aa1e | Python | anitera/distributedhw2 | /sessions_authorization.py | UTF-8 | 4,962 | 2.609375 | 3 | [] | no_license | import os
try:
import tkinter as tk
except ImportError:
import Tkinter as tk
try:
import tkMessageBox as tkBox
except ImportError:
from tkinter import messagebox as tkBox
sessionname_return = ''
sessuionsize_return = 0
choice = ''
from threading import Thread
import select
from protocol import *
from Tkinter import END
def send_data_sessions(listbox, sessions, number_of_players, window):
''' authorization of the session '''
print 'send data ', listbox, ' sess: ', sessions
current = listbox.curselection()
global sessionname_return
global sessionsize_return
global choice
if current:
print 'Decide to join existing session'
sessionname = listbox.get(current[0])
print("Session size is...", sessionname)
window.destroy()
sessionname_return = sessionname[0]
sessionsize_return = sessionname[1]
choice = "player"
else:
sessionname = sessions.get()
sessionsize = number_of_players.get()
print("Connecting to...", sessionname)
#return session_size
if validate_session_name_and_size(sessionname, sessionsize):
print("Welcome,", sessionname)
tkBox.showinfo("Connected!", "Have fun!")
choice = "host"
window.destroy()
sessionname_return = sessionname
sessionsize_return = sessionsize
else:
print("CAN NOT CONNECT TO SESSION")
tkBox.showinfo("Session already booked", "try another session")
sessions.delete(0, len(sessionname))
sessions.insert(0, "")
def validate_session_name_and_size(session_name, session_size):
''' set new session '''
if len(session_name) == 0 or ' ' in session_name or len(session_name) > 8 or session_size == 0 or isinstance( session_size, ( int, long ) ):
return False
else:
return True
scan = True
def scan_sess(s, listbox, gamedict):
''' List of games available '''
s.setblocking(0)
sesslist = []
global scan
while scan:
ready = select.select([s],[],[],2)
if ready[0]:
data, addr = s.recvfrom(1024)
else:
continue
msg = data.split(DELIM)
if (msg[0],msg[1]) not in sesslist:
print "server discovered!"
sesslist.append((msg[0], msg[1]))
gamedict[msg[0]] = ((addr[0],msg[2]))
print addr
print "Available games"
sessions_counter = 0
listbox.delete(0,END)
#sessions_list = sorted(sessions_list) # Not neccessary
for sess in sesslist:
listbox.insert(sessions_counter, sess)
sessions_counter += 1
print "scan thread die"
def sessionStart(s):
''' session GUI '''
window = tk.Tk()
listbox_label_location_x = 10
listbox_label_location_y = 10
listbox_label_x = 10
listbox_label_y = 30
session_label_x = 200
session_label_y = 30
session_x = 200
session_y = 60
number_label_x = 200
number_label_y = 80
number_x = 200
number_y = 120
button_x = 200
button_y = 150
button_height = 4
button_width = 15
window.geometry('370x250')
window.resizable(width=True, height=True)
window.title('Sessions')
listbox_text = tk.Label(text = "Join exesting session")
listbox_text.place(x = listbox_label_location_x, y = listbox_label_location_y)
listbox = tk.Listbox(window)
listbox.place(x=listbox_label_x, y=listbox_label_y)
session_text = tk.Label(text="Create new one. \n Enter session name:")
session_text.place(x=session_label_x, y = session_label_y)
session = tk.Entry()
session.place(x=session_x, y=session_y)
number_label = tk.Label(text="Create new one. \n Enter number of players:")
number_label.place(x = number_label_x, y = number_label_y)
number_of_players = tk.Entry()
number_of_players.place(x=number_x, y=number_y)
a = tk.Button(window, text="Pick session", command=lambda: send_data_sessions(listbox, session,
number_of_players, window))
a.config(height = button_height, width = button_width)
a.place(x=button_x, y=button_y)
gamedict = {}
bdt = Thread(target = scan_sess, args = (s, listbox,gamedict))
bdt.start()
window.mainloop()
print "choice=", choice
global scan
scan = False
bdt.join()
global sessionname_return
global sessionsize_return
if choice == "player":
print "return player"
return choice , gamedict[sessionname_return]
if choice == "host":
print "return host"
return choice, (sessionname_return, sessionsize_return)
if __name__== "__main__":
sessions = [('ses1', 5), ('ses2', 6), ('ses3', 7)]
s_ret = sessionStart(sessions)
print 'Size of session', s_ret[0]
print 'Session name ', s_ret[1]
| true |
e12e8d5cfca1a76ec21fe99412e7589264b9d7fa | Python | val2k/algorithms | /sort/quicksort.py | UTF-8 | 291 | 3.3125 | 3 | [] | no_license | #!/usr/bin/python3.4
def quicksort(liste):
if liste == []:
return []
pivot = liste.pop(0)
bigger = list(filter(lambda x: x > pivot, liste))
smaller = list(filter(lambda x: x <= pivot, liste))
return (quicksort(smaller) + [pivot] + quicksort(bigger))
| true |
c87f8fe4ffd4942a56a60ae694f24ace7c727e9b | Python | alvas-education-foundation/ISE_3rd_Year_Coding_challenge | /4AL17IS012_Danush_Kumar/PradeepSir_codingchallenge/PradeepSir_codingchallenge1/prg3.py | UTF-8 | 338 | 4.03125 | 4 | [] | no_license | ''' 3) Write a program to get a date before and after 1 year compares to the current date. '''
from datetime import date as t
from datetime import timedelta as t1
current = t.today()
before = (t.today()-t1(days=365))
after = (t.today()+t1(days=365))
print("Current Date: ",current)
print("Before : ",before)
print("After : ",after) | true |
89fa90a5d39288bce86942d42297dcf0ff8f6ff9 | Python | vicflair/climate_change_project | /process_kpex.py | UTF-8 | 586 | 2.546875 | 3 | [] | no_license | import numpy
import tokenize
import re
fname = 'enb_corpus_kpex.kpex_n9999.txt'
with open(fname, 'r') as f:
data = f.readlines()
for i in range(0, 10):
line = data[i]
with_synonym = re.search('([^:]*)::SYN::([\w]*),F ([\d]*)', line)
if with_synonym:
concept = with_synonym.group(1)
synonym = with_synonym.group(2)
frequency = with_synonym.group(3)
else:
no_syn = re.search('([^:]*)(,F )([\d]*)', line)
concept = no_syn.group(1)
synonym = ''
frequency = no_syn.group(3)
print concept, synonym, frequency
| true |
a9aa44d0f0845e225f568a00cc81d0298cb89b10 | Python | wellington16/BSI-UFRPE | /2016.1/Exércicio LAB DE PROGRAMAÇÃO/Exercício 2016.1/Exercícios/E10/wellington_luiz_E10.py | UTF-8 | 6,759 | 3.1875 | 3 | [] | no_license | import sys
import os
# Limpar o video
if sys.platform.startswith("Win32"):
os. system("cls")
elif sys.platform.startswith("Linux"):
os.system("clear")
#Autor Wellington Luiz
'''
UNIVERSIDADE FEDERAL RURAL DE PERNAMBUCO - UFRPE
Curso: Bacharelado em Sistemas de Informação
Disciplina: Laboratório de Programação - 2016.1
Professor: Rodrigo Soares
Exercício 10 - Laboratório de Programação
título: Notação Polonesa.
Executado em python 3.4
'''
class No:
def __init__(self, valor):
self.valor = valor
self.prox = None
self.ant = None
def getValor(self):
return self.valor
def setValor(self, novodado):
self.prox = novoDado
def getNovValor(self):
return self.prox
def setNovValor(self, novoNo):
self.prox = novoNo
def getAntValor(self):
return self.ant
def setAntValor(self, novoNo):
self.ant = novoNo
class ListEncad:
def __init__(self):
self._inicio = None
self._fim = None
# Verifica se a lista está vazia
def listVazia(self):
return (self._inicio is None) or (self._fim is None)
#Inseri no inicio
def InserirNoInicio(self, valor):
NovoNo = No(valor)
if self.listVazia():
self._inicio = self._fim = NovoNo
else:
self._inicio.setAntValor(NovoNo)
NovoNo.setNovValor(self._inicio)
NovoNo.setAntValor(None)
self._inicio = NovoNo
#inseri no fim
def InserirNoFim(self, valor):
NovoNo = No(valor)
if self.listVazia():
self._inicio = self._fim = NovoNo
else:
self._fim.setNovValor(NovoNo)
NovoNo.setAntValor(self._fim)
NovoNo.setNovValor(None)
self._fim = NovoNo
#pesquisa o valor
def pesquisar (self, valor):
if self.listVazia():
return None
NoAtual = self._inicio
while NoAtual.getValor() != valor:
NoAtual = NoAtual.getNovValor()
if NoAtual == None:
return "Esse valor não foi encontrado!"
return NoAtual.getValor
#Função Impirmir
def __str__(self):
NoAtual = self._inicio
if self.listVazia():
return(" Este valor não existe.")
texto = ''
while NoAtual != None:
texto = str(NoAtual.getValor())+ " "
print(NoAtual.getValor())
NoAtual = NoAtual.getNovValor()
return texto
#Função remover
def remover(self, valor):
NoAtual = self._inicio
if self.listVazia():
return None
while NoAtual.getValor() != valor:
NoAtual = NoAtual.getNovValor()
if NoAtual == None:
return "O valor não está na lista"
if self._inicio == self._fim:
self._inicio = self._fim = None
return None
elif NoAtual == self._inicio:
aux = self._inicio.getNovValor()
self._inicio.setNovValor(None)
aux.setNovValor(None)
self._inicio = aux
elif NoAtual == self._fim:
aux = self._fim.getAntValor()
self._fim.setAntValor(None)
aux.setNovValor(None)
self._fim = aux
else:
aux = NoAtual.getAntValor()
aux2 = NoAtual.getNovValor()
aux2.setAntValor(aux)
aux.setNovValor(aux2)
#Função esvaiziar lista
def esvaziarList(self):
self._inicio = self._fim = None
class Pilha(ListEncad):
#Função remover no final da pilha
def desempilhar(self):
if self.listVazia():
return
else:
UltmValNo = self._fim.getValor()
if self._inicio is self._fim:
self._inicio = self.fim = None
else:
aux1 = self._fim.getAntValor()
self._fim.setAntValor(None)
aux1.setNovValor(None)
self._fim = aux1
return UltmValNo
class Fila(ListEncad):
#Função remover no inicio da fila
def removerInicio(self):
if self.listVazia():
return" A fila está vazia!"
else:
PrimValNo = self._inicio.getValor()
if self._inicio is self._fim:
self._inicio = self._fim = None
else:
aux2 = self._inicio.getNovValor()
self._inicio.setNovValor(None)
aux2.setAntValor(None)
self._inicio = aux2
return PrimValNo
arqEntrada = open(sys.argv[1], "r")
arqSaida = open(sys.argv[2], "w")
#arqEntrada = open("in.txt", "r")
#arqSaida = open("out.txt", "w")
operandos = Pilha()
while True:
expressao = (arqEntrada.readline()).split()
#print(expressao)
if (expressao) == []:
break
for operador in range(len(expressao)-1,-1,-1):
#Se for Vezes calcule
if (expressao[operador] == '*'):
op1 = int(operandos.desempilhar())
op2 = int(operandos.desempilhar())
#print("operando 1 : ",op1, "operando 2 : ", op2)
result = int(op1)* int(op2)
operandos.InserirNoFim(result)
#Se for Mais calcule
elif (expressao[operador] == '+'):
op1 = int(operandos.desempilhar())
op2 = int(operandos.desempilhar())
#print("operando 1 : ",op1, "operando 2 : ", op2,)
result = int(op1) + int(op2)
operandos.InserirNoFim(result)
#Se for Divisão calcule
elif (expressao[operador] == '/'):
op1 = int(operandos.desempilhar())
op2 = int(operandos.desempilhar())
#print("operando 1 : ",op1, "operando 2 : ", op2)
result = int(float(op1) / float(op2))
operandos.InserirNoFim(result)
# Se for Menos calcule
elif (expressao[operador] == '-'):
op1 = int(operandos.desempilhar())
op2 = int(operandos.desempilhar())
#print("operando 1 : ",op1, "operando 2 : ", op2)
result = int(op1) - int(op2)
operandos.InserirNoFim(result)
#Se não for nem das alternativas acima, então faça, adicione
#os operandos.
else:
operandos.InserirNoFim(expressao[operador])
resultado = operandos.desempilhar()
print("O resultaodo é => " , resultado)
arqSaida.write(str(resultado)+"\n")
arqEntrada.close()
arqSaida.close()
| true |
f9c26179c87704b3a4b6bdc5fc5a9b782f10ff29 | Python | mrtoss/G2_TLS_Inspired_Custom_Secure_network_communication_System | /src/RSA/mod_exp/modexp.py | UTF-8 | 1,033 | 3.671875 | 4 | [] | no_license | import math
import time
def exp_func(x, y, n):
exp = bin(y)
exp = '0b0000' + exp[2:]
print ("Binary value of y is:",exp)
print ("Bit\tResult")
if exp[2] == '1':
value = x
else:
value = 1
for i in range(3, len(exp)):
value = (value * value) % n
print (i-1,":\t",value,"(square)")
if(exp[i:i+1]=='1'):
value = (value*x) % n
print (i-1,":\t",value,"(multiply)")
print ("result is: " + str(value))
print ("hex value: " + str(hex(value)))
return value
def real_vale(m,e,n):
mod = (m**e)%n
print ("result should be: " + str(mod))
if __name__=='__main__':
start_time = time.time()
exp_func(2134314354651231,1423145646468123513547564,1514564564564135135)
end_time = time.time()
print("time using square and multiply: " + str(end_time - start_time))
# start_time = time.time()
# real_vale(314547,824186,3541563)
# end_time = time.time()
# print("time using built in functions: " + str(end_time - start_time))
| true |
e43fbf2e4e6fac72f5a18501f09a53c4dc74db07 | Python | ftorto/Bubulle-Norminette | /utils/error_handling.py | UTF-8 | 2,588 | 2.640625 | 3 | [] | no_license | import re
from utils.string_utils import colors
errors = []
args = None
class BuError():
def __init__(self, file_name, errid, level, line, message):
self.file_name = file_name
self.errid = errid
self.level = level
self.line = line
self.message = message
def print_error(self):
try:
highlight = "\33[44m "
if self.level == 1:
highlight = "\33[0;30;43m "
elif self.level == 2:
highlight = "\x1b[0;30;41m "
line_st = ""
if not isinstance(self.file_name, str):
self.file_name = self.file_name[0]
if len(self.file_name) > 19:
self.file_name = self.file_name[:15] + "..."
level_st = ""
err_spaces = 22 - len(self.file_name)
shown_err = ""
for i in range(1, err_spaces):
shown_err = shown_err + " "
shown_err = shown_err + str(self.errid)
line_spaces = 9 - len(self.errid)
if self.line != -1:
line_st = line_st + highlight + str(self.line)
level_spaces = 7 - len(str(self.line))
for i in range(1, level_spaces):
level_st = " " + level_st
if self.line == -1:
line_st = line_st + " "
if self.level == 0:
level_st = level_st + "\33[44m INFO " + colors.ENDC
elif self.level == 1:
level_st = level_st + "\33[0;30;43m MINOR " + colors.ENDC
else:
level_st = level_st + "\x1b[0;30;41m MAJOR " + colors.ENDC
for i in range(1, line_spaces):
line_st = " " + line_st
details_spaces = 7 - len(str(self.line))
color = '\033[37m' if len(errors) % 2 == 1 else '\033[0m'
message = color + self.message
details_st = message
for i in range(1, details_spaces):
details_st = " " + details_st
line_st = line_st + " \033[0m"
print("{0}{1}{2}{3}{4}".format(color + self.file_name, color + shown_err, color + line_st, level_st, details_st))
except Exception as e:
print(e)
class BuErrors:
def split_on_empty_lines(s):
blank_line_regex = r"(?:\r?\n){2,}"
return re.split(blank_line_regex, s.strip())
def print_error(file_name, line, level, errid, message):
error = BuError(file_name, errid, level, line, message)
errors.append(error)
error.print_error()
| true |
e7828bb1ea4c4ff70264a6f5da42cbd7322c9e3d | Python | dharmesh-coder/Full-Coding | /Extra/freq.py | UTF-8 | 203 | 2.9375 | 3 | [] | no_license | n=int(input())
l=list(map(int,input().strip().split()))[:n]
mydict={}
for i in l:
if i in mydict:
mydict[i]+=1
else:
mydict[i]=1
print(mydict)
Keymax = max(mydict, key=mydict.get) | true |
ffdaaccf23c7f45eb5d4e49d3bd0685b175ae683 | Python | zcutlip/pyonepassword | /tests/fixtures/expected_vault_data.py | UTF-8 | 2,066 | 2.71875 | 3 | [
"MIT"
] | permissive | import datetime
from typing import Dict
from ..test_support._datetime import fromisoformat_z
from .expected_data import ExpectedData
class ExpectedVault:
def __init__(self, vault_dict: Dict):
self._data = vault_dict
@property
def unique_id(self) -> str:
return self._data["id"]
@property
def description(self) -> str:
return self._data["description"]
@property
def name(self) -> str:
return self._data["name"]
@property
def created_at(self) -> datetime.datetime:
created_at = self._data["created_at"]
return fromisoformat_z(created_at)
@property
def updated_at(self) -> datetime.datetime:
updated_at = self._data["updated_at"]
return fromisoformat_z(updated_at)
@property
def returncode(self) -> int:
return self._data["returncode"]
@property
def type(self) -> str:
return self._data["type"]
@property
def item_count(self) -> int:
return self._data["items"]
class ExpectedVaultData:
def __init__(self):
expected_data = ExpectedData()
vault_data: Dict = expected_data.vault_data
self._data: Dict = vault_data
def data_for_vault(self, vault_identifier: str):
vault_dict = self._data[vault_identifier]
user = ExpectedVault(vault_dict)
return user
class ExpectedVaultListEntry:
def __init__(self, user_item: Dict) -> None:
self._data = user_item
@property
def unique_id(self) -> str:
return self._data["id"]
@property
def name(self) -> str:
return self._data["name"]
class ExpectedVaultListData:
def __init__(self) -> None:
expected_data = ExpectedData()
vault_list_data: Dict = expected_data.vault_list_data
self._data: Dict = vault_list_data
def data_for_key(self, data_key: str):
vault_list = self._data[data_key]
vault_list = [ExpectedVaultListEntry(entry_dict)
for entry_dict in vault_list]
return vault_list
| true |
a1740b28f4e8a33ea94fe3f8133dca39013722f0 | Python | dionysus/coding_challenge | /leetcode/035_SearchInsertPosition.py | UTF-8 | 1,379 | 3.5625 | 4 | [] | no_license | from typing import List
def searchInsert(nums: List[int], target: int) -> int:
"""
>>> searchInsert02([], 0)
0
>>> searchInsert02([1], 0)
0
>>> searchInsert02([0], 1)
1
>>> searchInsert([1,3,5,6], 5)
2
>>> searchInsert([1,3,5,6], 2)
1
>>> searchInsert([1,3,5,6], 7)
4
>>> searchInsert([1,3,5,6], 0)
0
"""
if nums == []:
return 0
for i in range(len(nums)):
if target <= nums[i]:
return i
return len(nums)
def searchInsert02(nums: List[int], target: int) -> int:
"""
>>> searchInsert02([], 0)
0
>>> searchInsert02([1], 0)
0
>>> searchInsert02([0], 1)
1
>>> searchInsert02([1,3,5,6], 5)
2
>>> searchInsert02([1,3,5,6], 2)
1
>>> searchInsert02([1,3,5,6], 7)
4
>>> searchInsert02([1,3,5,6], 0)
0
>>> searchInsert02([1,3,5], 5)
2
>>> searchInsert02([1,3,5], 2)
1
>>> searchInsert02([1,3,5], 7)
3
>>> searchInsert02([1,3,5], 0)
0
"""
if nums == []:
return 0
if len(nums) == 1:
if nums[0] < target:
return 1
return 0
mid = len(nums) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
return mid + searchInsert02(nums[mid:], target)
else:
return searchInsert02(nums[:mid], target)
| true |
5d2ff6bf44c62ba1f1317fdbcec93abe90583502 | Python | jimin0826/python-study | /Algorithm & Data Structure/sorting/selection_sort.py | UTF-8 | 944 | 4.21875 | 4 | [] | no_license | def swap(arr, i, j) :
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
def selectionSort(arr) :
for i in range(len(arr) - 1) :
min_num = arr[i] # initialization of minimum number
min_index = i # initialization of index of the minimum number
for j in range(i+1, len(arr)) :
if(arr[j] < min_num) :
min_num = arr[j]
min_index = j
if(i != min_index) :
swap(arr, i, min_index)
print(i, arr)
return arr
# TO DO : maximum을 select해서 오른쪽으로 보내는 방식으로 정렬하는 inverse_selectionSort 구현
def inverse_selectionSort(arr) :
for i in range(len(arr)):
max_num = arr[i]
max_index = i
for j in range(len(arr) + 1):
if(arr[j] > max_num):
max_num= arr[j]
max_index = j
if(i != max_index) :
swap(arr, i, max_index)
print(i, arr)
return arr
myarr = [6, 3, 2, 9, 10, 7, 1, 5]
myarr = selectionSort(myarr)
print(myarr) | true |
e2eb2a1567d2a0123e6657b9f86a078ef21d549d | Python | kklamm/MovieRecommendations | /get_data.py | UTF-8 | 732 | 2.75 | 3 | [] | no_license | import argparse
import pathlib
import urllib.request
import zipfile
URLS = {
"small": "http://files.grouplens.org/datasets/movielens/ml-100k.zip",
"medium": "http://files.grouplens.org/datasets/movielens/ml-1m.zip",
"large": "http://files.grouplens.org/datasets/movielens/ml-10m.zip"
}
def get_dataset():
parser = argparse.ArgumentParser()
parser.add_argument("size", choices=["small", "medium", "large"],
help="Dataset size")
args = parser.parse_args()
url = URLS[args.size]
fname = url.split("/")[-1]
if not pathlib.Path(fname).exists():
urllib.request.urlretrieve(url, fname)
with zipfile.ZipFile(fname) as zf:
zf.extractall()
get_dataset()
| true |
96516983bf38a4d73019cf7a748cc5111b55913e | Python | ebjarkason/randomTSVDLM | /src/CholeskyCMinv.py | UTF-8 | 957 | 2.53125 | 3 | [] | no_license | # Evaluate the Cholesky factors of the regularization matrix R = W^T W = CM^(-1):
# Coded by: Elvar K. Bjarkason (2017)
import scipy as sp
import numpy as np
import scipy.sparse as sparse
import evalRegularJacobian
import SaveLoadSparseCSRmatrix as slspCSR
from scipy.sparse import csr_matrix
from scipy.linalg import cholesky
# Evaluate the regularization Jacobian W:
print 'Evaluating regularization Jacobian'
NRadj = sp.load('numgridbal.npy')[7]
rJac = csr_matrix( evalRegularJacobian.regjac(NRadj) )
slspCSR.save_sparse_csr('regJac.npz',csr_matrix(rJac))
slspCSR.save_sparse_csr('regJacT.npz',csr_matrix(rJac.transpose()))
# Find SVD of CMinv:
print 'Finding CMinv'
CMinv = rJac.transpose().dot(rJac)
# Estimate upper triangular Cholesky matrix CMinv
# That is L^{-1}
print 'Estimating Cholesky of CMinv'
cholLinv = cholesky(CMinv.todense() , lower=False , overwrite_a=False , check_finite=True )
sp.save('cholLinv.npy',cholLinv)
| true |
f9d1189907f799778050a0758ba57c838cb0d07f | Python | alexloboo/BanckPrediction | /BankPrediction.py | UTF-8 | 14,685 | 2.578125 | 3 | [] | no_license | import tkinter as tk
from tkinter import Entry, LabelFrame
from tkinter import messagebox
from tkinter import ttk
from tkinter.constants import COMMAND, END, VERTICAL
#--------------------------generación modelo, predicción
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn import metrics
import numpy as np
import pickle
import time
class MyApp(tk.Tk):
def __init__(self, *args, **kwargs, ):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
# --------------------------- menu
menu = tk.Menu(container)
betting = tk.Menu(menu, tearoff=0)
menu.add_cascade(menu=betting, label="Opciones")
betting.add_command(label="Modelo Test",command=lambda: self.show_frame(Startpage))
betting.add_command(label="Predicción",command=lambda: self.show_frame(PagePrediction))
tk.Tk.config(self, menu=menu)
for F in (Startpage, PagePrediction):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
frame.config(bg="#3CB371")
self.show_frame(Startpage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class Startpage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
tt = tk.Label(self, text="BIENVENIDO A BANKPREDICTOR",bg="#3CB371",fg='white',font=('Helvetica', 18, 'bold')).place(x=170,y=35)
div = tk.Label(self, text="_______________________________________________________",bg="#3CB371",fg='black',font=('Helvetica', 15, 'bold')).place(x=50,y=110)
l1 = tk.Label(self, text="BANKPREDICTOR busca predecir un el cliente se suscribirá \n\na un depósito a plazo (term deposit).",bg="#3CB371",fg='black')
l1.place(x=190,y=110)
div2 = tk.Label(self, text="_______________________________________________________",bg="#3CB371",fg='black',font=('Helvetica', 15, 'bold')).place(x=50,y=400)
t1 = tk.Label(self, text="OBJETIVOS",bg="#3CB371",fg='black',font=('Helvetica', 12, 'bold')).place(x=312,y=190)
t2 = tk.Label(self, text=" Neuronas (x) ",bg="#3CB371",fg='black',font=('Helvetica', 8, 'italic')).place(x=320,y=280)
t3 = tk.Label(self, text="Se va generar un modelo con el menor error posible del rango 5 a 'x'. \nInsertar en el Entry la cantidad maxima de neuroas en el hidden layer a analizar",bg="#3CB371",fg='black').place(x=170,y=240)
#--------------------------- Entry
self.e_nhl = tk.Entry(self,bg="#d9dcd6",fg="#16425B", width=12)
self.e_nhl.place(x=320,y=300)
# -------------------------- generar modelo
act = tk.Button(self, text="Generar Modelo",height = 1, width = 14,bg="#fedc56",command= self.gModelo)
act.place(x=250,y=330)
# -------------------------- test
act = tk.Button(self, text="Crear Test",height = 1, width = 14,bg="#fedc56",command= self.gTest)
act.place(x=370,y=330)
#------------------------------------aviso legal
w = tk.Canvas(self, width=610, bg="#3CB371",height=100).place(x=50,y=460)
e = tk.Label(self, text="AVISO LEGAL",bg="#3CB371",fg='black',font=('Helvetica', 12, 'bold')).place(x=300,y=465)
sub1 = tk.Label(self, text=" Bankpredictor excluye cualquier responsabilidad por los daños y perjuicios de toda naturaleza que pudieran deberse\n a la mala utilización del Servicio. Por motivos de seguridad, Bankprediction no recopila\n ni almacena información confidencial de su empresa",bg="#3CB371",fg='black',font=('Helvetica', 8, 'italic')).place(x=60,y=500)
def gModelo(self):
ehl = self.e_nhl.get()
if (ehl == ""):
messagebox.showinfo("Estatus", "Se requiere insertar la cantidad máxima de neuronas (x), porque se va buscar el menor error de 5 a x neuronas en hidden layer")
else:
messagebox.showinfo("Estatus", "Generando el modelo con la menor catidad de error del rango de neuronas de hl.")
# leyendo el csv sacando los datos de X y Y
x = np.loadtxt('train.csv', delimiter=',', usecols=range(16))
y = np.loadtxt('train.csv', delimiter=',', usecols=(16, ))
# se construyen conjuntos de entrenamiento y prueba al azar
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.30, random_state=3)
eTupple =[]
# hlmax = int(input('Se buscará el menor error desde el hidden layer 5 hasta: '))
for hl in range(5,int(ehl)):
# se usa el conjunto de prueba para entrenar el clasificador
clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(hl,), random_state=1)
clf.fit(x_train, y_train)
# se usa el modelo entrenado para predecir las salidas sobre el conjunto de prueba
predicted = clf.predict(x_test)
# se calcula el error sobre el conjunto de prueba
error = 1 - accuracy_score(y_test, predicted)
eTupple.append((error,hl))
hl = min(eTupple)
# print(eTupple)
clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(hl[1],), random_state=1)
clf.fit(x_train, y_train)
#Resultados
predicted = clf.predict(x_test)
print('\n--------BANK-------\nErrores de diferentes cantidades de neuronas en hl (error,#hl): {}\n'.format((eTupple)))
messagebox.showinfo("Estatus", 'Error menor sobre el conjunto de prueba: {}, HL: {}'.format(hl[0],hl[1]))
messagebox.showinfo("Estatus", 'En la consola se mostrará el reporte de clasificación y la matrix de confusión')
print('Reporte de clasificación: \n',metrics.classification_report(y_test, predicted))
print('Matrix de confusión: \n',metrics.confusion_matrix(y_test, predicted))
# se guarda el modelo entrenado para uso posterior
filename = 'trained_modelBankMLP.sav'
pickle.dump(clf, open(filename, 'wb'))
self.e_nhl.delete(0,'end')
pass
def gTest(self):
messagebox.showinfo("Estatus", "Sacando el error del archivo Test con 4521 ejemplos de datos con el modelo")
x = np.loadtxt('test.csv', delimiter=',', usecols=range(16))
y = np.loadtxt('test.csv', delimiter=',', usecols=(16, ))
# se carga la red neuronal entrenada
clf = pickle.load(open('trained_modelBankMLP.sav', 'rb'))
# se usa el modelo entrenado para predecir las salidas
predicted = clf.predict(x)
# se calcula el error de prediccion
error = 1 - accuracy_score(y, predicted)
messagebox.showinfo("Estatus", 'Error de prediccion del test: {}'.format(error))
pass
class PagePrediction(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
ll = tk.Label(self, text="PREDICCIÓN",bg="#3CB371",fg='white',font=('Helvetica', 25, 'bold')).place(x=250,y=35)
div = tk.Label(self, text="_______________________________________________________",bg="#3CB371",fg='black',font=('Helvetica', 15, 'bold')).place(x=50,y=110)
div2 = tk.Label(self, text="_______________________________________________________",bg="#3CB371",fg='black',font=('Helvetica', 15, 'bold')).place(x=50,y=400)
sp_op = tk.Label(self, text="Edad",bg="#3CB371",fg='black').place(x=70,y=170)
sp_op = tk.Label(self, text="Trabajo",bg="#3CB371",fg='black').place(x=70,y=200)
sp_op = tk.Label(self, text="Estado Civil",bg="#3CB371",fg='black').place(x=70,y=230)
sp_op = tk.Label(self, text="Educación",bg="#3CB371",fg='black').place(x=70,y=260)
sp_op = tk.Label(self, text="¿Cuenta con tarjeta de credito?",bg="#3CB371",fg='black').place(x=70,y=290)
sp_op = tk.Label(self, text="Salario promedio anual",bg="#3CB371",fg='black').place(x=70,y=320)
sp_op = tk.Label(self, text="¿Tiene préstamo para vivienda?",bg="#3CB371",fg='black').place(x=70,y=350)
sp_op = tk.Label(self, text="¿Tiene préstamo personal?",bg="#3CB371",fg='black').place(x=70,y=380)
self.p1 = tk.Entry(self,bg="#d9dcd6",fg="#16425B", width=12)
self.p1.place(x=240,y=170)
self.p2 = tk.Entry(self,bg="#d9dcd6",fg="#16425B", width=12)
self.p2.place(x=240,y=200)
self.p3 = tk.Entry(self,bg="#d9dcd6",fg="#16425B", width=12)
self.p3.place(x=240,y=230)
self.p4 = tk.Entry(self,bg="#d9dcd6",fg="#16425B", width=12)
self.p4.place(x=240,y=260)
self.p5 = tk.Entry(self,bg="#d9dcd6",fg="#16425B", width=12)
self.p5.place(x=240,y=290)
self.p6 = tk.Entry(self,bg="#d9dcd6",fg="#16425B", width=12)
self.p6.place(x=240,y=320)
self.p7 = tk.Entry(self,bg="#d9dcd6",fg="#16425B", width=12)
self.p7.place(x=240,y=350)
self.p8 = tk.Entry(self,bg="#d9dcd6",fg="#16425B", width=12)
self.p8.place(x=240,y=380)
sp_op = tk.Label(self, text="Tipo de comunicación",bg="#3CB371",fg='black').place(x=380,y=170)
sp_op = tk.Label(self, text="Último dia de comunicación",bg="#3CB371",fg='black').place(x=380,y=200)
sp_op = tk.Label(self, text="Último mes de comunicación",bg="#3CB371",fg='black').place(x=380,y=230)
sp_op = tk.Label(self, text="Duración",bg="#3CB371",fg='black').place(x=380,y=260)
sp_op = tk.Label(self, text="Cantidad de campaña",bg="#3CB371",fg='black').place(x=380,y=290)
sp_op = tk.Label(self, text="Días desde la última com.",bg="#3CB371",fg='black').place(x=380,y=320)
sp_op = tk.Label(self, text="Cantidad de comunicación\n antes de la campaña",bg="#3CB371",fg='black').place(x=380,y=350)
sp_op = tk.Label(self, text="Resultado Marketing anterior",bg="#3CB371",fg='black').place(x=380,y=380)
self.p9 = tk.Entry(self,bg="#d9dcd6",fg="#16425B", width=12)
self.p9.place(x=555,y=170)
self.p10 = tk.Entry(self,bg="#d9dcd6",fg="#16425B", width=12)
self.p10.place(x=555,y=200)
self.p11 = tk.Entry(self,bg="#d9dcd6",fg="#16425B", width=12)
self.p11.place(x=555,y=230)
self.p12 = tk.Entry(self,bg="#d9dcd6",fg="#16425B", width=12)
self.p12.place(x=555,y=260)
self.p13 = tk.Entry(self,bg="#d9dcd6",fg="#16425B", width=12)
self.p13.place(x=555,y=290)
self.p14 = tk.Entry(self,bg="#d9dcd6",fg="#16425B", width=12)
self.p14.place(x=555,y=320)
self.p15 = tk.Entry(self,bg="#d9dcd6",fg="#16425B", width=12)
self.p15.place(x=555,y=350)
self.p16 = tk.Entry(self,bg="#d9dcd6",fg="#16425B", width=12)
self.p16.place(x=555,y=380)
e_pp = tk.Label(self, text="Predicción: ",bg="#3CB371",fg='black').place(x=70,y=440)
self.pp = tk.Entry(self,bg="#d9dcd6",fg="#16425B", width=12)
self.pp.place(x=240,y=440)
self.btn_p = tk.Button(self, text="Crear predicción",bg="#fedc56",
command=lambda: [self.pprediction()])
self.btn_p.place(x=534,y=440)
self.btn_p = tk.Button(self, text="Vaciar campos",bg="#CD5C5C",
command=lambda: [self.vc()])
self.btn_p.place(x=430,y=440)
pass
def pprediction(self):
p1 = self.p1.get()
p2 = self.p2.get()
p3 = self.p3.get()
p4 = self.p4.get()
p5 = self.p5.get()
p6 = self.p6.get()
p7 = self.p7.get()
p8 = self.p8.get()
p9 = self.p9.get()
p10 = self.p10.get()
p11 = self.p11.get()
p12 = self.p12.get()
p13 = self.p13.get()
p14 = self.p14.get()
p15 = self.p15.get()
p16 = self.p16.get()
if (p1 == "" or p2 == "" or p3 == "" or p4 == "" or p5 == "" or p6 == "" or p7 == "" or p8 == "" or p9 == "" or p10 == "" or p11 == "" or p12 == "" or p13 == "" or p14 == "" or p15 == "" or p16 == ""):
messagebox.showinfo("Estatus", "Se requiere llenar todos los campos para hacer una predicción")
else:
pred = []
pred.append(int(p1))
pred.append(int(p2))
pred.append(int(p3))
pred.append(int(p4))
pred.append(int(p5))
pred.append(int(p6))
pred.append(int(p7))
pred.append(int(p8))
pred.append(int(p9))
pred.append(int(p10))
pred.append(int(p11))
pred.append(int(p12))
pred.append(int(p13))
pred.append(int(p14))
pred.append(int(p15))
pred.append(int(p16))
x = np.loadtxt('test.csv', delimiter=',', usecols=range(16))
y = np.loadtxt('test.csv', delimiter=',', usecols=(16, ))
# se carga la red neuronal entrenada
clf = pickle.load(open('trained_modelBankMLP.sav', 'rb'))
# se usa el modelo entrenado para predecir las salidas
predicted = clf.predict(x)
#------------------predicción
Xnew = [pred]
ynew = clf.predict(Xnew)
ynew=ynew[0]
print("predicción: ",(ynew))
if ynew == 2:
self.pp.config(state=tk.NORMAL)
self.pp.insert(0, "NO")
else:
self.pp.config(state=tk.NORMAL)
self.pp.insert(0, "YES")
pass
def vc(self):
self.p1.delete(0,'end')
self.p2.delete(0,'end')
self.p3.delete(0,'end')
self.p4.delete(0,'end')
self.p5.delete(0,'end')
self.p6.delete(0,'end')
self.p7.delete(0,'end')
self.p8.delete(0,'end')
self.p9.delete(0,'end')
self.p10.delete(0,'end')
self.p11.delete(0,'end')
self.p12.delete(0,'end')
self.p13.delete(0,'end')
self.p14.delete(0,'end')
self.p15.delete(0,'end')
self.p16.delete(0,'end')
self.p16.delete(0,'end')
self.pp.delete(0,'end')
pass
#-------------configuración basica de la ventanda
app = MyApp()
app.geometry("720x600")
app.title(" BANKPREDICTOR")
app.resizable(False,False)
app.mainloop()
| true |
2423f8a264332dc5ea82c0a07fa31eeade44d150 | Python | carminelaluna/Leetcode-Solutions | /Medium/55-jump_game.py | UTF-8 | 1,089 | 2.765625 | 3 | [] | no_license | class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
neg = []
zero = []
pos = []
res = []
for n in nums:
if n < 0:
neg.append(n)
if n > 0:
pos.append(n)
if n == 0:
zero.append(n)
Positive = set(pos)
Negative = set(neg)
if zero:
for n in Positive:
if n*-1 in Negative:
res.append((-n,0,n))
if len(zero) >= 3:
res.append((0,0,0))
for i in range(len(pos)):
for j in range(i+1,len(pos)):
app = -1*(pos[i]+pos[j])
if app in Negative:
res.append(tuple(sorted([pos[i],pos[j],app])))
for i in range(len(neg)):
for j in range(i+1,len(neg)):
app = -1*(neg[i]+neg[j])
if app in Positive:
res.append(tuple(sorted([neg[i],neg[j],app])))
return list(set(res))
| true |
c9c47e5f2e8bdcf853f10b0f5ce1808cf32c92b9 | Python | sameer-sarmah/python-concepts | /core/exception_handling.py | UTF-8 | 519 | 3.5625 | 4 | [] | no_license | def divide(numerator,denominator):
try:
result = numerator/denominator
print(result)
except ValueError:
raise Exception('Only number accepted')
except ZeroDivisionError:
raise Exception('zero cant be the denominator')
except:
raise Exception('Either one of the argument is invalid')
finally:
print('we are done!')
try:
divide(10,0)
except Exception as error:
print(error)
try:
divide(10,"a")
except Exception as error:
print(error) | true |
a08c9e74651b4e99fe3da050289a46c927cb97e4 | Python | fc731097343/csmathHW04 | /LM.py | UTF-8 | 1,124 | 2.765625 | 3 | [] | no_license | import math
import numpy as np
import random
#find one extremum for function y = a *sin(b*x)
a = 2
b = np.matrix([1,2])
x = np.matrix([[3],[2.5]])
gk_norm = 100
k = 0
epson = 1e-13
mu = 0.1
fk = a * math.sin(b * x)
maxk = 1000
qk = 1
while(gk_norm > epson and k < maxk):
gk = a * b * math.cos(b * x)
Gk = -1 * a * b.T * b * math.sin(b * x)
gk_norm = gk * gk.T
[S, V, D] = np.linalg.svd(Gk+mu*np.eye(2), full_matrices=True)
while(0 in V):
mu = 4*mu
[S, V, D] = np.linalg.svd(Gk+mu*np.eye(2), full_matrices=True)
sk = np.array((np.linalg.inv(Gk+mu*np.eye(2)) * (-gk.T)).T)[0]
fk_old = fk
qk_old = qk
fk = a * math.sin(b * (np.matrix(sk).T + x))
qk = (fk + gk * np.matrix(sk).T + 0.5 * np.matrix(sk) * Gk * np.matrix(sk).T)[0,0]
rk = (fk-fk_old) / (qk - qk_old)
if rk < 0.25:
mu = 4 * mu
elif rk > 0.75:
mu = 0.5 * mu
if rk > 0:
x = x + np.matrix(sk).T
k += 1
print "iterations : %d, gk norm = %e, x = [%f, %f]" % (k,gk_norm,x[0,0],x[1,0])
print "extremum = 2 or -2, estimate = a*sin(b*x) = " , (a * math.sin(b * x))
| true |
d843a56eef66cbfe88b70cc505284dc22e507935 | Python | Xavi-phil/testgit | /sqlitetest.py | UTF-8 | 1,348 | 2.796875 | 3 | [] | no_license | # -*- coding:utf-8 -*-
#获取并打印google首页的html
import urllib.request
from bs4 import BeautifulSoup
import time
import json
from urllib.parse import urlparse
import os
def getdata(url='http://www.nufe.edu.cn'):
response=urllib.request.urlopen(url)
html=response.read()
print(html)
bs = BeautifulSoup(html,"html.parser")
print (bs)
return bs
def getinfo(bs):
la = bs.find_all('a')
print (len(la))
res = []
for a in la:
if len(a.text)>0 and a.get('href') and len(a.get('href'))>2:
print (a)
if a.get('href')[:4]=='http':
print (a.text,a.get('href'))
res.append(a.get('href'))
break
return res
def getallpages(url):
bs = getdata(url)
def getname(url):
dest_str = urlparse(url)
print (dest_str)
print (dest_str.netloc)
fname = dest_str.netloc+'.'+dest_str.path+'.json'
fname = fname.replace('/','_')
return fname
def save(url,res):
with open(getname(url),'w') as f:
json.dump(res,f)
def main():
url = 'http://www.nufe.edu.cn'
fname = getname(url)
if os.path.exists(fname):
with open(fname,'r') as f:
res=json.load(f)
print ('exists')
else:
bs = getdata()
res = getinfo(bs)
print (res)
save(url,res)
return
for r in res:
bs = getdata(r)
print (r)
res = getinfo(bs)
print (r,len(res))
save(r,res)
time.sleep(2)
break
if __name__ == '__main__':
main() | true |
a3f64c85ea1d03245f8338797b158f15ecad1b89 | Python | BussHsu/AI | /A*Search/Heuristics.py | UTF-8 | 1,157 | 3.328125 | 3 | [] | no_license | from state import *
class SimpleHeuristic:
def __init__(self,env):
self.env = env
self.goal = Point(env.end_x,env.end_y)
def heuristic(self, state, goal= None):
if goal is None:
goal = self.goal
start = state.pos
a=(goal-start).abs_sum()
b=abs(self.env.get_elevation(goal.x,goal.y) - self.env.get_elevation(start.x,start.y))
return a+b
class AltHeuristic:
def __init__(self,env):
self.env = env
self.goal = Point(env.end_x,env.end_y)
def heuristic(self, state, num_visited, goal= None):
if goal is None:
goal = self.goal
start = state.pos
a=(goal-start).abs_sum()
# my alternate heuristics can provide better virtical estimation when goal is higher than target
b=self.env.get_elevation(goal.x,goal.y) - self.env.get_elevation(start.x,start.y)
if b>=0:
max_remain_moves = self.env.width*self.env.height - num_visited
c=(b/max_remain_moves)**2*max_remain_moves
vertical_est = max(b,c)
else:
vertical_est = -b
return a+vertical_est
| true |
1f27132f62e59235ac034ea275fa9f785bd23475 | Python | vasana12/python_python_git | /python_Source/Test.Py/re02.py | UTF-8 | 338 | 2.90625 | 3 | [] | no_license | #-*-coding:utf8 -*-
import re
#이스케이프 문자 적용되지 않는 코드
r=bool(re.search('\\\\\w+','\lanana'))
print(r)
#이스케이프 문자 적용한 코드
r02=bool(re.search(r'\\\w+',r'\banana'))
print(r02)
print(re.search('\\\\\w+','\\banana'))
print(re.search('\\\\\w+','\\banana'))
print(re.search(r'\\\w+',r'\banana')) | true |
e05b20f600d0abf2c70993762879f8592f2c9650 | Python | xiaoyisha/cut | /cut1/main.py | UTF-8 | 1,423 | 2.515625 | 3 | [] | no_license | from PyQt5 import QtWidgets
from helloWorld import Ui_MainWindow
from PyQt5.QtWidgets import QFileDialog, QApplication
from cut import videoCut
import sys
from PyQt5.QtCore import *
class MyWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super(MyWindow, self).__init__()
self.setupUi(self)
self.ini_path = ''
def read(self):
self.ini_path, ok = QFileDialog.getOpenFileName(self, 'select file', '/home')
if ok:
self.textBrowser.append(self.ini_path)
self.textBrowser.append("Loaded Successfully...")
def start(self):
self.textBrowser.append("already start")
if self.ini_path == '':
self.textBrowser.append("You need to select a ini file")
else:
self.textBrowser.append("Cutting, please wait")
QApplication.processEvents()
videoCut(self, self.ini_path)
QApplication.processEvents()
self.textBrowser.append("Done!")
class WorkThread(QThread):
trigger = pyqtSignal()
def __int__(self):
super(WorkThread, self).__init__()
def run(self):
for i in range(2000000000):
pass
# 循环完毕后发出信号
self.trigger.emit()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
myshow = MyWindow()
myshow.show()
sys.exit(app.exec_()) | true |
1e85f08fabdec93ae08ce97acfefee2e2a463b29 | Python | virtualcell/test_suite | /report_generation/combine/omex_maker.py | UTF-8 | 4,499 | 2.734375 | 3 | [
"MIT"
] | permissive | """ OMEX archive generator
:Author: Akhil Marupilla <marupilla@mail.com>
:Date: 2020-11-23
:Copyright: 2020, UConn Health
:License: MIT
"""
from libcombine import *
from report_generation.utils.files_list import get_file_list
from report_generation.config import Config
from logzero import logger
class GenOmex:
"""Create and generate OMEX archives
"""
def __init__(self,
model_path=Config.MODEL_FILES_PATH,
sedml_path=Config.SEDML_DOC_PATH,
omex_path=Config.OMEX_FILE_PATH,
simulators = ['vcell','copasi']) -> None:
"""
Args:
model_path (`str`, optional): SBML model directory path. Defaults to Config.MODEL_FILES_PATH.
sedml_path (`str`, optional): SED-ML doc directory path. Defaults to Config.SEDML_DOC_PATH.
omex_path (`str`, optional): OMEX directory path. Defaults to Config.OMEX_FILE_PATH.
simulators (list, optional): list of supported simulators. Defaults to ['vcell','copasi'].
"""
self.sbml_files_list = get_file_list(model_path)
self.model_path = model_path
self.sedml_path = sedml_path
self.omex_path = omex_path
self.simulators = []
# TODO: Add more simulators once supported, this loops is a failsafe mechanism
for simulator in simulators:
if simulator in ['vcell', 'copasi']:
self.simulators.append(simulator)
# Getting sedml files list for each simulator
self.simulator_sedml_list_map = dict()
for simulator in self.simulators:
self.simulator_sedml_list_map[simulator] = get_file_list(os.path.join(sedml_path, simulator), 'sedml')
def create_omex_archive(self, sbml_name,
sedml_name,
simulator='vcell',
) -> bool:
"""Creates OMEX archive using libCombine library
Args:
sbml_name (`str`): SBML model name without file extension
sedml_name (`str`): SED-ML doc name without file extension
simulator (str, optional): VCell or COPASI . Defaults to 'vcell'.
"""
archive = CombineArchive()
is_model = archive.addFile(
os.path.join(self.model_path,
f"{sbml_name}.xml"), # target file name
sbml_name + '.xml', # filename
# look up identifier for SBML models
KnownFormats.lookupFormat("sbml"),
True # mark file as master
)
is_sedml = archive.addFile(
os.path.join(self.sedml_path, simulator,
f"{sedml_name}.sedml"), # target file name
sedml_name + '.sedml', # filename
# look up identifier for SBML models
KnownFormats.lookupFormat("sedml"),
False # mark file as master
)
# add metadata to the archive itself
description = OmexDescription()
description.setAbout("VCell Test Cases OMEX archives")
description.setDescription("Test VCell against COPASI")
description.setCreated(OmexDescription.getCurrentDateAndTime())
creator = VCard()
creator.setFamilyName("Marupilla")
creator.setGivenName("Gnaneswara")
creator.setEmail("marupilla@uchc.edu")
creator.setOrganization("UConn Health")
description.addCreator(creator)
archive.addMetadata(".", description)
# add metadata to the added file
location = f'./{sbml_name}'
description = OmexDescription()
description.setAbout(location)
description.setDescription("SBML model")
description.setCreated(OmexDescription.getCurrentDateAndTime())
archive.addMetadata(location, description)
# write the archive
out_file = os.path.join(
self.omex_path, simulator, f"{sbml_name.split('.')[0]}.omex")
is_archive_written = archive.writeToFile(out_file)
out_file_name = out_file.split('/')[-1]
logger.info(f'Archive created: {out_file_name}')
return is_model and is_sedml and is_archive_written
def gen_omex(self) -> None:
""" It generates OMEX archives to respective directory
"""
for simulator, files in self.simulator_sedml_list_map.items():
for sbml, sedml in zip(self.sbml_files_list, files):
self.create_omex_archive(sbml, sedml, simulator=simulator)
| true |
e14332b22d78fe35e8fe0442f25c082e483ea57a | Python | CrkJohn/MITx-6.00.2x | /UNIT2/ProblemSet2/Problem5RandomWalkRobot.py | UTF-8 | 527 | 3.203125 | 3 | [] | no_license | class RandomWalkRobot(Robot):
"""
A RandomWalkRobot is a robot with the "random walk" movement strategy: it
chooses a new direction at random at the end of each time-step.
"""
def updatePositionAndClean(self):
newPosition = self.getRobotPosition().getNewPosition(self.d,self.speed)
if self.room.isPositionInRoom(newPosition):
self.setRobotPosition(newPosition)
self.room.cleanTileAtPosition(newPosition)
self.setRobotDirection(random.randint(0,359))
| true |
a95b881e058ea943eddc53be85f8383b7f55e7ae | Python | bambreeze/sandbox | /python/hexdump.py | UTF-8 | 529 | 2.90625 | 3 | [] | no_license | #!/usr/bin/python
import os, sys, string
fname = sys.argv[1]
fname2 = sys.argv[1] + '.hex'
infile = file(fname, "rb")
outfile = file(fname2, "wb")
counter = 0;
while 1:
c = infile.read(1)
if not c:
break
#outfile.write("%02s" % hex(ord(c)))
if ord(c) <= 15:
outfile.write(("0x0"+hex(ord(c))[2:])[2:])
else:
outfile.write((hex(ord(c)))[2:])
counter += 1
if counter % 16 == 0:
outfile.write("\n")
else:
outfile.write(" ")
outfile.close()
infile.close()
| true |
7c9452d2468a17734a0ff8bfba44eedf19283dfa | Python | Kosov234/University | /Python/(updated)5(5).py | UTF-8 | 872 | 3.625 | 4 | [] | no_license | ##function that reads the file line by line, sorts them by size and writes them to another file
def function(inpu,outpu):
buffer = []
read = open(inpu,'r')
write = open(outpu,'w+')
for line in read:
buffer.append(line)
print(buffer)
i=0
indent = 1
while(i<len(buffer)-1):
while(indent<len(buffer)-i):
if (len(buffer[i])>=len(buffer[i+indent])):
#print (buffer[i]+buffer[i+indent]+'\n')
buffer[i],buffer[i+indent]=buffer[i+indent],buffer[i]
#print (buffer[i]+buffer[i+indent]+'\n')
indent+=1
i+=1
indent=1
print(buffer)
for element in buffer:
write.write(element)
read.close()
write.close()
def main():
inpu = 'data.txt'
outpu= 'final.txt'
function(inpu,outpu)
main()
| true |
ee04e4008cae41776e61eff579af1581cd8cf460 | Python | Frogboxe/pygame-pong | /render.py | UTF-8 | 689 | 3.046875 | 3 | [] | no_license |
from __future__ import annotations
from dataclasses import dataclass
import pygame
from vector import Vector
class Render:
"""
A pygame.Surface wrapped with a Vector to simply
allow textures to have an offset from their parent's
Vector pos. This is slotted.
.texture: pygame.Surface
.offset: Vector
"""
texture: pygame.Surface
offset: Vector
__slots__ = ["texture", "offset"]
def __init__(self, texture, offset):
self.texture, self.offset = texture, offset
def __repr__(self):
return f"{self.__class__.__qualname__}{self.texture, self.offset}"
def get_size(self):
return self.texture.get_size()
| true |
fd09333a1d50cd99cf64a4d1b2f6ddaf0cb6b87d | Python | Sarveshgithub/Python-DS-ALgo | /HackerRank/array-left-rotation.py | UTF-8 | 317 | 3.171875 | 3 | [] | no_license | def leftRotation(a, d):
# while d != 0:
# firstElement = a[0]
# for i in range(len(a) - 1):
# a[i] = a[i + 1]
# a[len(a) - 1] = firstElement
# d -= 1
return " ".join(a[d:] + a[:d])
d = int(input().split(" ")[1])
a = input().split(" ")
print(leftRotation(a, d))
| true |
d5040c09792448165fd82a0644e9f912fe4b92bf | Python | Jaime-alv/Blackjack | /blackjack.py | UTF-8 | 24,364 | 3.15625 | 3 | [
"Apache-2.0"
] | permissive | # ! python3
# Copyright 2021 Jaime Álvarez Fernández
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import random
import sys
Deck = {'Ace': 1, 'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, 'Nine': 9, 'Ten': 10,
'Jack': 10, 'Queen': 10, 'King': 10}
Suit = ['of Clubs', 'of Spades', 'of Hearts', 'of Diamonds']
Croupier = {'Name': 'MAX', 'Deck1': [], 'c_values1': [], 'Play': True, 'Ace': False, 'BJ': False, 'Score1': 0}
Template = {'Name': '', 'Money': 0, 'Bet': 0, 'Active': True, 'Play': True, 'BJ': False, 'Double': False, 'Ace': False,
'Score1': 0, 'insurance': False, 'half_bet': 0}
Players = {}
Config = {'Number of players': 0, 'Money': 100, 'Minimum_bet': 5, 'show': True, 'game': 0, 'deck_size': 0,
'max_deck': 0}
used_cards = {}
Croupier_names = ['Max', 'Rachel', 'Joey', 'Monica', 'Rob', 'Phoebe', 'John', 'Ian', 'Becca', 'Sam', 'Dean']
def sum_card_values(card_values):
# Total value of player's deck
sum_card = 0
for y in card_values:
sum_card += Deck.get(y)
return sum_card
def draw_cards(quantity, player, deck, deck_value):
# draw x cards and add to a dict so can keep track of each card == no repeated card
if Config['deck_size'] > (40 * Config['max_deck']):
left = (12 * Config['max_deck'])
print('\nOnly {} cards left in the deck!'.format(left))
print('Time for reshuffling!')
used_cards.clear()
Config['deck_size'] = 0
pause()
for x in range(quantity):
while True:
card_value = random.choice(list(Deck.keys()))
card = card_value + ' ' + random.choice(Suit)
if used_cards.get(card, 0) < Config['max_deck']: # If card doesn't exit .get(card) = 0
used_cards.setdefault(card, 0) # Create card in dict used_cards with value = 0
used_cards[card] += 1
player[deck].append(card)
player[deck_value].append(card_value)
Config['deck_size'] += 1
break
def greeting():
Croupier['Name'] = random.choice(Croupier_names)
print("Hello, my name is {}. I'll be your Croupier for this session.".format(Croupier['Name']))
print('Prizes are:')
print('- Blackjack pays 3 to 2.')
print('- Wins pays 1 to 1.')
print('- Insurance pays 2 to 1.')
config()
def config():
print('\nLet me ask you a few questions before we set the table.')
print('Do you prefer default rules, or would you rather have a custom set of rules?')
while True:
print('Default: Minimum bet = {}¢; Funds available to each player = {}¢; Croupier show one card.'.format(
Config['Minimum_bet'], Config['Money']))
configuration = input("d/c: ").lower()
if configuration not in ['d', 'c']:
print('Please, enter a valid input.')
elif configuration == 'd':
active_players()
else:
while True:
print('How much should minimum bet be?')
min_bet = input("#: ")
if min_bet.isdigit() and 0 < int(min_bet) < 100:
Config['Minimum_bet'] = int(min_bet)
break
while True:
print('How much funds should each player have?')
funds = input("#: ")
if funds.isdigit() and Config['Minimum_bet'] * 2 < int(funds):
Config['Money'] = int(funds)
break
while True:
print('Croupier should show you one card?')
show = input("y/n: ").lower()
if show == 'y':
Config['show'] = True
break
if show == 'n':
Config['show'] = False
break
active_players()
def active_players():
# Ask for number of players and creates its profiles. Since dict and list are mutable, hence they are referenced,
# need to create new ones for each one
print('How many players will be in this session?')
np = input("#: ")
if np.isdigit() and 1 <= int(np):
Config['Number of players'] = int(np)
Config['max_deck'] = Config['Number of players'] // 2
if Config['max_deck'] == 0:
Config['max_deck'] = 1
for x in range(1, Config['Number of players'] + 1):
new_player = 'Player ' + str(x)
template_new = dict(Template)
Players.setdefault(new_player, template_new)
Players[new_player].setdefault('Deck1', [])
Players[new_player].setdefault('c_values1', [])
print("There will be {} deck(s) in play".format(Config['max_deck']))
pause()
name()
else:
print('Enter a valid input.')
active_players()
def name():
# loop for naming each player
print('\nWelcome!')
for x in Players:
if Players[x]['Active']:
while True:
print("\nWhat's your name?")
Players[x]['Name'] = input(x + ": ")
if Players[x]['Name'] != '':
print('Nice to meet you {}!'.format(Players[x]['Name']))
Players[x]['Money'] = Config['Money']
break
else:
print('Please, tell me your name.')
print("We are ready. Let's start!")
betting()
def betting():
Config['game'] += 1
print('\nGame number {}'.format(Config['game']))
if Config['game'] % 10 == 0:
while True:
new_croupier = random.choice(Croupier_names)
if new_croupier != Croupier['Name']:
Croupier['Name'] = new_croupier
print('My turn is over. I introduce you to your new croupier, {}'.format(Croupier['Name']))
print('Have fun!\n')
break
print('\nBetting round')
for x in Players:
if Players[x]['Active']:
while True:
print('\nPlease, {}. Place a bet! You can go up to {}'.format(Players[x]['Name'], Players[x]['Money']))
bet = input("#: ")
if bet.isdigit() and Config['Minimum_bet'] <= int(bet) <= 500 and int(bet) <= Players[x]['Money']:
Players[x]['Bet'] = int(bet)
print("Your bet has been registered.")
break
first_round()
def first_round():
# round_number = 1 draw 2 cards and check for Blackjack, doubles, deck value
print('')
for x in Players:
if Players[x]['Active']:
draw_cards(2, Players[x], 'Deck1', 'c_values1')
draw_cards(2, Croupier, 'Deck1', 'c_values1')
for x in Players:
if Players[x]['Active']:
print(Players[x]['Name'] + ' these are your cards:')
print_deck(Players[x], 'Deck1')
if Config['show']:
print("The croupier, {}, has {} and one hidden card.".format(Croupier['Name'], Croupier['Deck1'][0]))
if Croupier['c_values1'][0] == 'Ace': # Croupier might have Blackjack
insurance()
else:
print("The croupier, {}, has two hidden cards.".format(Croupier['Name']))
pause()
for x in Players:
if Players[x]['Active'] and Players[x]['Play']: # Check for Blackjack first on both sides
player = Players[x]
cards = player['c_values1']
if (cards[0] == 'Ace' and Deck.get(cards[1]) == 10) or (Deck.get(cards[0]) == 10 and cards[1] == 'Ace'):
player['BJ'] = True
print("Congratulations {}! You have Blackjack!".format(player['Name']))
player['Play'] = False
pause()
cards = Croupier['c_values1']
if (cards[0] == 'Ace' and Deck.get(cards[1]) == 10) or (Deck.get(cards[0]) == 10 and cards[1] == 'Ace'):
Croupier['BJ'] = True
print('I have Blackjack!')
print_deck(Croupier, 'Deck1')
pause()
game_resolution() # if Croupier has blackjack, no need to look more
for x in Players:
if Players[x]['Active'] and Players[x]['Play']:
player = Players[x]
if player['c_values1'][0] == player['c_values1'][1] and sum_card_values(player['c_values1']) in [9, 10, 11]:
print(
'\n{}. It seems you can double your bet and split your hand. Be wary, you can only do one!'.format(
player['Name']))
if sum_card_values(player['c_values1']) in [9, 10, 11]:
double_bet(Players[x])
for n in Players:
player = Players[n]
if player['c_values1'][0] == player['c_values1'][1] and player['Play']: # and len(player['c_values1']) == 2
split_deck(player)
hit_stand(Players[n], 'Deck1', 'c_values1', 'Score1', 'Play')
if Players[n].get('Double'):
hit_stand(Players[n], 'Deck2', 'c_values2', 'Score2', 'Double')
croupier()
def insurance():
print('\n{} has an Ace as first card.'.format(Croupier['Name']))
for x in Players:
while True:
bet_half = Players[x]['Bet'] // 2
if Players[x]['Money'] >= (Players[x]['Bet'] + bet_half):
print("{} would you like adding insurance?".format(Players[x]['Name']))
print("It can go from 0, up to {}¢.".format(bet_half))
answer = input('#: ')
if answer.isdigit() and 0 <= int(answer) <= bet_half:
Players[x]['half_bet'] = int(answer)
print('Bet updated')
Players[x]['insurance'] = True
break
else:
print('Enter a valid input, between 0 and {}.'.format(bet_half))
elif Players[x]['Money'] > Players[x]['Bet']: # Player's bet + half will be over player's money
print("{} would you like adding insurance?".format(Players[x]['Name']))
rest = Players[x]['Money'] - Players[x]['Bet']
print("It can go from 0, up to {}¢.".format(rest))
answer = input('#: ')
if answer.isdigit() and 0 <= int(answer) <= rest:
Players[x]['half_bet'] = int(answer)
print('Bet updated')
Players[x]['insurance'] = True
break
else:
print('Enter a valid input, between 0 and {}.'.format(rest))
else:
print("{}. You don't have enough money for insurance.".format(Players[x]['Name']))
pause()
break
def pause():
input('Press Enter when you are ready\n')
def double_bet(player):
if player['Money'] >= (player['Bet'] * 2):
val = sum_card_values(player['c_values1'])
print('\n{}. Your hand is worth {}.'.format(player['Name'], val))
print_deck(player, 'Deck1')
print('You can double down your bet if you want. You will draw just one additional card if you agree.')
while True:
print('Do you want your bet to be {}?'.format((player['Bet'] * 2)))
yes_no = input("y/n: ")
if yes_no not in ['y', 'n']:
print('Please, enter a valid input.')
if yes_no == 'y':
player['Bet'] = player['Bet'] * 2
draw_cards(1, player, 'Deck1', 'c_values1')
print('Your cards are:')
print_deck(player, 'Deck1')
for card_v in player['c_values1']:
if card_v == 'Ace':
player['Ace'] = True
player['Play'] = False
val = sum_card_values(player['c_values1'])
if player['Ace'] and (val + 10) <= 21:
player['Score1'] = val + 10
print('Its value is: {}'.format(val + 10))
elif player['Ace'] and (val + 10) > 21:
player['Score1'] = val
print('Its value is: {}'.format(val))
else:
player['Score1'] = val
print('Its value is: {}'.format(val))
pause()
break
elif yes_no == 'n':
break
else:
print("{}. You don't have enough funds for doubling down your bet.".format(player['Name']))
pause()
def show_card_value(player, deck, deck_value):
print('Your cards are:')
print_deck(player, deck)
val = sum_card_values(player[deck_value])
for card_v in player[deck_value]:
if card_v == 'Ace':
player['Ace'] = True
if player['Ace'] and (val + 10) <= 21:
print('There is an Ace. Possible values are:')
print('Hard value: ' + str(val))
print('Soft value: ' + str(val + 10))
else:
print('Its value is: {}'.format(val))
def print_deck(player, deck):
for card in player[deck]:
print("- " + card)
def hit_stand(player, deck, deck_value, score, state):
while player['Active'] and player[state]:
val = sum_card_values(player[deck_value])
print('\n{}, it is your turn.'.format(player['Name']))
show_card_value(player, deck, deck_value)
if val > 21:
print("Bust! Your hand is over 21.")
player[score] = val
player[state] = False
pause()
elif val <= 21:
while True:
print("What do you want to do, hit or stand?")
choice = input("h/s: ")
if choice not in ['h', 's']:
print('Enter a valid input.')
if choice == 's':
player[state] = False
if player['Ace'] and (val + 10) <= 21:
player[score] = val + 10
elif player['Ace'] and (val + 10) > 21:
player[score] = val
else:
player[score] = val
break
elif choice == 'h':
draw_cards(1, player, deck, deck_value)
break
def split_deck(player):
if player['Money'] >= (player['Bet'] * 2):
print('\n{}, you can split your pair in two different hands.'.format(player['Name']))
show_card_value(player, 'Deck1', 'c_values1')
while True:
print('Do you want two hands to play with?')
answer_double = input("y/n: ").lower()
if answer_double not in ['y', 'n']:
print('Enter a valid input')
elif answer_double == 'y':
player['Double'] = True
player.setdefault('Deck2', [])
player.setdefault('c_values2', [])
player.setdefault('Score2', 0)
player['c_values2'].append(player['c_values1'][1])
player['c_values1'].pop()
player['Deck2'].append(player['Deck1'][1])
player['Deck1'].pop()
if player['c_values1'][0] == 'Ace':
print('Since your hand contains an Ace, you can only draw one additional card.')
print('{}. This is hand #1:'.format(player['Name']))
double_ace(player, 'Deck1', 'c_values1', 'Score1')
print('{}. This is hand #2:'.format(player['Name']))
double_ace(player, 'Deck2', 'c_values2', 'Score2')
player['Play'] = False
player['Double'] = False
pause()
break
elif answer_double == 'n':
break
else:
print("{}. You don't have enough funds for playing two hands.".format(player['Name']))
pause()
def double_ace(player, deck, value, score):
draw_cards(1, player, deck, value)
print_deck(player, deck)
val = sum_card_values(player[deck])
player[score] = val + 10
def croupier():
print("\nIt's my turn.")
while Croupier['Play']:
val = sum_card_values(Croupier['c_values1'])
for card_v in Croupier['c_values1']:
if card_v == 'Ace':
Croupier['Ace'] = True
print('My cards are:')
print_deck(Croupier, 'Deck1')
if Croupier['Ace'] and (val + 10) <= 21:
print('Hard value: {}'.format(val))
print('Soft value: {}\n'.format((val + 10)))
else:
print("Its values is: {}\n".format(val))
if val > 21:
print('Bust! My hand is over 21.')
Croupier['Play'] = False
Croupier['Score1'] = val
elif Croupier['Ace'] and 17 <= (val + 10) <= 21:
print('I stand.')
Croupier['Score1'] = val + 10
Croupier['Play'] = False
elif 17 <= val <= 21:
Croupier['Score1'] = val
print('I stand.')
Croupier['Play'] = False
elif Croupier['Ace'] and (val + 10) < 17:
print('I hit for another card.')
draw_cards(1, Croupier, 'Deck1', 'c_values1')
elif val < 17:
print('I hit for another card.')
draw_cards(1, Croupier, 'Deck1', 'c_values1')
pause()
game_resolution()
def game_resolution():
# Check if there is any blackjack, if not check for player closer to 21
for x in Players:
if Players[x]['Active']:
player = Players[x]
if Croupier['BJ']:
if player['BJ']:
print('{}. You recover your bet of {}¢.'.format(player['Name'], player['Bet']))
if player['insurance'] and 0 < player.get('half_bet', 0):
print("{} your insurance covers your bet and you win {}¢".format(player['Name'],
player['half_bet'] * 2))
player['Money'] += player['half_bet'] * 2
else:
player['Money'] -= player['Bet']
print("Sorry, {}. You lost {}¢.".format(player['Name'], player['Bet'], ))
else: # Croupier['BJ'] is False
if player['BJ']:
player['Money'] += (player['Bet'] * 3) // 2
print(
"{}. You got Blackjack and receive {}¢!".format(player['Name'], ((player['Bet'] * 3) // 2) +
player['Bet']))
if player['insurance'] and 0 < player.get('half_bet', 0):
print("{} You lost your insurance bet".format(player['Name']))
player['Money'] -= player['half_bet']
elif Croupier['Score1'] > 21 and player['BJ'] is False:
if player['Score1'] <= 21:
player['Money'] += player['Bet']
print('{}. You win! You get {}¢.'.format(player['Name'], player['Bet'] * 2))
if player.get('Score2', 22) <= 21:
player['Money'] += player['Bet']
print('{}. You win! You get {}¢ from hand #2.'.format(player['Name'], player['Bet'] * 2))
if player['Score1'] > 21:
player['Money'] -= player['Bet']
print("Sorry, {}. You lost {}¢.".format(player['Name'], player['Bet'], ))
if player.get('Score2', 0) > 21:
player['Money'] -= player['Bet']
print("Sorry, {}. You lost {}¢ from hand #2.".format(player['Name'], player['Bet'], ))
elif Croupier['Score1'] <= 21 and player['BJ'] is False:
if Croupier['Score1'] < player['Score1'] <= 21:
player['Money'] += player['Bet']
print('{}. You win! You get {}¢.'.format(player['Name'], player['Bet'] * 2))
if Croupier['Score1'] < player.get('Score2', 0) <= 21:
player['Money'] += player['Bet']
print('{}. You win! You get {}¢.'.format(player['Name'], player['Bet'] * 2))
if Croupier['Score1'] == player['Score1']:
print("{}. It's a tie, you recover your bet.".format(player['Name']))
if Croupier['Score1'] == player.get('Score2', 0):
print("{}. It's a tie, you recover your bet from hand #2.".format(player['Name']))
if player['Score1'] < Croupier['Score1']:
player['Money'] -= player['Bet']
print("Sorry, {}. You lost {}¢.".format(player['Name'], player['Bet'], ))
if player.get('Score2', Croupier['Score1']) < Croupier['Score1']:
player['Money'] -= player['Bet']
print("Sorry, {}. You lost {}¢ from hand #2.".format(player['Name'], player['Bet'], ))
if player['Score1'] > 21:
player['Money'] -= player['Bet']
print("Sorry, {}. You lost {}¢.".format(player['Name'], player['Bet'], ))
if player.get('Score2', 0) > 21:
player['Money'] -= player['Bet']
print("Sorry, {}. You lost {}¢ from hand #2.".format(player['Name'], player['Bet'], ))
pause()
goodbye()
def goodbye(): # Check funds available to players, ask if anyone would like to leave and reset the game
for x in Players:
if Players[x]['Money'] < Config['Minimum_bet'] and Players[x]['Active']:
print("Sorry, {}. You don't have enough funds to cover minimum bet. You only have left {}¢.".format(
Players[x]['Name'], Players[x]['Money']))
Players[x]['Active'] = False
print('Thanks for playing! Come back another day!')
inactive = 0
for n in Players: # Reset all markers to default
if Players[n]['Active'] is False:
inactive += 1
if inactive == Config['Number of players']:
print('No active players left. Thanks for playing!')
pause()
sys.exit()
print('If any player would like to withdraw, please type your name. Leave it blank and we will continue with the '
'next game.')
out = input("Player: ")
for x in range(1, Config['Number of players'] + 1):
new_player = 'Player ' + str(x)
if out == Players[new_player].get('Name') and Players[new_player]['Active']:
print('Farewell {}.'.format(Players[new_player]['Name']))
net = Players[new_player]['Money'] - Config['Money']
print('Net worth: {}¢'.format(net))
Players[new_player]['Active'] = False
goodbye()
if out == '':
for n in Players: # Reset all markers to default
if Players[n]['Active']: # If any player is Active, it will reset its markers
Players[n]['Deck1'].clear()
Players[n]['c_values1'].clear()
Players[n]['Play'] = True
Players[n]['Double'] = False
Players[n]['Ace'] = False
Players[n]['BJ'] = False
Players[n]['insurance'] = False
if Players[n].get('Deck2'):
Players[n].pop('Deck2')
Players[n].pop('c_values2')
Players[n].pop('Score2')
Croupier['Deck1'].clear()
Croupier['c_values1'].clear()
Croupier['Play'] = True
Croupier['BJ'] = False
Croupier['Ace'] = False
betting()
else:
print('No player found with the name {}.'.format(out))
goodbye()
if __name__ == "__main__":
greeting()
| true |
b371bf5571195643df0e9506e01ae47f8ebf34b2 | Python | shahf14/ClientToServer | /Server.py | UTF-8 | 671 | 2.59375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 24 21:12:33 2019
@author: shahf
"""
import socket
import logging
logging.basicConfig(filename = 'Server_Record.log',level=logging.INFO)
logger = logging.getLogger()
with socket.socket(socket.SOCK_DGRAM) as s:
s.bind(('127.0.0.1', 65432))
s.listen()
logger.info("The server successfully logged in and listened to clients ")
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
logging.info("Connection has been closed ") | true |
63de2c824ed67dd798dfc6163f09c5a627eab83d | Python | Nyuhnyash/lab | /oop/lab1/5.py | UTF-8 | 131 | 3.109375 | 3 | [] | no_license | def solve(x0: float):
x = x0
k = 0
while x < 0:
k += 1
x = 1 + x / k
return k
print(solve(-100))
| true |
b09d6c471a4f7938a0c994614387d3a92f165abd | Python | disclaimedication/Fortigate | /Fortigate_Blacklist_using_list.py | UTF-8 | 2,793 | 2.90625 | 3 | [] | no_license | # Importing modules
import paramiko
import datetime
import sys
def validate_ip(s):
a = s.split('.')
if len(a) != 4:
return False
for x in a:
if not x.isdigit():
return False
i = int(x)
if i < 0 or i > 255:
return False
return True
# input no of IP address and IP address from user
print '*************************************'
print ' BLOCK IP ADDRESSES VIA LIST '
print '*************************************'
while 1:
try:
path_of_file = raw_input('Enter filename with complete path:') #call for path of file to block IP addresses
break
except:
print 'You have entered incorrect path or filename, please try again'
IP=[] #it will store valid IP addresses to block
with open(path_of_file) as f:
content = f.readlines()
content = [x.strip() for x in content]
for value in content:
if validate_ip(value) is True:
IP.append(value)
else:
pass
#log the IP address just blocked
blacklist_file = open("blacklisted_IP.txt", "ab+")
for ip_elem in IP:
blacklist_file.write(str(ip_elem) + ' was added on ' + str(datetime.date.today()) + '\n')
blacklist_file.close()
# add string "_blacklist" to each IP address
string = '_SIEM_blacklist'
IP = [x + string for x in IP]
# setting parameters like host IP, username, passwd
HOST = "a.b.c.d" #Your IP address here
USER = "User" # Your Username here
PASS = "####" #Your password here
client1 = paramiko.SSHClient()
# Add missing client key
client1.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# connect to switch
client1.connect(HOST, username=USER, password=PASS)
print "SSH connection to firewall %s established" % HOST
# Create address object
for bl_ip_name in IP:
bl_ip = bl_ip_name.strip('_SIEM_blacklist')
command1 = 'config firewall address \n edit "' + str(bl_ip_name) + '_' + str(datetime.date.today()) + '"\nset subnet ' + str(bl_ip) + ' 255.255.255.255' + '\nnext\nend'
stdin, stdout, stderr = client1.exec_command(command1)
print ('firewall Object %s created..!!' %bl_ip)
#Add addresses to address groups
for bl_ip_name_02 in IP:
command2 = 'config firewall addrgrp \nedit "Blacklisted_ip" \nappend member ' + str(bl_ip_name_02) + '_' + str(datetime.date.today()) + '\nend'
stdin, stdout, stderr = client1.exec_command(command2)
# stdout = stdout.readlines()
bl_ip_02 = bl_ip_name_02.strip('_SIEM_blacklist')
print ('IP address %s has been added to blacklisted address group' %bl_ip_02)
# print (str(stdout))
client1.close()
print "Logged out of firewall %s" % HOST
print 'Task completed'
raw_input('PRESS ANY KEY TO CONTINUE...... .') | true |
8b30fd3b35ab2f8021d85ddc9bdc2206abaf8f52 | Python | PrajaktaSelukar/Sorting-Visualizer | /Tkinter_GUI/sortingAlgorithms.py | UTF-8 | 3,664 | 3.40625 | 3 | [] | no_license | #Tkinter is used for developing GUI
from tkinter import *
from tkinter import ttk
import random
#create a random new array
#root is the name of the main window object
root = Tk()
root.title('Sorting Algorithm Visualizer')
#setting the minimum size of the root window
root.minsize(900, 600)
root.config(bg='black')
#variables to select the algorithms
selected_algo = StringVar()
def drawData(data):
#delete the previous input
canvas.delete("all")
#set the canvas dimension
c_height = 380
c_width = 900
#set the bar graph dimension which will be changed bcoz of differebt dataset
x_width = c_width / (len(data) + 1)
offset = 30
spacing = 10
#normalize the data to match the bars acc to canvas height
#normalize would help to make bar heights of (1, 2, 4, 6) same as (10, 20, 40, 60)
normalizedData = [i / max(data) for i in data]
#for i, height in enumerate(data):
for i, height in enumerate(normalizedData):
#set top left corner
x0 = i * x_width + offset + spacing
#y0 = c_height - height
y0 = c_height - height * 340
#set bottom right corner
x1 = (i+1) * x_width + offset #this time without spacing
y1 = c_height
canvas.create_rectangle(x0, y0, x1, y1, fill="red")
canvas.create_text(x0+2, y0, anchor=SW, text=str(data[i]))
def Generate():
print("Algorithm Selected: " + selected_algo.get()) #get the value selected by user
#data = [10, 20, 40, 60]
#use try-except if the user do not put any value, insert default instead
try:
minValue = int(minEntry.get())
except:
minValue = 1
try:
maxValue = int(maxEntry.get())
except:
maxValue = 100
try:
size = int(sizeEntry.get())
except:
size = 10
#check for some bugs in advance
if minValue < 0:
minValue=0
if maxValue > 100:
maxValue=100
# size > 30 would clutter our space
if size > 30 or size < 3:
size = 25
if minValue > maxValue: minValue, maxValue = maxValue, minValue
data = [] #first create empty dataset
for _ in range(size):
data.append(random.randrange(minValue, maxValue+1))
drawData(data)
#frame / base layout
UI_frame = Frame(root, width=900, height=200, bg='grey')
UI_frame.grid(row=0, column=0, padx=10, pady=5)
canvas = Canvas(root, width=900, height=380, bg='white')
canvas.grid(row=1, column=0, padx=10, pady=5)
#User Interface Area
#Row=0
Label(UI_frame, text="Algorithm: ", bg='grey').grid(row=0, column=0, padx=5, pady=5, sticky=W)
algoMenu = ttk.Combobox(UI_frame, textvariable=selected_algo, values=['Bubble Sort', 'Quick Sort', 'Merge Sort'])
algoMenu.grid(row=0, column=1, padx=5, pady=5)
algoMenu.current(0) #Keep the first algo as the default
#Now put a button beside that
Button(UI_frame, text="Generate", command=Generate, bg='red').grid(row=0, column=2, padx=5, pady=5)
#Row=1
Label(UI_frame, text="Size: ", bg='grey').grid(row=1, column=0, padx=5, pady=5, sticky=W)
sizeEntry = Entry(UI_frame)
sizeEntry.grid(row=1, column=1, padx=5, pady=5)
Label(UI_frame, text="Min Value: ", bg='grey').grid(row=1, column=2, padx=5, pady=5, sticky=W)
minEntry = Entry(UI_frame)
minEntry.grid(row=1, column=3, padx=5, pady=5)
Label(UI_frame, text="Max Value: ", bg='grey').grid(row=1, column=4, padx=5, pady=5, sticky=W)
maxEntry = Entry(UI_frame)
maxEntry.grid(row=1, column=5, padx=5, pady=5)
root.mainloop() | true |
3c4e010d0162dfd33affc1695c0b2ecbf0f985a1 | Python | tlee8/soff | /03_occupation/LeeLee_leeT-leeB.py | UTF-8 | 2,155 | 3.828125 | 4 | [] | no_license | # Team LeeLee - Thomas Lee and Brian Lee
# SoftDev1 pd6
# K06 -- StI/O: DIvine Your Destiny!
# 2018-09-13
import random
d = {}
def read_jobs():
"""
Return a dictionary containing data on jobs in the US.
"""
with open("occupations.csv") as csv:
lines = csv.readlines()
for line in lines[1:-1]: # Only read lines containing job data
job_data = parse_csv_line(line)
job_name = job_data[0]
job_percentage = float(job_data[1])
d[job_name] = job_percentage
return d
def parse_csv_line(line):
"""
Given a string representing a line in csv, returns a list containing the line's values.
"""
list = []
prev_comma_idx = -1
outside_quotes = True
for i in range(len(line)):
char = line[i]
if char == "\"":
# Update whether we are inside quotes or not
outside_quotes = not outside_quotes
elif char == "\n" or (char == "," and outside_quotes):
value = line[prev_comma_idx + 1 : i]
value = value.replace("\"", "") # Remove quotes
list.append(value)
prev_comma_idx = i
return list
def weighted_random():
"""
Given a list of a dictionary containing keys and its weights,
return a random key from the dict where the results are weighted by the weights given.
"""
# Create seperate lists of of the dictionary's keys and values
k = list(d.keys())
v = list(d.values())
v = [i * 10 for i in v] # Multiply the percentages by 10 to get rid of decimals
r = random.randint(1,998) # The total sum of percentages is 99.8
b = 0
for c in range (len(d)):
b += v[c] # Increase the bound by the next percentage
if r <= b:
return k[c] # If the random number is within a specific range, it will return a specific job
# def test_weighted_random_job():
# job_dict = read_jobs()
# for i in range(100):
# random_job = weighted_random(job_dict)
# print(random_job)
#
# test_weighted_random_job()
print(read_jobs())
print("-" * 80)
print("Your random occupation is: " + weighted_random())
| true |
2a3711b40143eea2a6fb9495368cf17dbb86d63e | Python | heiheitian/MordenProgramDesign | /homework5/server.py | UTF-8 | 4,932 | 2.625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import socket
import thread
import random
import hashlib
import urllib, urlparse
import time
connLock = 0
def sendMsg(conn, msg):
while connLock == 1:
continue
connLock = 1
conn.send(msg)
connLock = 0
class player():
username = ''
token = ''
point = 0
guess = 0
conn = None
timeoutCount = 0
def __init__(self, username, conn):
self.username = username
self.token = hashlib.md5(str(random.randint(1, 2**256))).hexdigest()
self.point = 0
self.timeoutCount = 0
self.conn = conn
def getToken(self):
return self.token
def win(self):
self.point = self.point + 10
def lose(self):
self.point = self.point - 5
def timeout(self):
self.point = self.point - 10
self.timeoutCount = self.timeoutCount + 1
def submit(self, guess):
self.guess = guess
def getGuess(self):
return self.guess
def getUsername(self):
return self.username
def getPoint(self):
return self.point
def newRound(self, timeout, count):
req = {
'cmd': 'newround',
'count': count,
'timeout': str(timeout),
'yourpoint': str(self.getPoint())
}
sendMsg(conn, urllib.urlencode(req))
class game():
roundTime = 30
lastWinner = ''
lastLosers = []
lastG = 0
players = []
waiting = 0
roundCount = 0
def __init__(self):
self.roundTime = 5
def newRound(self):
print 'users:'
for i in self.players:
print i.getUsername(), i.point
#compute G
self.waiting = 0
i = [i.getGuess() for i in self.players]
if len(i) != 0:
self.lastG = sum(i)*0.618/len(i)
if len(self.players) > 0:
minabs = abs(self.players[0].getGuess() - self.lastG)
maxabs = abs(self.players[0].getGuess() - self.lastG)
#calculate winner point
for i in self.players[1:]:
#calculate timeouts
if i.getGuess == 0:
i.timeout()
if i.timeoutCount >= 3:
players.remove(i)
continue
if abs(i.getGuess() - self.lastG) < minabs:
self.lastWinner = i.getUsername()
minabs = abs(i.getGuess() - self.lastG)
if abs(i.getGuess() - self.lastG) > maxabs:
maxabs = abs(i.getGuess() - self.lastG)
i.guess = 0
#calculate losers
self.lastLosers = [i.getUsername for i in self.players if abs(i.getGuess() - self.lastG) == maxabs]
#add or minus points
self.roundCount = self.roundCount + 1
for i in self.players:
if i.getUsername() == self.lastWinner:
i.win()
elif i.getUsername() in self.lastLosers:
i.lose()
i.newRound(self.roundTime, self.roundCount)
self.waiting = 1
def newPlayer(self, username, conn):
t = player(username, conn)
self.players.append(t)
return t
def getPara(d, p):
if d.has_key(p):
return d[p][0]
return None
def dealWithClient(conn, g):
p = None
while True:
buf = conn.recv(1024)
d = urlparse.parse_qs(buf)
cmd = getPara(d, 'cmd')
if (cmd == 'newplayer'):
username = getPara(d, 'username')
p = g.newPlayer(username, conn)
req = {
'cmd': 'confirmplayer',
'username': username,
'token': p.getToken()
}
sendMsg(conn, urllib.urlencode(req))
elif (cmd == 'submit'):
point = int(getPara(d, 'point'))
print 'submit from ',p.getUsername(), 'point=',point
p.submit(point)
req = {
'cmd': 'confirmsubmit',
'point': point
}
sendMsg(conn, urllib.urlencode(req))
elif (cmd == 'query'):
yourpoint = str(p.getPoint())
lastg = str(g.lastG)
lastwinner = g.lastWinner
req = {
'cmd': 'confirmquery',
'yourpoint': yourpoint,
'lastg': lastg,
'lastwinner': lastwinner
}
sendMsg(conn, urllib.urlencode(req))
def timer(g):
while True:
timeout = g.roundTime
time.sleep(timeout)
g.newRound()
if __name__ == '__main__':
g = game()
thread.start_new_thread(timer, (g, ))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('localhost', 9210))
sock.listen(5)
while True:
conn,address = sock.accept()
print 'New client connected.'
thread.start_new_thread(dealWithClient, (conn, g)) | true |
ebb3a1096b741b3676f910cb5297ffbc1b525c6e | Python | LandenBrown/ProjectFrog | /Main.py | UTF-8 | 881 | 3.421875 | 3 | [] | no_license | #this is the start of something great
###initial planning:
#Frogs: 2
#Predators: 1
#
#
#
#
#
import time
versionNumber = "0.1"
sysQuit = "x"
print ("Welcome to the Prject Frog, Version", versionNumber)
print("Press X to randomize population and biome data...")
#Initial
p_input = input()
if p_input == "X" or p_input == "x":
print("Diving into the world of Project Frog")
time.sleep(0.4)
#####CREATE OBJECTS HERE
#Biome Details here
print("Biome Details:\n-Weather: X\n-Foliage: X\n-Foliage Density: X")
#Initial Frog count and details here
print("Frogs: X")
print("-Frog 1: X\n-Frog 2: X")
#Initial Predator count and details here
print("Predators: X")
print("-Predator 1: X\n-Predator 2: X")
else:
print("That is not a valid command, you are not worthy.")
while sysQuit != "q":
print("test")
sysQuit = input() | true |
9799d8cd924ef4621fdd49b4346983f4db048334 | Python | danieta/autonomous_systems | /ekf_localization/ros/src/ekf_localization_ros/ekf_localization_node.py | UTF-8 | 23,769 | 2.5625 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# ROS python api with lots of handy ROS functions
import rospy
# to be able to get the current frames and positions
import tf
# to be able to subcribe to laser scanner data
from sensor_msgs.msg import LaserScan
# to be able to publish Twist data (and move the robot)
from geometry_msgs.msg import Twist
# to be able to get the map
from nav_msgs.msg import OccupancyGrid
# to be able to obtain the map
from nav_msgs.srv import GetMap
# to be able to do matrix multiplications
import numpy as np
# to be able to do calculations for ray tracing
import math
#import matplotlib.pyplot as plt
from scipy import io as sio
# static_transform_publisher 0.0528600998223 0.0631977245212 -0.282212913036 -1.570796 0 0 map mocap
class ekf_localization(object):
'''
Node for localizing a robot in a map based on its odometry in tf and the scan of a laser range finder
'''
def __init__(self):
'''
Class constructor: will get executed at the moment
of object creation
'''
# register node in ROS network
rospy.init_node('ekf_node', anonymous=False)
# path for recording file and availability of ground truth
self.filepath = "/home/fichti/matfiles/ground_truth4.mat"
self.exist_truth = True
#variables for recording the positions and variances
self.beliefs = np.zeros((1, 3))
self.predictions = np.zeros((1, 3))
self.uncertainties = np.zeros((1, 3, 3))
if(self.exist_truth):
self.ground_truths = np.zeros((1, 3))
self.ground_truth = np.zeros((1, 3))
self.matches = [-1]
self.times = [0]
# number of rays used as observations (odd nr for center ray)
self.NUMBER_OF_OBSERVATIONS = 31
# position of the laser relative to base link
self.lrf_position = np.array([0.035, 0.0, 0.0])
# compute angles for predicted observations
min_angle = -math.pi/2
max_angle = -min_angle
angle_incr = (max_angle - min_angle)/(self.NUMBER_OF_OBSERVATIONS-1)
self.angles = np.arange(min_angle, max_angle+0.1, angle_incr)
# print message in terminal
rospy.loginfo('ekf localization started !')
# subscribe to pioneer laser scanner topic
if rospy.has_param('laser_topic'):
# retrieves the name of the LaserScan topic from the parameter server if it exists
rospy.Subscriber(rospy.get_param('laser_topic'), LaserScan, self.laser_callback)
else:
rospy.Subscriber("/scan", LaserScan, self.laser_callback)
# obtain currently published map
rospy.wait_for_service('static_map')
try:
getMap = rospy.ServiceProxy('static_map', GetMap)
get_map = getMap()
except rospy.ServiceException, e:
print "Service call failed: %s"%e
# transform map array into 2D map matrix
self.grid_map = np.reshape(get_map.map.data, (get_map.map.info.height, get_map.map.info.width))
self.grid_map = (self.grid_map).T
#plt.matshow(self.grid_map)
#plt.show()
origin = get_map.map.info.origin.position
self.map_origin = np.array([origin.x, origin.y, origin.z])
self.map_resolution = get_map.map.info.resolution
self.map_width = get_map.map.info.width
self.map_height = get_map.map.info.height
# create a tf listener and broadcaster instance to update tf and get positions
self.listener = tf.TransformListener()
self.br = tf.TransformBroadcaster()
# starting point for the odometry
self.listener.waitForTransform("odom", "base_link", rospy.Time(), rospy.Duration(20.0))
try:
now = rospy.Time.now()
self.listener.waitForTransform("odom", "base_link", now, rospy.Duration(20.0))
(trans,quat) = self.listener.lookupTransform("odom", "base_link", now)
except:
rospy.loginfo("No odom!!!")
trans = np.zeros((3,1))
quat = np.array([0, 0, 0, 1.0])
self.listener.waitForTransform("map", "pioneer", rospy.Time(), rospy.Duration(20.0))
if(self.exist_truth):
try:
(ground_truth_trans,ground_truth_quat) = self.listener.lookupTransform("map", "pioneer", rospy.Time(0))
except:
rospy.loginfo("No ground truth obtained!!!")
ground_truth_rot = tf.transformations.euler_from_quaternion(ground_truth_quat)
self.ground_truths[0, :] = np.array([ground_truth_trans[0], ground_truth_trans[1], ground_truth_rot[2]])
self.odom_bl_trans = np.array(trans)
self.odom_bl_rot = np.array(tf.transformations.euler_from_quaternion(quat))
#print(trans)
# defines the distance threshold below which the robot should relocalize
#print("check")
#print(rospy.has_param('distance_threshold'))
if rospy.has_param('~distance_threshold'):
self.distance_threshold = rospy.get_param('~distance_threshold')
else:
self.distance_threshold = 0.05
# defines the angle threshold below which the robot should relocalize
if rospy.has_param('~angle_threshold'):
self.angle_threshold = rospy.get_param('~angle_threshold')
else:
self.angle_threshold = 0.05
# iniitialize belief of where the robot is. transpose to get a column vector
#self.current_belief = np.array(rospy.get_param('belief', [0.0, 0.0, 0.0])).T
#self.current_belief = np.array([189*self.map_resolution, 180*self.map_resolution, 1.65])
#self.current_belief = np.array([362*self.map_resolution, 149*self.map_resolution, math.pi/2])
self.current_belief = np.array([0.0*self.map_resolution, 0.0*self.map_resolution, 0.0])
self.map_bl_trans = np.array([self.current_belief[0], self.current_belief[1], 0])
self.map_bl_rot = np.array([0, 0, self.current_belief[2]])
self.prediction_belief = self.current_belief
# NEED TO TWEAK THE DIAGONAL VALUES.
self.sigma = np.diag([1.0, 1.0, 0.3])
# Add starting belief as first position in recording
self.beliefs[0, :] = self.current_belief
self.predictions[0,:] = self.current_belief
self.uncertainties[0, :, :] = self.sigma
self.R = np.array([0.05, 0.05, 0.05])
self.q_obs = np.array([0.03,0.0])
self.q_pred = np.array([math.sqrt(2)*self.map_resolution,0.01])
self.gamma = 2.0
self.match_fail_counter = 1
self.map_odom_rot = np.array([0.0, 0.0, self.correct_angle(self.current_belief[2]-self.odom_bl_rot[2])])
self.map_odom_rot_prediction = np.array([0.0, 0.0, self.correct_angle(self.current_belief[2]-self.odom_bl_rot[2])])
self.map_odom_trans = self.map_bl_trans - self.rotate(self.odom_bl_trans, self.map_odom_rot[2])
self.map_odom_quat = tf.transformations.quaternion_from_euler(0.0, 0.0, self.map_odom_rot[2])
# publish the starting transformation between map and odom frame
self.br.sendTransform((self.map_odom_trans[0], self.map_odom_trans[1], self.map_odom_trans[2]),
(self.map_odom_quat[0], self.map_odom_quat[1], self.map_odom_quat[2], self.map_odom_quat[3]),
rospy.Time.now(),
"odom",
"map")
def laser_callback(self, msg):
min_angle = -math.pi/2
max_angle = -min_angle
# calculating the indices of the first and last used ray in the laser scan message
min_index = int((min_angle-msg.angle_min)/msg.angle_increment)
max_index = int((max_angle-msg.angle_min)/msg.angle_increment)
increment = (max_index - min_index)/(self.NUMBER_OF_OBSERVATIONS-1)
indices = np.array(range(min_index, max_index+1, increment)).astype(int)
angles = msg.angle_min + indices*msg.angle_increment
distances = np.array(msg.ranges)[indices]
# Remove distances that are NaN, and the corresponding angles
indices = np.isfinite(distances)
angles = angles[indices]
distances = distances[indices]
self.observation = [val for pair in zip(distances, angles) for val in pair]
def rotate(self, trans, theta):
"""
function for turning a translation vector by the angle theta
"""
theta = self.correct_angle(theta)
rot_mat = np.array([[math.cos(theta), -math.sin(theta), 0], [math.sin(theta), math.cos(theta), 0], [0, 0, 1]])
return rot_mat.dot(trans)
def correct_angle(self, angle):
"""
function for keeping an angle in the range of -pi to pi
"""
while angle > math.pi:
angle = angle - 2*math.pi
while angle < -math.pi:
angle = angle + 2*math.pi
return angle
def kalman_filter(self):
start = rospy.get_time()
# get the odometry
self.listener.waitForTransform("odom", "base_link", rospy.Time(), rospy.Duration(20.0))
try:
now = rospy.Time.now()
self.listener.waitForTransform("odom", "base_link", now, rospy.Duration(10.0))
(current_trans,current_quat) = self.listener.lookupTransform("odom", "base_link", now)
except:
rospy.loginfo("No map!!!")
current_trans = (0.0, 0.0, 0.0)
current_quat = (0.0, 0.0, 0.0, 1.0)
z = self.observation
if(self.exist_truth):
try:
(ground_truth_trans,ground_truth_quat) = self.listener.lookupTransform("map", "pioneer", rospy.Time(0))
except:
rospy.loginfo("No ground truth obtained!!!")
ground_truth_rot = tf.transformations.euler_from_quaternion(ground_truth_quat)
self.ground_truth = np.array([ground_truth_trans[0], ground_truth_trans[1], ground_truth_rot[2]])
current_trans = np.array(current_trans)
current_rot = np.array(tf.transformations.euler_from_quaternion(current_quat))
delta_trans_odom = current_trans - self.odom_bl_trans
delta_trans_map = self.rotate(delta_trans_odom, self.map_odom_rot[2])
delta_trans_map_prediction = self.rotate(delta_trans_odom, self.map_odom_rot_prediction[2])
delta_rot = np.array([0.0, 0.0, self.correct_angle(current_rot[2] - self.odom_bl_rot[2])])
# The distance in x and y moved, and the rotation about z
delta_odom = np.array([delta_trans_map[0], delta_trans_map[1], delta_rot[2]])
delta_odom_prediction = np.array([delta_trans_map_prediction[0], delta_trans_map_prediction[1], delta_rot[2]])
#print delta_odom
#dont do anything if the distance traveled and angle rotated is too small
if ((np.sqrt(delta_odom[0]**2 + delta_odom[1]**2)<self.distance_threshold) and (abs(delta_odom[2]) < self.angle_threshold) and (self.match_fail_counter<1)):
#print("too small change. do not update odometry")
return
# delta_D_k*cos(theta_k) is the 0th element of the translation given by odometry. delta_D_k*sin(theta_k) is the 1st.
G = np.matrix([ [1, 0, -delta_odom[1]],
[0, 1, delta_odom[0]],
[0, 0, 1] ])
#PREDICT
mu_predicted = self.current_belief + delta_odom
mu_predicted[2] = self.correct_angle(mu_predicted[2])
sigma_predicted = np.matmul( G, np.matmul(self.sigma, G.T) ) + np.diag((delta_odom * self.R)**2) #NEED TO DEFINE R, COVARIANCE OF THE STATE TRANSITION NOISE
self.prediction_belief = self.prediction_belief + delta_odom_prediction
self.prediction_belief[2] = self.correct_angle(self.prediction_belief[2])
laser_pose = mu_predicted + self.rotate(self.lrf_position, mu_predicted[2])
# now using the predicted measurement as pose, but should actually be lasers position, not the robots position
z_expected = self.z_exp(self.grid_map, laser_pose-self.map_origin, z[1::2])
# UPDATE/CORRECT
H_rays = np.zeros((len(z)/2,2,3))
S_rays = np.zeros((len(z)/2, 2, 2))
Q_unfiltered = []
for i in range(len(z)/2):
d_n = z[2*i]
theta_n = self.correct_angle(mu_predicted[2] + z[2*i+1])
H_rays[i] = np.array([[-np.cos(theta_n), -np.sin(theta_n), 0],
[np.sin(theta_n) / d_n, -np.cos(theta_n) / d_n, -1]])
Q_obs = self.q_obs*d_n
if abs(Q_obs[0]) < 0.03:
Q_obs[0] = 0.03
Q_ray = (self.q_pred + Q_obs)**2
Q_unfiltered = np.hstack((Q_unfiltered, Q_ray))
S_rays[i] = np.matmul(H_rays[i], np.matmul(sigma_predicted, H_rays[i].T)) + np.diag(Q_ray)
indices_of_matches = []
v_unfiltered = z-z_expected
#print "Product"
#MATCHING (in the middle of update step in order to remove non-matching rays)
for i in range(len(z)/2):
S_inv = np.linalg.inv(S_rays[i])
v_ray = v_unfiltered[2*i:2*i+2].T
product = v_ray.dot( S_inv.dot(v_ray.T))
#print product
if (product) < self.gamma:
#print("gut")
indices_of_matches.append(i)
#else:
#print("nicht gut")
#print("successful rays")
#print( float(len(indices_of_matches))/self.NUMBER_OF_OBSERVATIONS )
# if the observation is not good at all, stop executing
if len(indices_of_matches) < self.NUMBER_OF_OBSERVATIONS/3:
print "FAILED MATCH"
self.current_belief = mu_predicted
self.sigma = sigma_predicted
self.map_bl_trans = np.array([self.current_belief[0], self.current_belief[1], 0])
self.map_bl_rot = np.array([0, 0, self.current_belief[2]])
self.odom_bl_trans = current_trans
self.odom_bl_rot = current_rot
self.match_fail_counter = self.match_fail_counter + 1
if self.match_fail_counter < 4:
self.sigma = self.sigma*self.match_fail_counter
else:
self.sigma = self.sigma * 2
if self.match_fail_counter > 10:
print "KIDNAPPED"
self.sigma = np.diag([100, 100, math.pi*2])
# Update trajectory tracking
self.beliefs = np.append(self.beliefs, np.expand_dims(self.current_belief, axis=0), axis=0)
self.predictions = np.append(self.predictions, np.expand_dims(self.prediction_belief, axis=0), axis=0)
self.uncertainties = np.append(self.uncertainties, np.expand_dims(self.sigma, axis=0), axis=0)
if(self.exist_truth):
self.ground_truths = np.append(self.ground_truths, np.expand_dims(self.ground_truth, axis=0), axis=0)
self.matches.append(0)
self.times.append(rospy.get_time()-start)
return
else:
print "OK MATCHING"
self.match_fail_counter = 0
v = []
Q_expanded = []
#filter out the bad matches
for i in range(len(indices_of_matches)):
v.append(v_unfiltered[2*indices_of_matches[i]])
v.append(v_unfiltered[2*indices_of_matches[i]+1])
Q_expanded.append(Q_unfiltered[2*indices_of_matches[i]])
Q_expanded.append(Q_unfiltered[2*indices_of_matches[i]+1])
H = H_rays[indices_of_matches]
H = H.reshape(-1, H.shape[-1])
#UPDATE
# expand Q so we have the 2x2 Q-matrix on the diagonal
#Q_expanded = linalg.block_diag(* [self.Q]*(len(v)/2))
# Measurement prediction covariance
S = np.matmul(H, np.matmul(sigma_predicted, H.T)) + np.diag(Q_expanded)
# Kalman gain
K = np.matmul(sigma_predicted, np.matmul(H.T, np.linalg.inv(S)))
delta_update = np.array(np.matmul(K, v)).flatten()
delta_update[2] = -delta_update[2]
# new_belief
#new_belief = mu_predicted + np.array(np.matmul(K, v)).flatten()
new_belief = mu_predicted + delta_update
#update
self.current_belief = new_belief
self.current_belief[2] = self.correct_angle(self.current_belief[2])
self.map_bl_trans = np.array([self.current_belief[0], self.current_belief[1], 0])
self.map_bl_rot = np.array([0, 0, self.current_belief[2]])
self.odom_bl_trans = current_trans
self.odom_bl_rot = current_rot
self.sigma = sigma_predicted - np.matmul( K, np.matmul( S, K.T) )
if np.sum(np.sign(self.sigma.diagonal())-1) != 0:
self.sigma[0, 0] = abs(self.sigma[0, 0])
self.sigma[1, 1] = abs(self.sigma[1, 1])
self.sigma[2, 2] = abs(self.sigma[2, 2])
self.map_odom_rot[2] = self.correct_angle(self.map_bl_rot[2] - self.odom_bl_rot[2])
self.map_odom_trans = self.map_bl_trans - self.rotate(self.odom_bl_trans, self.map_odom_rot[2])
self.map_odom_quat = tf.transformations.quaternion_from_euler(0.0, 0.0, self.map_odom_rot[2])
rospy.loginfo("current belief")
rospy.loginfo(str(self.current_belief))
rospy.loginfo("sigma")
rospy.loginfo(str(self.sigma.diagonal()))
# Update position tracking
self.beliefs = np.append(self.beliefs, np.expand_dims(self.current_belief, axis=0), axis=0)
self.predictions = np.append(self.predictions, np.expand_dims(self.prediction_belief, axis=0), axis=0)
self.uncertainties = np.append(self.uncertainties, np.expand_dims(self.sigma, axis=0), axis=0)
if(self.exist_truth):
self.ground_truths = np.append(self.ground_truths, np.expand_dims(self.ground_truth, axis=0), axis=0)
self.matches.append(1)
self.times.append(rospy.get_time()-start)
# returns the measurement we expect to see when we're in a given state
# here we have to do the ray tracing
def z_exp(self, map, pose, angles):
z_expected = np.zeros(2*len(angles)) #measurement contains distance, angle, distance, angle... must then have 2 times as many elements as 'angles' does
for i, theta in enumerate(angles):
z_expected[2*i] = self.ray_trace(map, pose, theta, 50.0)
z_expected[2*i+1] = theta
return z_expected
def ray_trace(self, map, pose, angle, threshold):
#computes ray_angle from robot_angle and relative_angle
ray_angle = pose[2] + angle
#brings the ray_angle in the range 0-2pi
ray_angle = ray_angle%(2*math.pi)
if ray_angle < 0:
ray_angle = 2 * math.pi - ray_angle
# finds tan and cotan of the ray angle
tan = math.tan(ray_angle)
if tan != 0:
cotan = 1/tan
map_height = map.shape[0]
map_width = map.shape[1]
start_pixel = [int(round(pose[0]/self.map_resolution)), int(round(pose[1]/self.map_resolution))]
curr_pixel = [int(round(pose[0]/self.map_resolution)), int(round(pose[1]/self.map_resolution))]
# DEBUG: map.flags.writeable = True
#DEBUG: print("ray_angle:", ray_angle/math.pi*180,"tan:", tan)
# image.flags.writeable = True
#while we are within the image boundaries
while curr_pixel[0] < map_height-1 and curr_pixel[0] >= 0 and curr_pixel[1] < map_width-1 and curr_pixel[1] >= 0:
#if the inspected pixel is darker than a threshold returns the position of the pixel (collision detected)
if map[int(round(curr_pixel[0])), int(round(curr_pixel[1]))] > threshold or map[int(round(curr_pixel[0])), int(round(curr_pixel[1]))] == -1:
#print(self.map_resolution*math.sqrt((curr_pixel[0]-start_pixel[0])**2 + (curr_pixel[1]-start_pixel[1])**2))
return self.map_resolution*math.sqrt((curr_pixel[0]-start_pixel[0])**2 + (curr_pixel[1]-start_pixel[1])**2) #euclidean distance
#map[map_height-round(curr_pixel[1])-1,round(curr_pixel[0])] = 0 # sets the inspected pixel to black (for debugging)
#finds the next pixel to inspect:
#if ray_angle is between -45 and +45 (included)
if (ray_angle >= math.pi*7/4 or ray_angle <= math.pi/4):
curr_pixel[0] += 1 #increment x
curr_pixel[1] += tan #increment y according to ray_angle
#if ray_angle is between +45 and +135 (not included)
elif (ray_angle > math.pi/4 and ray_angle < math.pi*3/4):
curr_pixel[0] += cotan
curr_pixel[1] += 1 #increment y
#if ray_angle is between 135 and 225 degrees (included)
elif (ray_angle >= math.pi*3/4 and ray_angle <= math.pi*5/4):
curr_pixel[0] -= 1
curr_pixel[1] -= tan
#if ray_angle is between 225 and 315 degrees (not included)
elif (ray_angle > math.pi*5/4 and ray_angle < math.pi*7/4):
curr_pixel[0] -= cotan
curr_pixel[1] -= 1
else:
return None
return None
def run_behavior(self):
rospy.loginfo('Working')
while not rospy.is_shutdown():
self.kalman_filter()
# publish transform of odom frame in map frame to tf based on EKF results
self.br.sendTransform((self.map_odom_trans[0], self.map_odom_trans[1], self.map_odom_trans[2]),
(self.map_odom_quat[0], self.map_odom_quat[1], self.map_odom_quat[2], self.map_odom_quat[3]),
rospy.Time.now(),
"odom",
"map")
self.br.sendTransform((self.prediction_belief[0], self.prediction_belief[1], 0.0), tf.transformations.quaternion_from_euler(0.0, 0.0, self.prediction_belief[2]),
rospy.Time.now(), "prediction", "map")
self.br.sendTransform((self.current_belief[0], self.current_belief[1], 0.0), tf.transformations.quaternion_from_euler(0.0, 0.0, self.current_belief[2]),
rospy.Time.now(), "belief", "map")
# sleep for a small amount of time
# rospy.sleep(0.1)
if self.exist_truth:
sio.savemat(self.filepath, dict([('beliefs', self.beliefs), ('predictions', self.predictions), ('sigmas', self.uncertainties), ('ground_truth', self.ground_truths),
('times', self.times), ('matches', self.matches), ('num_of_observations', self.NUMBER_OF_OBSERVATIONS),
('map_origin', self.map_origin), ('map_resolution', self.map_resolution)]))
else:
sio.savemat(self.filepath, dict([('beliefs', self.beliefs), ('predictions', self.predictions), ('sigmas', self.uncertainties),
('times', self.times), ('matches', self.matches), ('num_of_observations', self.NUMBER_OF_OBSERVATIONS),
('map_origin', self.map_origin), ('map_resolution', self.map_resolution)]))
if __name__ == '__main__':
# create object of the class ekf_localization (constructor will get executed!)
my_object = ekf_localization()
# call run_behavior method of class EKF_localization
my_object.run_behavior()
| true |
61c2b9ba73d71d42c6b9bd54a55d8f40f3eddc9a | Python | RenzoPL23/TF_Complejidad | /1°algoritmo.py | UTF-8 | 1,744 | 2.8125 | 3 | [] | no_license | import math as mt
import heapq as hq
def asd(x):
num = x.split(',')
return int(num[0]),float(num[1])
def LeerListAP(filename):
G=[]
file= open(filename,'r',encoding='utf8')
for line in file:
G.append([asd(x) for x in line.split( )])
return G
def prim(G,s,t):
n = len(G)
dist = [mt.inf]*n
path = [-1]*n
visited = [False]*n
dist[s]=0
q = []
hq.heappush(q, (0, s))
dist[0] = 0
while len(q) > 0:
_, u = hq.heappop(q)
if visited[u]: continue
visited[u] = True
if u ==t: break
for v, w in G[u]:
if not visited[v] and w < dist[v]:
dist[v] = w
path[v] = u
hq.heappush(q, (w, v))
return path, dist
def CrearTxt(filename,p):
file = open(filename,"w")
n = len(p)
for i in range(n):
file.write(str(p[i]))
file.write('\n')
file.close()
def combinacion(c1,c2):
for i in range(len(c1)):
if c1[i] == -1:
c1[i] = c2[i]
return c1
#DS_CDist_10_cercanos.csv 1678
#DS_CProv_10_cercanos.csv 171
#DS_CReg_10_cercanos.csv 25
#LAP2.txt 145224
def Camino(filename,s,t):
G = LeerListAP(filename)
p,d=prim(G,s,t-1)
lenG = len(G)
indexaux=t-1
camino=[-1]*lenG
while(True):
camino[indexaux]=p[indexaux]
indexaux=p[indexaux]
if p[indexaux]==-1:
break
return camino
#camino = Camino('LAP2.txt',0,145224)
camino1 = Camino('DS_CReg_10_cercanos.csv',15,25)
camino2 = Camino('DS_CReg_10_cercanos.csv',0,15+1)
ca=combinacion(camino1,camino2)
#CDis.txt
#CProv.txt
#CReg.txt
#CResto.txt
CrearTxt('CReg1.txt',ca) | true |
27c010237574a5b7837077312addd644d3aeecb9 | Python | Nexz/easybackup | /easy-backup.py | UTF-8 | 2,601 | 2.9375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/python3
# Norbert van Adrichem / 2019 / www.norbert.in
import argparse
import shutil
import os
import time
version = "0.1"
parser = argparse.ArgumentParser()
current_backup = ""
current_folder = ""
def parser_setup():
parser.add_argument("source", help="The directory that contains the files to be backupped")
parser.add_argument("destination", help="The destination of the backups. Dated directories will be created in this folder")
parser.add_argument("--no-rotation", help="Turn off backup rotation", action="store_true")
parser.add_argument("--max-backups", help="Defines the maximum number of backups to be stored in the destination", type=int, default=5)
parser.add_argument("--prepend", help="Defines a different string to prepend to individual backups", default='ezback')
def validate():
options = parser.parse_args()
if not (os.path.isdir(options.source)):
print("The source provided is not a directory or does not exist")
exit()
if not (os.path.isdir(options.destination)):
print("Please enter a valid destination directory")
exit()
if not (os.path.isabs(options.destination)):
options.destination = os.getcwd()+"/"+options.destination
if not (os.path.isabs(options.source)):
options.source = os.getcwd()+"/"+options.source
return options
def create_new_current(options):
global current_backup, current_folder
current_backup = options.prepend+"-"+str(round(time.time()))
current_folder = options.destination.rstrip("/")+"/"+current_backup
def execute_backup(options):
print("Backup initiated...")
print(current_folder)
shutil.copytree(options.source, current_folder)
print("New state saved")
def rotate_backups(options):
if (options.no_rotation == False):
all_directories = os.listdir(options.destination.rstrip("/"))
relevant_directories = []
for directory in all_directories:
if (directory.startswith(options.prepend)):
relevant_directories.append(directory)
relevant_directories.sort(reverse=True)
relevant_directories = relevant_directories[options.max_backups:]
for remove_directory in relevant_directories:
if (remove_directory != ""):
shutil.rmtree(options.destination.rstrip("/")+"/"+remove_directory)
def main():
print("Starting EasyBackup v"+version)
parser_setup()
options = validate()
create_new_current(options)
execute_backup(options)
rotate_backups(options)
print("Done.")
if __name__ == '__main__':
main()
| true |
ae9f3ec2f8b3a30fba2e597972077f5bb126d3be | Python | sebastien/literate | /src/literate.py | UTF-8 | 18,061 | 3.28125 | 3 | [] | no_license | #!/usr/bin/env python3
# encoding=utf8 ---------------------------------------------------------------
# Project : Literate.py
# -----------------------------------------------------------------------------
# Author : FFunction
# License : BSD License
# -----------------------------------------------------------------------------
# Creation date : 02-Mar-2015
# Last modification : 08-Sep-2016
# -----------------------------------------------------------------------------
import re, sys, argparse
VERSION = "0.1.3"
LICENSE = "http://ffctn.com/doc/licenses/bsd"
__version__ = VERSION
__doc__ = """
A small literate-programming tool that extracts and strips text within comment
delimiters and outputs it on stdout.
"""
"""{{{
\# Literate.py
## A multi-language literate programming tool
```
Version : 0.1.2
URL : http://github.com/sebastien/literate.py
```
`literate.py` extracts documentation embedded in source-code files, allowing
to have both project documentation and source code in the same file.
It is intended for small-sized projects where you would prefer to avoid
having the documentation and the code separate.
It can also be used as a literate programming tool where you have the source
code presented alongside explanations.
How does it work?
=================
`literate.py` will look for specific delimiters in your source files and
extract the content content between these delimiters. The delimiters depend
on the language you're using.
In C-style languages (Java, JavaScript), it looks like this
```
/**
* TEXT THAT WILL BE EXTRACTED
* ‥
*/
```
In shell-like or Python-like languages:
```
# {{{
# TEXT THAT WILL BE EXTRACTED
# ‥
# \}\}}
```
In Python:
```
\"\"\"{{{
TEXT THAT WILL BE EXTRACTED
\}\}\}\"\"\"
{{{
TEXT THAT WILL BE EXTRACTED
\}\}\}
```
In indentation:
The extracted text will then be output to stdout (or to a specific file using
the `-o` command line option). You're then free to process the output
with a tool such as `pandoc` to format it to a more readable format.
A typical workflow would be like that
```
$ literate.py a.py b.py | pandoc -f markdown -t html README.html
```
}}}"""
# {{{PASTE:COMMAND_LINE}}}
# {{{PASTE:LANGUAGES}}}
# {{{PASTE:COMMANDS}}}
# {{{PASTE:API}}}
# -----------------------------------------------------------------------------
#
# COMMNANDS
#
# -----------------------------------------------------------------------------
# {{{CUT:COMMANDS}}}
"""{{{
Commands
========
One of the typical problem you'll encounter when adding documentation in your
source code is that the source ordering of elements (functions, classes, etc)
might not be ideal from an explanation/documentation perspective. In other
words, you might want some sections of your literate text to be re-ordered
on the output.
To do that, `literate.py` provides you with a few useful commands, which
need to be the only content of a literate text to be interpreted.
For instance, in C/JavaScript:
```
/**
* CUT:ABOUT
*/
```
or in Python/Sugar:
```
# {{{CUT:ABOUT\}\}\}
```
The *available commands* are the following:
<dl>
<dt>`CUT:<NAME>`</dt>
<dd>
`CUT` will not output any following literate text until another
`CUT` command or a corresponding `END` command is encountered.
</dd>
<dt>`END:<NAME>`</dt>
<dd>
`END` will end the `CUT`ting of the literate text. Any literate
text after that will be output.
</dd>
<dt>`PASTE:<NAME>`</dt>
<dd>
`PASTE`s the `CUT`ted literate text block. You can `PASTE` before
a `CUT`, but there always need to be a corresponding `CUT`ted block.
</dd>
</dl>
Note that `<NAME>` in the above corresponds to a string that matches
`[A-Z][A-Z0-9_\-]*[A-Z0-9]?`, that is starts with an UPPER CASE letter,
might contain UPPER CASE letters, digits, dashes or underscores and end
with an UPPER CASE letter or digit. That's a bit restrictive, but it makes
it easier to highlight and spot in your source code.
}}}"""
RE_COMMAND_PASTE = re.compile("\s*(PASTE):([A-Z][A-Z0-9_\-]*[A-Z0-9]?)")
RE_COMMAND_CUT = re.compile("\s*(CUT):([A-Z][A-Z0-9_\-]*[A-Z0-9]?)")
RE_COMMAND_END = re.compile("\s*(END):([A-Z][A-Z0-9_\-]*[A-Z0-9]?)")
RE_COMMAND_VERBATIM = re.compile("\s*(VERBATIM):(START|END)")
RE_ESCAPE = re.compile("\\\\.")
COMMANDS = {
"PASTE": RE_COMMAND_PASTE,
"CUT" : RE_COMMAND_CUT,
"END" : RE_COMMAND_END,
"VERBATIM" : RE_COMMAND_VERBATIM
}
# -----------------------------------------------------------------------------
#
# LANGUAGES/API
#
# -----------------------------------------------------------------------------
# {{{CUT:API}}}
"""{{{
API
===
You can import `literate` as a module from Python directly, and use it
to extract literate text from files/text.
The module defines ready-made language parsers:
- `literate.C`, `literate.JavaScript` for C-like languages
- `literate.Python`, `literate.Sugar` for Pythonic languages
You can also subclass the `literate.Language`, in particular:
}}}"""
class Language(object):
EOLS = "\r\n"
SPACES = "\t\n"
VERBATIM_DEINDENT = True
LINE_BASED = False
# {{{
# `Language.RE_START:regexp`
# :
# The regular expression that is used to match start delimiters
# }}}
RE_START = None
# {{{
# `Language.RE_END:regexp`
# :
# The regular expression that is used to match end delimiters
# }}}
RE_END = None
# {{{
# `Language.RE_STRIP:regexp`
# :
# The regular expression that is used to strip pieces such as leading
# `#` characters.
# }}}
RE_STRIP = None
# {{{
# `Language.ESCAPE=[(old:String,new:String)]`
# :
# A list of `old` strings to be replaced by `new` strings, which is
# a very basic way of dealing with excaping delimiters.
# }}}
ESCAPE = [None, None]
def __init__( self, options=None ):
self.newlines = options and options.newlines or True
self.strip = options and options.strip or True
def command( self, text ):
"""Returns a couple `(command:String, argument:String)` if the
given text corresponds to a Literate command."""
for name, regexp in list(COMMANDS.items()):
m = regexp.match(text)
if m: return m.group(1), m.group(2)
return None
# {{{
# `Language.extract( self, text:String )`
# :
# The main algorithm that extracts the literate text blocks from the
# source files.
# }}}
def extract( self, text, start=None, end=None, strip=None, escape=None ):
"""Extracts literate string from the given text, using
the given `start`, `end` and `strip` regular expressions.
- `start` is used to match the start of a literate text
- `end` is used to match the end of a literate text
- `strip` is used to match any leading text to be stripped from
a literate text line.
"""
start = start or self.RE_START
end = end or self.RE_END
strip = strip or self.RE_STRIP
escape = escape or self.ESCAPE
assert start, "Language.extract: no start regexp given"
assert end, "Language.extract: no end regexp given"
block = []
blocks = {"MAIN":block}
last_end = -1
verbatim = None
# FIXME: Stripping should be smarter and should check for a consitent
# pattern at the start
for i, s in enumerate(start.finditer(text)):
e = end.search(text, s.end())
# If we did not find an end, or that we found a start before the last
# end, then we continue.
if not e or s.end() < last_end: continue
t = text[s.end():e.start()]
if self.LINE_BASED:
# For line-based languages, we string on a line basis
r = []
for line in t.split("\n"):
m = strip.match(line)
if m: r.append(line[m.end():])
else: r.append(line)
t = "\n".join(r)
else:
# For non-line-based languages, we strip the expressions directly
t = "".join((_ for _ in strip.split(t) if _ is not None))
for old, new in escape: t = t.replace(old, new)
command = self.command(t)
if not command:
if verbatim:
block.append(self._processBlock(text[max(verbatim,last_end):s.start()]))
# If we have the strip option, we absorb the leading newline
if self.strip and i == 0 and len(block) == 0 and t[0] == "\n": t = t[1:]
# If we have the newlines options, and the block is not empty, ends with a string,
# which is not the empty string, then we add it.
if self.newlines and i > 0 and len(block) > 0 and type(block[-1]) is str and not block[-1][-1] == "\n": block.append("\n")
block.append(self._processBlock(t))
elif command[0] == "CUT":
block = blocks.setdefault(command[1], [])
elif command[0] == "END":
block = blocks["MAIN"]
elif command[0] == "PASTE":
block.append(command)
elif command[0] == "VERBATIM":
if command[1] == "START":
verbatim = e.end()
else:
# TODO: We should de-indent for Pythonic languages
block.append(self._processVerbatim(text, max(verbatim,last_end), s.start(), verbatim))
verbatim = None
else:
raise Exception("Unsupported command: " + t)
last_end = e.end()
for _ in self._output(blocks["MAIN"], blocks):
yield _
def _processBlock( self, text ):
res = []
o = 0
for m in RE_ESCAPE.finditer(text):
res.append(text[o:m.start()])
res.append(text[m.start()+1])
o = m.end()
res.append(text[o:])
return "".join(res)
def _processVerbatim( self, text, startOffset, endOffset, verbatimOffset ):
"""Processes the given verbatim text, de-indenting the lines
based on the indentation of the first verbatim text."""
# We extract the leading indent
spaces = []
o = verbatimOffset - 1
while o >= 0 and text[o] not in self.EOLS:
c = text[o]
if c in self.SPACES:
spaces.append(c)
elif c not in self.EOLS:
spaces = []
o -= 1
spaces.reverse()
spaces = "".join(spaces)
# Now we split the block in lines and deindent them before joining them
# back. We also strip the lines that contain the stripping characters
block = "\n".join(
self._deindent(_, spaces) for _ in text[startOffset:endOffset].split("\n") if not self.RE_STRIP.match(_)
)
if block and block[0] == "\n": block = block[1:]
return block
def _deindent( self, line, indent ):
"""De-indents the given line of text."""
# FIXME: This is a dumb deindent
i = 0
while i < len(indent) and i < len(line) and line[i] == indent[i]: i += 1
return line[i:]
def _output( self, block, blocks ):
for i, line in enumerate(block):
if type(line) in (str, str):
yield line
elif line[0] == "PASTE":
for _ in self._output( blocks[line[1]], blocks):
yield _
# -----------------------------------------------------------------------------
#
# SPECIFIC LANGUAGES
#
# -----------------------------------------------------------------------------
# {{{CUT:LANGUAGES}}}
"""{{{
Supported Languages
===================
C, C++ & JavaScript
-------------------
The recognized extensions are `.c`, `.cpp`, `.h` and `.js`. Literate texts
start with `/**` and end with `*/`. Any line starting with `*` (leading and
trailng spaces) will be stripped.
Example:
```
/**
* Input data is acquired through _iterators_. Iterators wrap an input source
* (the default input is a `FileInput`) and a `move` callback that updates the
* iterator's offset. The iterator will build a buffer of the acquired input
* and maintain a pointer for the current offset within the data acquired from
* the input stream.
*
* You can get an iterator on a file by doing:
*
* ```c
* Iterator* iterator = Iterator_Open("example.txt");
* ```
*
*/
```
}}}"""
class C(Language):
RE_START = re.compile("/\*\*")
RE_END = re.compile("\*/")
RE_STRIP = re.compile("[ \t]*\*[ \t]?")
ESCAPE = (("\\*\\/", "*/"),)
class JavaScript(C):
pass
"""{{{
Python
------
The recognized extensions are `.py`. Literate texts
start with `{{{` and end with `\}\}\}`. Any line starting with `|` (leading and
trailing spaces) will be stripped.
The following block of text will be processed as part of the documentation:
```python
"\""{{{CUT:ABOUT\}}}{{{
Input data is acquired through _iterators_. Iterators wrap an input source
(the default input is a `FileInput`) and a `move` callback that updates the
iterator's offset. The iterator will build a buffer of the acquired input
and maintain a pointer for the current offset within the data acquired from
the input stream.
}\}}"\""
if True:
# The following will be appended to the documentation as well
"\""{\{{
\| You can get an iterator on a file by doing:
\|
\| ```c
\| Iterator* iterator = Iterator_Open("example.txt");
\| ```
}\}}
"\""
```
}}}"""
class Python(Language):
LINE_BASED = True
RE_START = re.compile("\{\{\{")
RE_STRIP = re.compile("^\s*[\|#]\s?")
RE_END = re.compile("\s*\#?\s*}}" "}")
ESCAPE = (
("\\}\\}\\}", "}" "}}"),
('\\"\\"\\"', '"""')
)
"""{{{
Sugar
-----
The recognized extensions are `.sjs` and `.spy`. Literate texts
start with `{{{` and end with `\}\}\}`. Any line starting with `|` (leading and
trailng spaces) will be stripped.
Example:
```
\# {{{CUT:ABOUT\}\}\}
\# {\{{
\# Input data is acquired through _iterators_. Iterators wrap an input source
\# (the default input is a `FileInput`) and a `move` callback that updates the
\# iterator's offset. The iterator will build a buffer of the acquired input
\# and maintain a pointer for the current offset within the data acquired from
\# the input stream.
\# \}\}\}
if True
\# {\{{
\# You can get an iterator on a file by doing:
\#
\# \\```c
\# Iterator* iterator = Iterator_Open("example.txt");
\# \\```
\# \}\}\}
end
```
}}}"""
class Sugar(Python):
pass
class Paml(Python):
pass
"""{{{
A note about escaping
---------------------
Your source code might contain the delimiters as part of regular code, most
likely within strings. If this is the case you should try to write them diffently,
either by using escape symbols (such as `\`) or by breaking the string in bits (
in Python you could do `"{{" "{"` which would return a string equivalent to
the start delimiter).
If you'd like to represent a delimiter within a literate text, you only have
to worry about the end delimiter. The convention is to write the delimiter
with each character prefixed by a `\`.
}}}"""
# {{{END:LANGUAGES}}}
# -----------------------------------------------------------------------------
#
# FUNCTIONS
#
# -----------------------------------------------------------------------------
LANGUAGES = {
"c|cpp|h" : C,
"js" : JavaScript,
"py" : Python,
"sjs|spy" : Sugar,
"paml" : Paml,
}
def getLanguage( filename, args ):
ext = filename.rsplit(".", 1)[-1]
for pattern, parser in list(LANGUAGES.items()):
if re.match(pattern, ext):
return parser(args)
return None
# -----------------------------------------------------------------------------
#
# MAIN
#
# -----------------------------------------------------------------------------
def run(args=None):
args = sys.argv[1:] if args is None else args
def fail( message ):
sys.stderr.write("[!] ")
sys.stderr.write(message)
sys.stderr.write("\n")
sys.stderr.flush()
return sys.exit(-1)
# {{{CUT:COMMAND_LINE}}}
"""{{{
|
| Command-line tool
| =================
|
| `literate.py` can be executed as a command-line tool.
|
| `literate.py [OPTIONS] FILE...`
|
| `FILE` is optional (by default, stdin will be used). You can use `-` to
| explicitely read data from stding.
|
| It takes the following options:
|
| - `-l=LANG` `--language=LANG`, where `LANG` is any of `c`, `js` or `sugar`.
| If you don't give a language, it will output the list of supported languages.
|
| - `-o=PATH` will output the resulting text to the given file. By default,
| the extracted text is printed on stdout.
|
| - `-n, `--newlines` will ensure that the blocks are always separated by
| newlines (default is ON)
|
| - `-s, `--strip` will strip leading and trailing spaces/newlines
| from the output (default is ON)
| }}}"""
out = sys.stdout
# Parses the arguments
parser = argparse.ArgumentParser(
description="Extracts selected text from source code to create documentation files."
)
parser.add_argument("files", metavar="FILE", type=str, nargs="*", help="Source files to be processed. Stdin is denoted by `-`")
parser.add_argument("-l", "--language", dest="language", action="store", help="Enforces the given language for the input file. If empty, lists the available languages")
parser.add_argument("-o", "--output", dest="output", action="store", help="Specifies an input file, stdout is denoted by -")
parser.add_argument("-n", "--newlines", dest="newlines", action="store_true", default=True, help="Ensures that blocks are separated by newlines")
parser.add_argument("-s", "--strip", dest="strip", action="store_true", default=True, help="Strips leading and trailing newlines")
# parser.add_argument("-t", "--template", dest="template", action="store_true", default=True, help="Outputs the path to the template")
args = parser.parse_args(args)
output = None
if args.output:
output = file(args.output, "w")
out = output or out
if False and args.template and not output:
pass
# path = os.path.dirname(os.path.abspath(__file__))
# path = os.path.expanduser("~/Projects/Public/Literate/literate.tmpl")
# # FIXME: This should be done differently
else:
# Executes the main program
if not args.files or args.files == ["-"]:
if not args.language:
fail("A language (-l, --language) must be specified when using stdin. Try again with -lc, or run literate --help for more information ")
out.write(getLanguage(args.language, args).extract(sys.stdin.read()))
else:
for p in args.files:
language = args.language or getLanguage(p, args)
assert language, "No language registered for file: {0}. Supported extensions are {1}".format(p, ", ".join(list(LANGUAGES.keys())))
with open(p, "r") as f:
for line in language.extract(f.read()):
out.write(line)
if output: output.close()
if __name__ == "__main__":
run()
# EOF - vim: ts=4 sw=4 noet
| true |
c94d7babba347d01fe79133562eaac31bad071ba | Python | AnthonyCarrasco/MSLcompiler | /recursiveDescentParser.py | UTF-8 | 7,350 | 3.15625 | 3 | [] | no_license | ''' Recursive Descent Parser '''
''' It verifies the list of tokens from scanner/lexer'''
''' Are valid for MSL Grammar '''
''' Import the lexer '''
from scanner import *
''' The grammar is as follows '''
''' Program -> [RESERVE int] { PROC-DEC } series "." '''
def program(tokens):
print("entering program routine")
if not tokens:
return True
if tokens[-1] == "RESERVE":
tokens.pop()
if tokens[-1].isdigit():
print("RESERVED MEMORY :: " + tokens.pop())
else:
return False
if tokens[-1] == "PROC":
if proc_dec(tokens):
if series(tokens):
if tokens == ["."]:
return True
else:
return False
print("PROC DEC PASSED")
if series(tokens):
if tokens == ["."]:
print(tokens)
return True
else:
return program(tokens)
''' PROCDEC -> PROC identifier ["(" identifier {"," identifier} ")"] series END '''
def proc_dec(tokens):
print("entering proc_dec")
nextChar = tokens.pop() #obtain next token
if nextChar == "PROC":
nextChar = tokens.pop()
if nextChar.isalpha():
if tokens[-1] == "(":
tokens.pop()
nextChar = tokens.pop()
if nextChar.isalpha():
nextChar = tokens.pop()
if nextChar == ")":
if series(tokens):
if tokens[-1] == "END":
tokens.pop()
return True
else:
return False
else:
return False
elif nextChar == ",":
nextChar = tokens.pop()
while(nextChar.isalpha()):
nextChar = tokens.pop()
print(nextChar)
if nextChar == ",":
nextChar = tokens.pop()
elif nextChar == ")":
if series(tokens):
if tokens[-1] == "END":
tokens.pop()
return True
else:
return False
else:
return False
else:
nextChar = tokens.pop()
''' series -> statement { 'statement' } '''
def series(tokens):
print("entering series routine")
boolean = statement(tokens)
return True
''' statement -> assign | while | if | call | read | write '''
def statement(tokens):
print("entering statement routine")
if tokens[-1] == "." or tokens[-1] == "END":
return True
nextChar = tokens.pop()
if nextChar == "WHILE":
return while_statement(tokens)
elif nextChar == "IF":
return if_statement(tokens)
elif nextChar == "READ":
return read_statement(tokens)
elif nextChar == "WRITE":
return write_statement(tokens)
elif nextChar.isalpha():
tokens.append(nextChar)
return assign_statement(tokens)
else:
return False
''' while -> WHILE expression DO series OD '''
def while_statement(tokens):
print("entering while_statement routine")
if expression(tokens):
nextChar = tokens.pop()
if nextChar == "DO":
if(series(tokens)):
nextChar == tokens.pop()
if nextChar == "OD":
return True
else:
return False
else:
return False
else:
return False
else:
return False
''' if-> IF expression THEN series[ELSE series] FI '''
def if_statement(tokens):
print("entering if_statement routine")
if expression(tokens):
nextChar = tokens.pop()
if nextChar == "THEN":
if series(tokens):
if tokens[-1] == "ELSE":
tokens.pop()
if series(tokens):
nextChar == tokens.pop()
return nextChar == "FI"
elif tokens:
nextChar = tokens.pop()
return nextChar == "FI"
else:
return False
else:
return False
else:
return False
''' assign -> variable ":=" expression '''
def assign_statement(tokens):
print("entering assign_statement routine")
if variable(tokens):
nextChar = tokens.pop()
if nextChar == ":=":
return expression(tokens)
else:
return False
else:
return False
''' read -> READ [#]varaible { "," [#] variable} '''
def read_statement(tokens):
print("entering read_statement routine")
if tokens[-1] == "#":
tokens.pop()
if variable(tokens):
if tokens[-1] == ",":
tokens.pop()
return read_statement(tokens)
else:
return True
else:
return False
''' write -> WRITE [#] expression { "," [#] expression } '''
def write_statement(tokens):
print("entering wrtie_statement routine")
if tokens[-1] == "#":
tokens.pop()
if expression(tokens):
if tokens[-1] == ",":
tokens.pop()
return write_statement(tokens)
else:
return True
else:
return False
''' variable -> identifier ["!" operand] '''
def variable(tokens):
print("entering varaible routine")
nextChar = tokens.pop()
if nextChar.isalpha():
if tokens[-1] == "!":
tokens.pop()
return operand(tokens)
else:
return True
else:
return False
''' expression -> operand { operator operand' } '''
def expression(tokens):
print("entering expression routine")
if operand(tokens):
if operator(tokens):
return operand(tokens)
elif tokens:
return True
else:
return False
else:
return False
''' operand -> int | text | variable | "(" expression ")" '''
def operand(tokens):
print("entering operand routine")
nextChar = tokens.pop()
if nextChar.isdigit() or nextChar.isalpha():
return True
elif nextChar == "(":
if expression(tokens):
nextChar == tokens.pop()
if nextChar == ")":
return True
else:
return False
else:
return False
else:
return False
''' operator -> All possible operators '''
def operator(tokens):
print("entering operator routine")
nextChar = tokens.pop()
operators = ["<",">","=","<=","==",">=","+","-","/","*","%","&", "!"]
if nextChar in operators:
return True
else:
return False
''' Main Program to run '''
lexemes = main() #Call the lexer to return a list of tokens
lexemes.reverse() #reverse tokens to treat as a stack
print(lexemes) # print to verify
boolean = program(lexemes) #program returns true or false
print boolean
| true |
1d28f8224671bb524adb512e9d708e598ea1227d | Python | ljrodriguez1/llevame-opti | /main.py | UTF-8 | 3,165 | 2.90625 | 3 | [] | no_license | from parametros import *
import googlemaps
import pandas as pd
from usuarios import Usuario
import requests
import random
def cargarUsuarios(path):
dataUsuarios = pd.read_csv(path)
#print(dataUsuarios.keys())
usuarios = []
for num in range(len(dataUsuarios)): #range(len(dataUsuarios))
nombre = dataUsuarios['nombre'][num]
appellido_mat = dataUsuarios['apellido_mat'][num]
appellido_pat = dataUsuarios['apellido_pat'][num]
direccion = dataUsuarios['direccion'][num]
lat = dataUsuarios['lat'][num]
lng = dataUsuarios['lng'][num]
real_uid = dataUsuarios['id'][num]
if isinstance(direccion, str):
usuarios.append(Usuario(nombre, appellido_mat, appellido_pat, direccion, lat, lng, real_uid))
return usuarios
def calcular_distancia(usuarios):
gmaps = googlemaps.Client(key=API_KEY)
for usuario1 in usuarios:
for usuario2 in usuarios:
usuario1.calcular_tiempo(usuario2, gmaps)
pass
maxLenght = max(len(x.tiempo_a) for x in usuarios)
usuariosValidos = []
for usuario in usuarios:
if len(usuario.tiempo_a) == maxLenght:
usuariosValidos.append(usuario)
with open('usuarios_validos.csv', 'w', encoding='utf-8') as file:
for usuario in usuariosValidos:
usuario.guardar_usuario(file)
with open('tiempo_entre_usuarios.csv', 'w', encoding='utf-8') as file:
for usuario in usuariosValidos:
usuario.guardar_tiempo_entre(file)
def aCordenadas(path):
GOOGLE_MAPS_API_URL = 'https://maps.googleapis.com/maps/api/geocode/json'
usuarios = pd.read_csv(path)
print(usuarios.keys())
with open('usuarios_validos3.csv', 'w', encoding='utf-8') as file:
file.write('id,nombre,apellido_mat,apellido_pat,direccion,lat,lng\n')
print(len(usuarios))
for num in range(len(usuarios)):
print(num)
direccion = usuarios['direccion'][num]
params = {
'address': direccion,
'region': 'chile',
'key': API_KEY
}
# Do the request and get the response data
req = requests.get(GOOGLE_MAPS_API_URL, params=params)
res = req.json()
# Use the first result
result = res['results'][0]
geodata = dict()
geodata['lat'] = result['geometry']['location']['lat'] + random.randint(-100, 100)/50000
geodata['lng'] = result['geometry']['location']['lng'] + random.randint(-100, 100)/50000
geodata['address'] = result['formatted_address']
nombre = usuarios['nombre'][num]
apellido_mat = usuarios['apellido_mat'][num]
apellido_pat = usuarios['apellido_pat'][num]
file.write('{},{},{},{},"{}",{},{}\n'.format(num, nombre, apellido_mat, apellido_pat, geodata['address'], geodata['lat'], geodata['lng']))
#aCordenadas('usuarios_validos2.csv')
#gmaps = googlemaps.Client(key=API_key)
#data = gmaps.distance_matrix('camino punta de aguila 4307', 'alonso de cordova 2860')['rows'][0]['elements'][0]
#print(data) | true |
640a6241753a0fc8f7b241cab208a84d296ea85f | Python | BrianThomasRoss/juxta-city-data-ds | /test_main.py | UTF-8 | 751 | 2.546875 | 3 | [
"MIT"
] | permissive | import os
import psycopg2
import unittest
import pandas as pd
from dotenv import load_dotenv
load_dotenv()
DB_NAME = os.getenv("DB_NAME")
DB_HOST = os.getenv("DB_HOST")
DB_PASS = os.getenv("DB_PASS")
DB_USER = os.getenv("DB_USER")
connection = psycopg2.connect(database=DB_NAME, user=DB_USER,
password=DB_PASS, host=DB_HOST, port="5432")
cursor = connection.cursor()
heart = pd.read_csv('./useful_datasets/heart_data.csv')
class SQLTestCase(unittest.TestCase):
def test_heartQuery(self):
query = "SELECT COUNT(*) FROM heart_disease;"
cursor.execute(query)
result = cursor.fetchone()[0]
self.assertEqual(result, heart.shape[0])
if __name__ == "__main__":
unittest.main()
| true |
7603005f5c613ab42505e1a700381d37ca1d0b30 | Python | kevburke24/TexasHoldEm-Python | /Modules/stud_poker_hand.py | UTF-8 | 3,867 | 4.09375 | 4 | [] | no_license | """Class creating an object representing a stud poker hand consisting of 2 hole cards
I affirm that I have carried out my academic endeavours with full academic honesty-
Kevin Burke"""
from card import Card
from community_card_set import CommunityCardSet
from itertools import combinations
from poker_hand import PokerHand
class StudPokerHand:
def __init__(self, community_cards):
"""Creates a StudPokerHand object with list and community card attributes"""
self.stud_hand = []
self.community_card_set = community_cards
def add_card(self, card):
"""Adds a card to stud hand object"""
self.stud_hand.append(card)
def get_card(self, i):
"""Returns ith card from stud hand object"""
return self.stud_hand[i]
def remove_card(self, i):
"""Removes ith card from stud hand object and returns it"""
return self.stud_hand.pop(i)
def __str__(self):
"""Creates string representation of stud hand object"""
return ", ".join([str(c) for c in self.stud_hand])
def test_get_card(self):
return self.get_card(3)
def test_remove_card(self):
return self.remove_card(3)
def compare_to(self, other):
"""Compare this hand (self) to another hand (other) taking into
account the community cards, and return a positive number,
negative number, or zero depending on which is worth more.
:param self: The first hand to compare
:param other: The second hand to compare
:return: a negative number if self is worth LESS than other, zero
if they are worth the SAME, and a positive number if self is worth
MORE than other
"""
best_hand1 = self.__get_best_five_card_hand()
best_hand2 = other.__get_best_five_card_hand()
if best_hand1.compare_to(best_hand2) > 0:
return 1
if best_hand1.compare_to(best_hand2) < 0:
return -1
else:
return 0
def __get_all_five_card_hands(self):
"""Determines all possible 5-card PokerHand objects from combined stud and community
cards and returns them"""
for i in range(0, len(self.community_card_set.community_cards)):
card = self.community_card_set.get_card(i)
self.add_card(card)
five_card_hands = combinations(self.stud_hand, 5)
a_list = []
for combination in five_card_hands:
hand = PokerHand()
for i in range(0, len(combination)):
card = combination[i]
hand.add_card(card)
a_list.append(hand)
return a_list
def __get_best_five_card_hand(self):
"""Determine the best possible 5-card PokerHand object from
the available hole and community cards and return it.
"""
hands = self.__get_all_five_card_hands()
best_so_far = hands[0]
for i in range(1, len(hands)):
if hands[i].compare_to(best_so_far) > 0:
best_so_far = hands[i]
return best_so_far
if __name__ == "__main__":
community_card_set = CommunityCardSet()
community_card_set.add(Card('D', 9))
community_card_set.add(Card('C', 10))
community_card_set.add(Card('C', 8))
community_card_set.add(Card('H', 2))
community_card_set.add(Card('C', 4))
stud_hand = StudPokerHand(community_card_set)
stud_hand.add_card(Card('D', 2))
stud_hand.add_card(Card('S', 3))
other_stud_hand = StudPokerHand(community_card_set)
other_stud_hand.add_card(Card('S', 5))
other_stud_hand.add_card(Card('C', 6))
print(stud_hand.compare_to(other_stud_hand))
print(community_card_set.test_get_card())
print(community_card_set.test_remove_card()) | true |
a9e9f12a55e02b66ea774fd81e7d9244ea889f8a | Python | orlandodiaz/pdbox | /examples/strategies/strat_adx.py | UTF-8 | 5,682 | 2.84375 | 3 | [] | no_license | from backtest.strategy import *
from datetime import time, datetime
class ADXStrat(Strategy):
def __init__(self, name):
super(ADXStrat, self).__init__(name)
self.direction = "long"
self.bar_interval = "5min"
self.body = 0
self.bear_shadow = 0
def get_buy_coordinates(self, df):
buy_locations = df.index[
(df['chg_since_open'] > 5) & (df['adx'] < 30) &
# (df['avg_vol_14d'] > 80000) &
# (df['close'] < df['ema13'])
(df['close'] > 1) & (df['close'].shift(1) < df['ema13'].shift(1)) &
(df['open'] - df['close'] < 0)
& # If we have a positive candlestick
# (abs((df['close'] - df['open']) / df['open']) > 0.03) & # with a least .3% pos change. Prevent those low trade dojis
# (df['rel_close_open_diff'] > 7) & # The candle is much bigger than previous ones. Note: This might not always be the case
(df['volume'] > 120000)
& #50,000 is not a lot of volume to start with. Higher than 100k ensures this is not a false alarm
# (df['rel_vol_20p'] > 13) & # The higher the market cap the less relative volume there would be
# (df['rel_vol_100p'] > 15) & # The higher the market cap the less relative volume you have to target
# (df['rel_vol_2day'] > 8) & # use this to prevent getting third or fourth candlesticks which may already be overbought. Don't use for realtime
# (df['7dayTotalVol'] > 4000) &
(df['date'].dt.time != time(16)) &
# (df['date'].dt.time != datetime.time(9,30)) & # Alphavantage starts reporting at 9:35
# (df['high'] > df['4mo_high']) & # The close is greater than the "7" day high or less depending on the data we have
((df['volume'] / df['7dayMaxVol']) > 1.25
) # Not really a 7day high if we don't have enough data. Common issue with alphavantage which only returns the previous 15 days. Previously sued 2.5
# ... meaning if the breakout happened early we could get as little as 1 day previous high data or no data at all
#(df['high'] / df['close'] < 1.2375)
# ((df['high'] / df['close'] < 1.1375) & (df['pct_change'] < 0.5)) # Candlestick pattern should not be bearish. Not being hammered down. Greater than 13% indicates it had negative candlesticks in the 1 or 2min
# (df['close'] / df['ema13'] < 1.35) #The close is currently NOT deviated more than 45% from its 14-EMA
]
return buy_locations
@staticmethod
def check_for_conditions(self, df, ticker, buy_locations):
if len(buy_locations) == 0:
# Tells us which conditions failed. Note: Wrong because sometimes multiple conditions are not met
if (df['volume'] > 130000).any() is False:
print '{ticker}\t Volume condition failed. Volume not greater than 130,000'.format(
ticker=ticker)
elif (df['high'] > df['4mo_high']).any() is False:
print '{ticker} \t Current high is not greater than the 4 month high'.format(
ticker=ticker)
elif (df['rel_vol_100p'] > 23).any() is False:
print 'Relative volume from the last 100 observations is not greater than 23'
elif ((df['volume'] / df['7dayMaxVol']) > 2.5).any() is False:
print('volume is not greater than the 7day maximum volume')
elif ((df['high'] / df['close']) < 1.1375).any() is False:
print 'Bearish candlestick pattern (high over close is greater than 13.76%)'
# Used to prevent getting 3/4 candlesticks which may already be overbought. Don't use for realtime
elif (df['rel_vol_2day'] > 8).any() is False:
print 'rel_vol_2day is not greater than 8'
else:
print '{ticker} \t a condition failed'.format(ticker=ticker)
pass
def sell_algorithm(self, init, ticker, df):
sell_price = 0
sell_date = 0
for i in range(init, len(df) + 1):
# Bearish hammer
self.body = (
df.iloc[[i + 1]]['open'] - df.iloc[[i + 1]]['close']).values[0]
self.bear_shadow = (
df.iloc[[i + 1]]['high'] - df.iloc[[i + 1]]['open']).values[0]
hammer_strength = self.bear_shadow / self.body # 3 is a strong hammer , 4 is a very strong hammer
previous_body = (
df.iloc[[i]]['close'] - df.iloc[[i]]['open']).values[0]
# Use .values[0] to convert to numpy boolean. Dont use == or is True
if (df.iloc[[i + 1]]['close'] > df.iloc[[i + 1
]]['ema13']).values[0]:
if self._trade_type == "daily":
# Break loop at the end of the day otherwise
if (df.iloc[[i]]['date'].dt.time >= time(15, 55)).values[0]:
sell_price = df.iloc[[i + 1]]['close'].values[0]
sell_date = df.iloc[[i + 1]]['date'].values[0]
break
else:
continue
else:
continue
else:
sell_price = df.iloc[[i + 1]]['close'].values[0]
sell_date = df.iloc[[i + 1]]['date'].values[0]
print "%s backtester2: \t %s \t SELL @ %.3f\t LOC: %d . Sold solely on close < ema" \
% (datetime.now().strftime("%H:%M:%S"), ticker, sell_price, i+1)
break
return sell_date, sell_price
| true |
7152f6596be72451add79a8770dbb4831179005a | Python | maifatai/image-processing | /code/ThresholdSegmentation.py | UTF-8 | 4,270 | 2.953125 | 3 | [] | no_license | import cv2
import numpy as np
import matplotlib.pyplot as plt
'''
阈值分割:OTSU、TRIANGER、熵算法、自适应阈值分割
二值图像的与、或、非、异或运算
'''
src=cv2.imread('lena.jpg',0)
plt.figure('histogram')
plt.title('plt:histogram of lena')
plt.hist(src.ravel(),256)
plt.show()
'''
全局阈值分割
'''
ret,binary_img=cv2.threshold(src,127,255,cv2.THRESH_BINARY)#必须有两个返回值,ret为阈值
cv2.imshow('binary',binary_img)
plt.imshow(binary_img,cmap='gray')
plt.title('binary')
plt.show()
'''
OTSU阈值处理:前景和背景差异的方差最大
'''
thres,otsu=cv2.threshold(src,0,255,cv2.THRESH_OTSU)
print(thres)
plt.imshow(otsu,cmap='gray')
plt.title('otsu')
plt.show()
'''
triangle 阈值处理
'''
tri_thres,triangle=cv2.threshold(src,0,255,cv2.THRESH_TRIANGLE)
print(tri_thres)
plt.imshow(triangle,cmap='gray')
plt.title('triangle')
plt.show()
tri_thres1,triangle1=cv2.threshold(src,0,255,cv2.THRESH_TRIANGLE+cv2.THRESH_BINARY_INV)
print(tri_thres1)
plt.imshow(triangle1,cmap='gray')
plt.title('triangle binary inv')
plt.show()
'''
熵算法
'''
def threshold_entropy(img):
r,c=img.shape
hist=cv2.calcHist([src],[0],None,[256],[0,256])
normalize=(hist/float(r*c)).ravel()
#计算累加直方图
zeromoment=np.zeros([256],np.float32)
for i in range(256):
if i==0:
zeromoment[i]=normalize[i]
else:
zeromoment[i]=zeromoment[i-1]+normalize[i]
#计算各个灰度级的熵
entropy=np.zeros([256],np.float32)
for i in range(256):
if i==0:
if normalize[i]==0:
entropy[i]=0
else:
entropy[i]=-normalize[i]*np.log10(normalize[i])
else:
if normalize[i]==0:
entropy[i]=entropy[i-1]
else:
entropy[i]=entropy[i-1]--normalize[i]*np.log10(normalize[i])
#找阈值
ft=np.zeros([256],np.float32)
f1,f2=0,0
totalentropy=entropy[255]
for i in range(255):
max_front=np.max(normalize[0:i+1])
max_back=np.max(normalize[i+1:256])
if(max_front==0 or zeromoment[i]==0 or max_front==1 or zeromoment[i]==1 or totalentropy==0):
f1=0
else:
f1=entropy[i]/totalentropy*(np.log10(zeromoment[i])/np.log10(max_front))
if(max_back==0 or 1-zeromoment[i]==0 or max_back==1 or 1-zeromoment[i]==1):
f2=0
else:
f2=(1-entropy[i]/totalentropy)*(np.log10(1-zeromoment[i])/np.log10(max_back))
ft[i]=f1+f2
#找到最大值的索引
thresh_index=np.where(ft==np.max(ft))#np.where获取下标
thresh=thresh_index[0][0]
#阈值处理
dst=np.copy(img)
dst[dst>thresh]=255#形成布尔数组下标
dst[dst<=thresh]=0
plt.imshow(dst,cmap='gray')
plt.title('entropy threshold')
plt.show()
return dst
threshold_entropy(src)
'''
局部阈值分割:针对输入矩阵的每个位置的值都有相应的阈值,这些阈值构成了和输入矩阵同尺寸的矩阵thresh,
其核心是计算阈值矩阵。
自适应阈值分割:利用平滑处理后的图像作为阈值矩阵,平滑算子的尺寸决定了分割出来的物体的尺寸。
自适应阈值分割可以克服光照不均匀的影响
'''
adapt_mean=cv2.adaptiveThreshold(src,255,adaptiveMethod=cv2.ADAPTIVE_THRESH_MEAN_C,thresholdType=cv2.THRESH_BINARY,blockSize=9,C=0.15)
plt.imshow(adapt_mean,cmap='gray')
plt.title('adaptive threshold mean')
plt.show()
adapt_gauss=cv2.adaptiveThreshold(src,255,adaptiveMethod=cv2.ADAPTIVE_THRESH_GAUSSIAN_C,thresholdType=cv2.THRESH_BINARY,blockSize=9,C=0.15)
plt.imshow(adapt_gauss,cmap='gray')
plt.title('adaptive threshold guass')
plt.show()
'''
二值图像的与、或、非、异或运算
'''
dst_and=cv2.bitwise_and(adapt_mean,adapt_gauss)
plt.imshow(dst_and,cmap='gray')
plt.title('binary and')
plt.show()
dst_or=cv2.bitwise_or(adapt_mean,adapt_gauss)
plt.imshow(dst_or,cmap='gray')
plt.title('binary or')
plt.show()
dst_not=cv2.bitwise_not(adapt_mean)
plt.imshow(dst_not,cmap='gray')
plt.title('binary not')
plt.show()
dst_xor=cv2.bitwise_xor(adapt_mean,adapt_gauss)
plt.imshow(dst_xor,cmap='gray')
plt.title('binary xor')
plt.show()
cv2.waitKey(0)
cv2.destroyAllWindows()
| true |
48afdd2c6a7ee99df28c357d9b0ca05e520097b4 | Python | huozhiwei/Python3Project | /TCPAndUDP/demo01.py | UTF-8 | 1,366 | 3.78125 | 4 | [] | no_license | # TCP与UDP编程
# TCP: 传输控制协议,面向连接的,保证数据的可达性
# UDP: 数据报协议,无连接的,不能保证数据一定可以到达另一端
# Socket (套接字)
# socketServer模块
# 建立TCP服务端
"""
1. 创建Socket对象
2. 绑定端口号
3. 监听端口号
4. 等待客户端Socket的连接
5. 读取从客户端发过来的数据
6. 向客户端发送数据
7. 关闭客户端Socket连接
8. 关闭服务端的Socket连接
"""
# 以下代码为服务端代码
# 9876
from socket import *
host = "" # ip
bufferSize = 1024 # 字节
port = 9876
addr = (host, port)
# 1. 创建Socket对象
# AF_INET:IPV4,AF_INET:IPV6,SOCK_STREAM:TCP
tcpServerSocket = socket(AF_INET,SOCK_STREAM)
# 2. 绑定端口号
tcpServerSocket.bind(addr)
# 3. 监听端口号
tcpServerSocket.listen()
print("Server Port:9876")
print("正在等待客户端连接")
# 4. 等待客户端Socket的连接
tcpClientSocket,addr = tcpServerSocket.accept()
print("客户端已经连接","addr","=",addr)
# 5. 读取从客户端发过来的数据
data = tcpClientSocket.recv(bufferSize) # 1024 byte
print(data.decode("utf-8"))
# 6. 向客户端发送数据
tcpClientSocket.send("hello,I love you.\n".encode(encoding="utf-8"))
# 7. 关闭客户端Socket连接
tcpClientSocket.close()
# 8. 关闭服务端的Socket连接
tcpServerSocket.close() | true |
89134d9f591b19f8cdf15214a90ced07ab81f633 | Python | bintangbhp/dasar-pemrograman-1 | /lab/lab01/lab01.py | UTF-8 | 781 | 3.5625 | 4 | [] | no_license | # Untuk memanggil/mengimpor moodul turtle
import turtle
# Untuk mengubah warna turle menjadi biru
turtle.color("blue")
# Untuk mengaktifkan mode menggambar
turtle.pendown()
# Maju 100 satuan dari posisi awal
turtle.forward(100)
# Berputar 144 derajat ke kiri
turtle.left(144)
# Maju 200 satuan
turtle.forward(200)
# Berputar 144 derajat ke kiri
turtle.left(144)
# Baju 200 satuan
turtle.forward(200)
# Berputar 144 derajat ke kiri
turtle.left(144)
# Maju 200 satuan
turtle.forward(200)
# Berputar 144 derajat ke kiri
turtle.left(144)
# Maju 200 satuan
turtle.forward(200)
# Berputar 200 satuan ke kiri
turtle.left(144)
# Maju 100 satuan
turtle.forward(100)
# Membuat program turtle berhenti jika di klik
turtle.exitonclick() | true |
4b3cc1b6cdf517fa1c0c0845fe557cd713ffc46d | Python | Shaurya0802/C99 | /shutilfile.py | UTF-8 | 267 | 3.03125 | 3 | [] | no_license | import os
import shutil
path = "E:/Python/C99/folder"
print("Before Copying File: ")
print(os.listdir(path))
source = "E:/Python/C99/abc"
destination = "E:/Python/C99-test"
dest = shutil.move(source, destination)
print("After Copying file:")
print(os.listdir(path)) | true |