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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
1e79d24639d102051bd6214ecbf85ef44e7ca0ef | Python | pavancse17/user-activity | /user_activity/management/commands/dump_user_activity.py | UTF-8 | 1,607 | 2.671875 | 3 | [] | no_license | from datetime import timedelta
from random import randint
import pytz
from django.core.management.base import BaseCommand
import faker
from user_activity.models import User, ActivityPeriod
class Command(BaseCommand):
help = 'Generates some random fake data.'
faker.Faker.seed(0)
fake = faker.Faker()
def add_arguments(self, parser):
parser.add_argument('count', type=int)
def create_user(self):
profile = self.fake.simple_profile()
return User.objects.create_user(
id=self.fake.bothify(text='??#?##?##'),
username=profile["username"],
password="123",
email=profile["mail"],
is_active=True,
timezone=self.fake.timezone(),
real_name=profile["name"]
)
def create_max_of_10_activity_periods(self, user):
for _ in range(0, randint(0, 10)):
self.create_activity_period(user)
def create_activity_period(self, user):
start_time = self.fake.date_time(
tzinfo=pytz.timezone(self.fake.timezone()))
end_time = start_time + timedelta(minutes=30)
activity_period = ActivityPeriod.objects.create(
start_time=start_time,
end_time=end_time,
user=user
)
activity_period.save()
def handle(self, *args, **options):
for i in range(0, options['count']):
print('Created bummy %d users data out of %d...' %
(i+1, options["count"]))
user = self.create_user()
self.create_max_of_10_activity_periods(user)
| true |
63de754469cb15cbfdb521b80206399b66efa003 | Python | green-fox-academy/MartonG11 | /week-03/day-2/count_lines.py | UTF-8 | 662 | 4.03125 | 4 | [] | no_license | # Write a function that takes a filename as string,
# then returns the number of lines the file contains.
# It should return zero if it can't open the file, and
# should not raise any error.
my_file = open("my_file.txt", "w")
my_file.write("Apple\n Pear\n Grape\n Pineapple\n Beer")
my_file.close()
def contain_line(file):
try:
my_file = open("my_file.txt", "r")
with open("my_file.txt") as counting:
print(sum(1 for line in counting))
except IOError:
print(0)
contain_line(my_file)
my_file = open(filename, 'r')
with open(filename) as counting:
return(sum(1 for letter in counting)) | true |
5da85a3f92070e17f627096c64faf91b95b2d8f0 | Python | A03ki/uec_tl_markov | /uectl/models.py | UTF-8 | 2,138 | 3.640625 | 4 | [
"MIT"
] | permissive | import json
import markovify
class MarkovChainModel:
def __init__(self, model: markovify.NewlineText):
self.model = model
def generate_sentence(self, max_chars=140, **kwargs) -> str:
"`max_chars` 以内の文字列を生成する"
sentence = None
while sentence is None:
sentence = self.model.make_short_sentence(max_chars, **kwargs)
return sentence.replace(" ", "")
def generate_sentence_with_start(self, beginning: str, **kwargs) -> str:
"`beginning` で始まる文字列を生成する"
sentence = None
while sentence is None:
sentence = self.model.make_sentence_with_start(beginning, **kwargs)
return sentence.replace(" ", "")
@classmethod
def load_json(cls, path: str) -> "MarkovChainModel":
"JSON形式で学習済みモデルを読み込んだ後, 新しいクラスのインスタンスオブジェクトを作成して返す"
with open(path, "r") as f:
json_data = json.load(f)
model = markovify.NewlineText.from_json(json_data)
return cls(model)
def save_json(self, path: str, indent: int = 4) -> None:
"モデルをJSON形式で保存する"
json_data = self.model.to_json()
with open(path, "w") as f:
json.dump(json_data, f, indent=indent)
@classmethod
def train(cls, training_text: str,
state_size: int = 2) -> "MarkovChainModel":
"""モデルの学習後, 新しいクラスのインスタンスオブジェクトを作成して返す
Args:
training_text: モデルの学習に使用する文字列. 各単語は空白文字で
区切られている必要があり, 改行ごとに学習する.
state_size: Optional; 現在から過去までの考慮する状態のサイズ
"""
model = markovify.NewlineText(training_text, state_size=state_size)
return cls(model)
def compile(self, inplace: bool = False) -> None:
"モデルを軽量化する"
self.model = self.model.compile(inplace=inplace)
| true |
f3b8ef546c492decaa0997db6a5ffdbced6ee462 | Python | huimeizhex/leetcode | /RotateImage.py | UTF-8 | 1,536 | 3.46875 | 3 | [] | no_license | #!/usr/bin/env python
# coding=utf-8
class Solution(object):
def rotate(self, matrix):
self.my_rotate(matrix, 0, 0, len(matrix))
def rotate_vertical(self, matrix, x, y, n):
for i in xrange(0, n):
matrix[i+x][n+y], matrix[n+x][2*n-i+y] = matrix[n+x][2*n-i+y], matrix[i+x][n+y]
matrix[i+x][n+y], matrix[n+x][i+y] = matrix[n+x][i+y], matrix[i+x][n+y]
matrix[n+x][i+y], matrix[2*n-i+x][n+y] = matrix[2*n-i+x][n+y], matrix[n+x][i+y]
def rotate_matrix(self, matrix, x, y, n, m):
for i in xrange(0, m):
for j in xrange(0, m):
matrix[x+i][y+j], matrix[x+i][y+j+n] = matrix[x+i][y+j+n], matrix[x+i][y+j]
matrix[x+i+n][y+j], matrix[x+i][y+j] = matrix[x+i][y+j], matrix[x+i+n][y+j]
matrix[x+i+n][y+j], matrix[x+i+n][y+j+n] = matrix[x+i+n][y+j+n], matrix[x+i+n][y+j]
def my_rotate(self, matrix, x, y, n):
if n == 1:
return
trans = n/2
if n%2 == 1:
self.rotate_vertical(matrix, x, y, n/2)
trans += 1
self.rotate_matrix(matrix, x, y, trans, n/2)
self.my_rotate(matrix, x+trans, y, n/2)
self.my_rotate(matrix, x, y+trans, n/2)
self.my_rotate(matrix, x, y, n/2)
self.my_rotate(matrix, x+trans, y+trans, n/2)
if __name__ == "__main__":
num = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
so = Solution()
so.rotate(num)
print num
| true |
43bbadd48b37ca47690851a8802e6480b90dabe7 | Python | imaadzaffar/family-fitness | /main/models.py | UTF-8 | 1,795 | 2.53125 | 3 | [
"MIT"
] | permissive | import string
from accounts.models import User
from django import forms
from django.db import IntegrityError, models
from django.utils import timezone
from django.utils.crypto import get_random_string
# Create your models here.
class FitnessRecord(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
created = models.DateTimeField(default=timezone.now)
class CategoryChoices(models.TextChoices):
BIKE = 'Bike'
WALK = 'Walk'
RUN = 'Run'
SPORTS = 'Sports'
category = models.CharField(max_length=10, choices=CategoryChoices.choices, default=CategoryChoices.BIKE)
calories = models.IntegerField(default=100)
duration = models.DurationField(default='00:30:00', help_text='HH:MM:ss format')
def __str__(self):
return f'{self.user.name} | {self.category} | {self.calories}'
def generate_code():
return get_random_string(length=6, allowed_chars=string.ascii_lowercase + string.digits)
class Family(models.Model):
name = models.CharField(max_length=20, verbose_name='Family Name')
members = models.ManyToManyField(User)
code = models.CharField(max_length=6, blank=True, unique=True)
def save(self, *args, **kwargs):
if not self.code:
self.code = generate_code()
success = False
while not success:
try:
super(Family, self).save(*args, **kwargs)
except IntegrityError:
self.code = generate_code()
else:
success = True
class Meta:
verbose_name_plural = 'Families'
def __str__(self):
try:
return f'{self.name} | {self.members.all().count()} members | {self.code}'
except:
return f'{self.name} | {self.code}'
| true |
4a0a6e38c5fe760d90437553d6a1b13accba5c6f | Python | ojasvajain/HadoopSearchEngine | /backend/GenerateIndexReducer.py | UTF-8 | 1,694 | 3.15625 | 3 | [] | no_license | #!/usr/bin/env python
'''
Reducer Purpose: To produce inverted index and store it in a HBase Database,
1) Input format: Word,Frequency,FancyHitBit,DocId
2) Row Format: Word - DocId1(Freq,FHBit)$DocId2(Freq,FHBit)$...
3) Store the output row in hbase database
Everytime Mapreduce job is run, a new column is created in InvertedIndex table which stores the InvertedIndex string of that job.
Wanted to append to existing invertedIndex string but there was an unknown issue in modifying existing entries in hbase table.
'''
import fileinput
import happybase
connection = happybase.Connection('172.31.10.32') #ip of host running thrift server
table = connection.table('InvertedIndex')
prev_word = ''
isFirst = True
invertedIndexString = ''
def insertInTable(word,invertedIndexString): #insert in InvertedIndex table
invertedIndexString = invertedIndexString[:len(invertedIndexString)-1] #remove last $
row = table.row(word) #returns a dictionary
postings_no = len(row.keys())+1 #new inverted index string will be stored in a new column named ('postings' + postings_no)
table.put(word, {'cf:postings{0}'.format(postings_no) : invertedIndexString}) #insert into table
for line in fileinput.input(): #read input line by line. Input format is mentioned above.
items=line.strip().split('\t')
if(len(items)!=4):
continue
word,freq,fhbit,docid=items
if(prev_word!=word and isFirst==False):
insertInTable(prev_word,invertedIndexString)
invertedIndexString=''
invertedIndexString+="{0}({1},{2})$".format(docid,freq,fhbit)
prev_word=word
isFirst=False
insertInTable(prev_word,invertedIndexString) #to insert last word
connection.close()
| true |
8bb36809b6ad435ec79459b411aa53cd06f5c296 | Python | NREL/floris | /floris/tools/uncertainty_interface.py | UTF-8 | 30,200 | 2.78125 | 3 | [
"Apache-2.0"
] | permissive | # Copyright 2021 NREL
# 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.
# See https://floris.readthedocs.io for documentation
import copy
import numpy as np
from scipy.stats import norm
from floris.logging_manager import LoggerBase
from floris.tools import FlorisInterface
from floris.utilities import wrap_360
class UncertaintyInterface(LoggerBase):
def __init__(
self,
configuration,
unc_options=None,
unc_pmfs=None,
fix_yaw_in_relative_frame=False,
):
"""A wrapper around the nominal floris_interface class that adds
uncertainty to the floris evaluations. One can specify a probability
distribution function (pdf) for the ambient wind direction. Unless
the exact pdf is specified manually using the option 'unc_pmfs', a
Gaussian probability distribution function will be assumed.
Args:
configuration (:py:obj:`dict` or FlorisInterface object): The Floris
object, configuration dictarionary, or YAML file. The
configuration should have the following inputs specified.
- **flow_field**: See `floris.simulation.flow_field.FlowField` for more details.
- **farm**: See `floris.simulation.farm.Farm` for more details.
- **turbine**: See `floris.simulation.turbine.Turbine` for more details.
- **wake**: See `floris.simulation.wake.WakeManager` for more details.
- **logging**: See `floris.simulation.floris.Floris` for more details.
unc_options (dictionary, optional): A dictionary containing values
used to create normally-distributed, zero-mean probability mass
functions describing the distribution of wind direction deviations.
This argument is only used when **unc_pmfs** is None and contain
the following key-value pairs:
- **std_wd** (*float*): A float containing the standard
deviation of the wind direction deviations from the
original wind direction.
- **pmf_res** (*float*): A float containing the resolution in
degrees of the wind direction and yaw angle PMFs.
- **pdf_cutoff** (*float*): A float containing the cumulative
distribution function value at which the tails of the
PMFs are truncated.
Defaults to None. Initializes to {'std_wd': 4.95, 'pmf_res': 1.0,
'pdf_cutoff': 0.995}.
unc_pmfs (dictionary, optional): A dictionary containing optional
probability mass functions describing the distribution of wind
direction deviations. Contains the following key-value pairs:
- **wd_unc** (*np.array*): Wind direction deviations from the
original wind direction.
- **wd_unc_pmf** (*np.array*): Probability of each wind
direction deviation in **wd_unc** occuring.
Defaults to None, in which case default PMFs are calculated
using values provided in **unc_options**.
fix_yaw_in_relative_frame (bool, optional): When set to True, the
relative yaw angle of all turbines is fixed and always has the
nominal value (e.g., 0 deg) when evaluating uncertainty in the
wind direction. Evaluating wind direction uncertainty like this
will essentially come down to a Gaussian smoothing of FLORIS
solutions over the wind directions. This calculation can therefore
be really fast, since it does not require additional calculations
compared to a non-uncertainty FLORIS evaluation.
When fix_yaw_in_relative_frame=False, the yaw angles are fixed in
the absolute (compass) reference frame, meaning that for each
probablistic wind direction evaluation, our probablistic (relative)
yaw angle evaluated goes into the opposite direction. For example,
a probablistic wind direction 3 deg above the nominal value means
that we evaluate it with a relative yaw angle that is 3 deg below
its nominal value. This requires additional computations compared
to a non- uncertainty evaluation.
Typically, fix_yaw_in_relative_frame=True is used when comparing
FLORIS to historical data, in which a single measurement usually
represents a 10-minute average, and thus is often a mix of various
true wind directions. The inherent assumption then is that the turbine
perfectly tracks the wind direction changes within those 10 minutes.
Then, fix_yaw_in_relative_frame=False is typically used for robust
yaw angle optimization, in which we take into account that the turbine
often does not perfectly know the true wind direction, and that a
turbine often does not perfectly achieve its desired yaw angle offset.
Defaults to fix_yaw_in_relative_frame=False.
"""
if (unc_options is None) & (unc_pmfs is None):
# Default options:
unc_options = {
"std_wd": 3.0, # Standard deviation for inflow wind direction (deg)
"pmf_res": 1.0, # Resolution over which to calculate angles (deg)
"pdf_cutoff": 0.995, # Probability density function cut-off (-)
}
# Initialize floris object and uncertainty pdfs
if isinstance(configuration, FlorisInterface):
self.fi = configuration
else:
self.fi = FlorisInterface(configuration)
self.reinitialize_uncertainty(
unc_options=unc_options,
unc_pmfs=unc_pmfs,
fix_yaw_in_relative_frame=fix_yaw_in_relative_frame,
)
# Add a _no_wake switch to keep track of calculate_wake/calculate_no_wake
self._no_wake = False
# Private methods
def _generate_pdfs_from_dict(self):
"""Generates the uncertainty probability distributions from a
dictionary only describing the wd_std and yaw_std, and discretization
resolution.
"""
wd_unc = np.zeros(1)
wd_unc_pmf = np.ones(1)
# create normally distributed wd and yaw uncertaitny pmfs if appropriate
unc_options = self.unc_options
if unc_options["std_wd"] > 0:
wd_bnd = int(
np.ceil(
norm.ppf(unc_options["pdf_cutoff"], scale=unc_options["std_wd"])
/ unc_options["pmf_res"]
)
)
bound = wd_bnd * unc_options["pmf_res"]
wd_unc = np.linspace(-1 * bound, bound, 2 * wd_bnd + 1)
wd_unc_pmf = norm.pdf(wd_unc, scale=unc_options["std_wd"])
wd_unc_pmf /= np.sum(wd_unc_pmf) # normalize so sum = 1.0
unc_pmfs = {
"wd_unc": wd_unc,
"wd_unc_pmf": wd_unc_pmf,
}
# Save to self
self.unc_pmfs = unc_pmfs
def _expand_wind_directions_and_yaw_angles(self):
"""Expands the nominal wind directions and yaw angles to the full set
of conditions that need to be evaluated for the probablistic
calculation of the floris solutions. This produces the np.NDArrays
"wd_array_probablistic" and "yaw_angles_probablistic", with shapes:
(
num_wind_direction_pdf_points_to_evaluate,
num_nominal_wind_directions,
)
and
(
num_wind_direction_pdf_points_to_evaluate,
num_nominal_wind_directions,
num_nominal_wind_speeds,
num_turbines
),
respectively.
"""
# First initialize unc_pmfs from self
unc_pmfs = self.unc_pmfs
# We first save the nominal settings, since we will be overwriting
# the floris wind conditions and yaw angles to include all
# probablistic conditions.
wd_array_nominal = self.fi.floris.flow_field.wind_directions
yaw_angles_nominal = self.fi.floris.farm.yaw_angles
# Expand wind direction and yaw angle array into the direction
# of uncertainty over the ambient wind direction.
wd_array_probablistic = np.vstack([
np.expand_dims(wd_array_nominal, axis=0) + dy
for dy in unc_pmfs["wd_unc"]
])
if self.fix_yaw_in_relative_frame:
# The relative yaw angle is fixed and always has the nominal
# value (e.g., 0 deg) when evaluating uncertainty. Evaluating
# wind direction uncertainty like this would essentially come
# down to a Gaussian smoothing of FLORIS solutions over the
# wind directions. This can also be really fast, since it would
# not require any additional calculations compared to the
# non-uncertainty FLORIS evaluation.
yaw_angles_probablistic = np.vstack([
np.expand_dims(yaw_angles_nominal, axis=0)
for _ in unc_pmfs["wd_unc"]
])
else:
# Fix yaw angles in the absolute (compass) reference frame,
# meaning that for each probablistic wind direction evaluation,
# our probablistic (relative) yaw angle evaluated goes into
# the opposite direction. For example, a probablistic wind
# direction 3 deg above the nominal value means that we evaluate
# it with a relative yaw angle that is 3 deg below its nominal
# value.
yaw_angles_probablistic = np.vstack([
np.expand_dims(yaw_angles_nominal, axis=0) - dy
for dy in unc_pmfs["wd_unc"]
])
self.wd_array_probablistic = wd_array_probablistic
self.yaw_angles_probablistic = yaw_angles_probablistic
def _reassign_yaw_angles(self, yaw_angles=None):
# Overwrite the yaw angles in the FlorisInterface object
if yaw_angles is not None:
self.fi.floris.farm.yaw_angles = yaw_angles
# Public methods
def copy(self):
"""Create an independent copy of the current UncertaintyInterface
object"""
fi_unc_copy = copy.deepcopy(self)
fi_unc_copy.fi = self.fi.copy()
return fi_unc_copy
def reinitialize_uncertainty(
self,
unc_options=None,
unc_pmfs=None,
fix_yaw_in_relative_frame=None
):
"""Reinitialize the wind direction and yaw angle probability
distributions used in evaluating FLORIS. Must either specify
'unc_options', in which case distributions are calculated assuming
a Gaussian distribution, or `unc_pmfs` must be specified directly
assigning the probability distribution functions.
Args:
unc_options (dictionary, optional): A dictionary containing values
used to create normally-distributed, zero-mean probability mass
functions describing the distribution of wind direction and yaw
position deviations when wind direction and/or yaw position
uncertainty is included. This argument is only used when
**unc_pmfs** is None and contains the following key-value pairs:
- **std_wd** (*float*): A float containing the standard
deviation of the wind direction deviations from the
original wind direction.
- **std_yaw** (*float*): A float containing the standard
deviation of the yaw angle deviations from the original yaw
angles.
- **pmf_res** (*float*): A float containing the resolution in
degrees of the wind direction and yaw angle PMFs.
- **pdf_cutoff** (*float*): A float containing the cumulative
distribution function value at which the tails of the
PMFs are truncated.
Defaults to None.
unc_pmfs (dictionary, optional): A dictionary containing optional
probability mass functions describing the distribution of wind
direction and yaw position deviations when wind direction and/or
yaw position uncertainty is included in the power calculations.
Contains the following key-value pairs:
- **wd_unc** (*np.array*): Wind direction deviations from the
original wind direction.
- **wd_unc_pmf** (*np.array*): Probability of each wind
direction deviation in **wd_unc** occuring.
- **yaw_unc** (*np.array*): Yaw angle deviations from the
original yaw angles.
- **yaw_unc_pmf** (*np.array*): Probability of each yaw angle
deviation in **yaw_unc** occuring.
Defaults to None.
fix_yaw_in_relative_frame (bool, optional): When set to True, the
relative yaw angle of all turbines is fixed and always has the
nominal value (e.g., 0 deg) when evaluating uncertainty in the
wind direction. Evaluating wind direction uncertainty like this
will essentially come down to a Gaussian smoothing of FLORIS
solutions over the wind directions. This calculation can therefore
be really fast, since it does not require additional calculations
compared to a non-uncertainty FLORIS evaluation.
When fix_yaw_in_relative_frame=False, the yaw angles are fixed in
the absolute (compass) reference frame, meaning that for each
probablistic wind direction evaluation, our probablistic (relative)
yaw angle evaluated goes into the opposite direction. For example,
a probablistic wind direction 3 deg above the nominal value means
that we evaluate it with a relative yaw angle that is 3 deg below
its nominal value. This requires additional computations compared
to a non- uncertainty evaluation.
Typically, fix_yaw_in_relative_frame=True is used when comparing
FLORIS to historical data, in which a single measurement usually
represents a 10-minute average, and thus is often a mix of various
true wind directions. The inherent assumption then is that the turbine
perfectly tracks the wind direction changes within those 10 minutes.
Then, fix_yaw_in_relative_frame=False is typically used for robust
yaw angle optimization, in which we take into account that the turbine
often does not perfectly know the true wind direction, and that a
turbine often does not perfectly achieve its desired yaw angle offset.
Defaults to fix_yaw_in_relative_frame=False.
"""
# Check inputs
if (unc_options is not None) and (unc_pmfs is not None):
self.logger.error("Must specify either 'unc_options' or 'unc_pmfs', not both.")
# Assign uncertainty probability distributions
if unc_options is not None:
self.unc_options = unc_options
self._generate_pdfs_from_dict()
if unc_pmfs is not None:
self.unc_pmfs = unc_pmfs
if fix_yaw_in_relative_frame is not None:
self.fix_yaw_in_relative_frame = bool(fix_yaw_in_relative_frame)
def reinitialize(
self,
wind_speeds=None,
wind_directions=None,
wind_shear=None,
wind_veer=None,
reference_wind_height=None,
turbulence_intensity=None,
air_density=None,
layout_x=None,
layout_y=None,
turbine_type=None,
solver_settings=None,
):
"""Pass to the FlorisInterface reinitialize function. To allow users
to directly replace a FlorisInterface object with this
UncertaintyInterface object, this function is required."""
# Just passes arguments to the floris object
self.fi.reinitialize(
wind_speeds=wind_speeds,
wind_directions=wind_directions,
wind_shear=wind_shear,
wind_veer=wind_veer,
reference_wind_height=reference_wind_height,
turbulence_intensity=turbulence_intensity,
air_density=air_density,
layout_x=layout_x,
layout_y=layout_y,
turbine_type=turbine_type,
solver_settings=solver_settings,
)
def calculate_wake(self, yaw_angles=None):
"""Replaces the 'calculate_wake' function in the FlorisInterface
object. Fundamentally, this function only overwrites the nominal
yaw angles in the FlorisInterface object. The actual wake calculations
are performed once 'get_turbine_powers' or 'get_farm_powers' is
called. However, to allow users to directly replace a FlorisInterface
object with this UncertaintyInterface object, this function is
required.
Args:
yaw_angles: NDArrayFloat | list[float] | None = None,
"""
self._reassign_yaw_angles(yaw_angles)
self._no_wake = False
def calculate_no_wake(self, yaw_angles=None):
"""Replaces the 'calculate_no_wake' function in the FlorisInterface
object. Fundamentally, this function only overwrites the nominal
yaw angles in the FlorisInterface object. The actual wake calculations
are performed once 'get_turbine_powers' or 'get_farm_powers' is
called. However, to allow users to directly replace a FlorisInterface
object with this UncertaintyInterface object, this function is
required.
Args:
yaw_angles: NDArrayFloat | list[float] | None = None,
"""
self._reassign_yaw_angles(yaw_angles)
self._no_wake = True
def get_turbine_powers(self):
"""Calculates the probability-weighted power production of each
turbine in the wind farm.
Returns:
NDArrayFloat: Power production of all turbines in the wind farm.
This array has the shape (num_wind_directions, num_wind_speeds,
num_turbines).
"""
# To include uncertainty, we expand the dimensionality
# of the problem along the wind direction pdf and/or yaw angle
# pdf. We make use of the vectorization of FLORIS to
# evaluate all conditions in a single call, rather than in
# loops. Therefore, the effective number of wind conditions and
# yaw angle combinations we evaluate expands.
unc_pmfs = self.unc_pmfs
self._expand_wind_directions_and_yaw_angles()
# Get dimensions of nominal conditions
wd_array_nominal = self.fi.floris.flow_field.wind_directions
num_wd = self.fi.floris.flow_field.n_wind_directions
num_ws = self.fi.floris.flow_field.n_wind_speeds
num_wd_unc = len(unc_pmfs["wd_unc"])
num_turbines = self.fi.floris.farm.n_turbines
# Format into conventional floris format by reshaping
wd_array_probablistic = np.reshape(self.wd_array_probablistic, -1)
yaw_angles_probablistic = np.reshape(
self.yaw_angles_probablistic,
(-1, num_ws, num_turbines)
)
# Wrap wind direction array around 360 deg
wd_array_probablistic = wrap_360(wd_array_probablistic)
# Find minimal set of solutions to evaluate
wd_exp = np.tile(wd_array_probablistic, (1, num_ws, 1)).T
_, id_unq, id_unq_rev = np.unique(
np.append(yaw_angles_probablistic, wd_exp, axis=2),
axis=0,
return_index=True,
return_inverse=True
)
wd_array_probablistic_min = wd_array_probablistic[id_unq]
yaw_angles_probablistic_min = yaw_angles_probablistic[id_unq, :, :]
# Evaluate floris for minimal probablistic set
self.fi.reinitialize(wind_directions=wd_array_probablistic_min)
if self._no_wake:
self.fi.calculate_no_wake(yaw_angles=yaw_angles_probablistic_min)
else:
self.fi.calculate_wake(yaw_angles=yaw_angles_probablistic_min)
# Retrieve all power productions using the nominal call
turbine_powers = self.fi.get_turbine_powers()
self.fi.reinitialize(wind_directions=wd_array_nominal)
# Reshape solutions back to full set
power_probablistic = turbine_powers[id_unq_rev, :]
power_probablistic = np.reshape(
power_probablistic,
(num_wd_unc, num_wd, num_ws, num_turbines)
)
# Calculate probability weighing terms
wd_weighing = (
(np.expand_dims(unc_pmfs["wd_unc_pmf"], axis=(1, 2, 3)))
.repeat(num_wd, 1)
.repeat(num_ws, 2)
.repeat(num_turbines, 3)
)
# Now apply probability distribution weighing to get turbine powers
return np.sum(wd_weighing * power_probablistic, axis=0)
def get_farm_power(self, turbine_weights=None):
"""Calculates the probability-weighted power production of the
collective of all turbines in the farm, for each wind direction
and wind speed specified.
Args:
turbine_weights (NDArrayFloat | list[float] | None, optional):
weighing terms that allow the user to emphasize power at
particular turbines and/or completely ignore the power
from other turbines. This is useful when, for example, you are
modeling multiple wind farms in a single floris object. If you
only want to calculate the power production for one of those
farms and include the wake effects of the neighboring farms,
you can set the turbine_weights for the neighboring farms'
turbines to 0.0. The array of turbine powers from floris
is multiplied with this array in the calculation of the
objective function. If None, this is an array with all values
1.0 and with shape equal to (n_wind_directions, n_wind_speeds,
n_turbines). Defaults to None.
Returns:
NDArrayFloat: Expectation of power production of the wind farm.
This array has the shape (num_wind_directions, num_wind_speeds).
"""
if turbine_weights is None:
# Default to equal weighing of all turbines when turbine_weights is None
turbine_weights = np.ones(
(
self.floris.flow_field.n_wind_directions,
self.floris.flow_field.n_wind_speeds,
self.floris.farm.n_turbines
)
)
elif len(np.shape(turbine_weights)) == 1:
# Deal with situation when 1D array is provided
turbine_weights = np.tile(
turbine_weights,
(
self.floris.flow_field.n_wind_directions,
self.floris.flow_field.n_wind_speeds,
1
)
)
# Calculate all turbine powers and apply weights
turbine_powers = self.get_turbine_powers()
turbine_powers = np.multiply(turbine_weights, turbine_powers)
return np.sum(turbine_powers, axis=2)
def get_farm_AEP(
self,
freq,
cut_in_wind_speed=0.001,
cut_out_wind_speed=None,
yaw_angles=None,
turbine_weights=None,
no_wake=False,
) -> float:
"""
Estimate annual energy production (AEP) for distributions of wind speed, wind
direction, frequency of occurrence, and yaw offset.
Args:
freq (NDArrayFloat): NumPy array with shape (n_wind_directions,
n_wind_speeds) with the frequencies of each wind direction and
wind speed combination. These frequencies should typically sum
up to 1.0 and are used to weigh the wind farm power for every
condition in calculating the wind farm's AEP.
cut_in_wind_speed (float, optional): Wind speed in m/s below which
any calculations are ignored and the wind farm is known to
produce 0.0 W of power. Note that to prevent problems with the
wake models at negative / zero wind speeds, this variable must
always have a positive value. Defaults to 0.001 [m/s].
cut_out_wind_speed (float, optional): Wind speed above which the
wind farm is known to produce 0.0 W of power. If None is
specified, will assume that the wind farm does not cut out
at high wind speeds. Defaults to None.
yaw_angles (NDArrayFloat | list[float] | None, optional):
The relative turbine yaw angles in degrees. If None is
specified, will assume that the turbine yaw angles are all
zero degrees for all conditions. Defaults to None.
turbine_weights (NDArrayFloat | list[float] | None, optional):
weighing terms that allow the user to emphasize power at
particular turbines and/or completely ignore the power
from other turbines. This is useful when, for example, you are
modeling multiple wind farms in a single floris object. If you
only want to calculate the power production for one of those
farms and include the wake effects of the neighboring farms,
you can set the turbine_weights for the neighboring farms'
turbines to 0.0. The array of turbine powers from floris
is multiplied with this array in the calculation of the
objective function. If None, this is an array with all values
1.0 and with shape equal to (n_wind_directions, n_wind_speeds,
n_turbines). Defaults to None.
no_wake: (bool, optional): When *True* updates the turbine
quantities without calculating the wake or adding the wake to
the flow field. This can be useful when quantifying the loss
in AEP due to wakes. Defaults to *False*.
Returns:
float:
The Annual Energy Production (AEP) for the wind farm in
watt-hours.
"""
# Verify dimensions of the variable "freq"
if not (
(np.shape(freq)[0] == self.floris.flow_field.n_wind_directions)
& (np.shape(freq)[1] == self.floris.flow_field.n_wind_speeds)
& (len(np.shape(freq)) == 2)
):
raise UserWarning(
"'freq' should be a two-dimensional array with dimensions "
"(n_wind_directions, n_wind_speeds)."
)
# Check if frequency vector sums to 1.0. If not, raise a warning
if np.abs(np.sum(freq) - 1.0) > 0.001:
self.logger.warning(
"WARNING: The frequency array provided to get_farm_AEP() does not sum to 1.0. "
)
# Copy the full wind speed array from the floris object and initialize
# the the farm_power variable as an empty array.
wind_speeds = np.array(self.fi.floris.flow_field.wind_speeds, copy=True)
farm_power = np.zeros((self.fi.floris.flow_field.n_wind_directions, len(wind_speeds)))
# Determine which wind speeds we must evaluate in floris
conditions_to_evaluate = wind_speeds >= cut_in_wind_speed
if cut_out_wind_speed is not None:
conditions_to_evaluate = conditions_to_evaluate & (wind_speeds < cut_out_wind_speed)
# Evaluate the conditions in floris
if np.any(conditions_to_evaluate):
wind_speeds_subset = wind_speeds[conditions_to_evaluate]
yaw_angles_subset = None
if yaw_angles is not None:
yaw_angles_subset = yaw_angles[:, conditions_to_evaluate]
self.reinitialize(wind_speeds=wind_speeds_subset)
if no_wake:
self.calculate_no_wake(yaw_angles=yaw_angles_subset)
else:
self.calculate_wake(yaw_angles=yaw_angles_subset)
farm_power[:, conditions_to_evaluate] = (
self.get_farm_power(turbine_weights=turbine_weights)
)
# Finally, calculate AEP in GWh
aep = np.sum(np.multiply(freq, farm_power) * 365 * 24)
# Reset the FLORIS object to the full wind speed array
self.reinitialize(wind_speeds=wind_speeds)
return aep
def assign_hub_height_to_ref_height(self):
return self.fi.assign_hub_height_to_ref_height()
def get_turbine_layout(self, z=False):
return self.fi.get_turbine_layout(z=z)
def get_turbine_Cts(self):
return self.fi.get_turbine_Cts()
def get_turbine_ais(self):
return self.fi.get_turbine_ais()
def get_turbine_average_velocities(self):
return self.fi.get_turbine_average_velocities()
# Define getter functions that just pass information from FlorisInterface
@property
def floris(self):
return self.fi.floris
@property
def layout_x(self):
return self.fi.layout_x
@property
def layout_y(self):
return self.fi.layout_y
| true |
7b7ec58474717cfc58e7fe7a5c576514232e71bd | Python | Aasthaengg/IBMdataset | /Python_codes/p03555/s135085854.py | UTF-8 | 123 | 3.015625 | 3 | [] | no_license | c = str(input())
d = str(input())
if c[0] == d[2] and c[1] == d[1] and c[2] == d[0]:
print('YES')
else:
print('NO') | true |
58aa68a2d5da255f84cd29a9784176410aa25262 | Python | narinn-star/Python | /Python 300/09. Function/211.py | UTF-8 | 81 | 3.046875 | 3 | [] | no_license | #functions _ 함수 호출
def f(string):
print(string)
f("안녕")
f("Hi") | true |
4b734b8264ef5d4dac96260df5ca68fa2ec1269c | Python | chjfth/trivials | /python/UASYNCPY/CH3/p40-future-chj1.py | UTF-8 | 916 | 2.78125 | 3 | [] | no_license | #!/usr/bin/env python3
#coding: utf-8
# [2021-01-15] Chj tested with Python 3.7.4
import asyncio
async def main(f: asyncio.Future):
print("In main(), before sleep.")
await asyncio.sleep(1)
print("In main(), after sleep.")
f.set_result('I have finished.')
# With this, statement, at SPOT-A,
# fut.done() will be True and tsk.done() will be false.
await asyncio.sleep(0.01)
loop = asyncio.get_event_loop()
fut = asyncio.Future()
print("init fut.done()=", fut.done()) # False
coro = main(fut)
tsk = loop.create_task(coro)
# <Task pending name='Task-1' coro=<main() running at <console>:1>>
cpt = loop.run_until_complete(fut)
# cpt will be 'I have finished.'
print("* fut.done()=", fut.done()) # True
print("* tsk.done()=", tsk.done()) # False
# SPOT-A
print(fut.result())
# A second run of
# loop.run_until_complete(fut)
# or
# loop.run_until_complete(tsk)
# here, will change tsk.done() to True.
| true |
efbdbc032045795b71de1b8997d558fff24e1c5b | Python | KaranAhuja94/FST-M1 | /Python/Activities/Activity20.py | UTF-8 | 303 | 3.421875 | 3 | [] | no_license | import pandas
dataframe = pandas.read_excel("UserDetails.xlsx")
print("User Details: ")
print(dataframe)
print("Number of rows and columns: ", dataframe.shape)
print("Email ids: ")
print(dataframe["Email"])
print("Sorted in ascending order: ")
print(dataframe.sort_values("FirstName")) | true |
8536c2888f35cc401825458eb198962be315cf07 | Python | juan250897/Prueba-_Tecnica_TSAKANA | /1_python_flask/main.py | UTF-8 | 8,178 | 2.53125 | 3 | [] | no_license | import os
from flask import Flask,redirect,url_for, render_template,request,flash
from datetime import datetime
from flask_mysqldb import MySQL
app= Flask(__name__)
app.secret_key ='clave_secreta_flask'
#context procesor
@app.context_processor
def date_now():
return{
'now':datetime.utcnow()
}
#endpoints
#conexion DB
app.config['MYSQL_HOST'] ='localhost'
app.config['MYSQL_USER'] ='root'
app.config['MYSQL_PASSWORD'] =''
app.config['MYSQL_DB'] = 'prueba_tecnica_tsakana'
mysql = MySQL(app)
@app.route('/')
#para registar
def index():
return render_template('index.html')
@app.route('/registrar-productos', methods=['GET','POST'])
def registrar_productos ():
if request.method == 'POST':
categoria = request.form['categoria']
nombre = request.form['nombre']
precio = request.form['precio']
cantidad = request.form['cantidad']
estado = request.form['estado']
cursor = mysql.connection.cursor()
cursor.execute("INSERT INTO productos VALUES(NULL,%s,%s,%s,%s,%s)",(categoria, nombre, precio, cantidad, estado))
cursor.connection.commit()
flash('Has agregado el producto correctamente!!')
return redirect(url_for('registrar_productos'))
return render_template('registrar_producto.html')
@app.route('/registrar-clientes/',methods=['GET','POST'])
def registrar_clientes():
if request.method == 'POST':
cedula = request.form['cedula']
nombre = request.form['nombre']
direccion = request.form['direccion']
telefono = request.form['telefono']
cursor = mysql.connection.cursor()
cursor.execute("INSERT INTO clientes VALUES(%s,%s,%s,%s)",(cedula, nombre, direccion, telefono))
cursor.connection.commit()
flash('Has agregado un cliente correctamente!!')
return redirect(url_for('registrar_clientes'))
return render_template('registrar_cliente.html')
@app.route('/registrar-facturas',methods=['GET','POST'])
def registrar_facturas ():
if request.method == 'POST':
cliente = request.form['cliente']
productos = request.form['productos']
cantidad = request.form['cantidad']
fecha = request.form['fecha']
total = request.form['total']
metodo_pago = request.form['metodo_pago']
cursor = mysql.connection.cursor()
cursor.execute("INSERT INTO facturas VALUES(NULL,%s,%s,%s,%s,%s,%s)",(cliente, productos, cantidad, fecha,total,metodo_pago))
cursor.connection.commit()
flash('Has agregado una factura correctamente!!')
return redirect(url_for('registrar_facturas'))
return render_template('registrar_factura.html')
#para ver listas
@app.route('/productos')
def productos():
cursor = mysql.connection.cursor()
cursor.execute("SELECT * FROM productos")
productos = cursor.fetchall()
cursor.close()
return render_template('productos.html', productos = productos)
@app.route('/clientes')
def clientes():
cursor = mysql.connection.cursor()
cursor.execute("SELECT * FROM clientes")
clientes = cursor.fetchall()
cursor.close()
return render_template('clientes.html', clientes = clientes)
@app.route('/facturas')
def facturas():
cursor = mysql.connection.cursor()
cursor.execute("SELECT * FROM facturas")
facturas = cursor.fetchall()
cursor.close()
return render_template('facturas.html', facturas = facturas)
#para borrar clientes
@app.route('/borrar-clientes/<int:cedula_id>')
def borrar_cliente(cedula_id):
cursor = mysql.connection.cursor()
cursor.execute(f"DELETE FROM clientes WHERE cedula= {cedula_id}")
cursor.connection.commit()
flash('Has borrado el cliente correctamente')
return redirect (url_for('clientes'))
#para ver pagina de detalle
@app.route('/producto/<producto_id>')
def producto(producto_id):
cursor = mysql.connection.cursor()
cursor.execute("SELECT * FROM productos WHERE codigo =%s",[producto_id])
producto= cursor.fetchall()
cursor.close()
return render_template('producto.html', producto = producto[0])
@app.route('/cliente/<cedula_id>')
def cliente(cedula_id):
cursor = mysql.connection.cursor()
cursor.execute("SELECT * FROM clientes WHERE cedula =%s",[cedula_id])
cliente= cursor.fetchall()
cursor.close()
return render_template('cliente.html', cliente = cliente[0])
@app.route('/factura/<factura_id>')
def factura(factura_id):
cursor = mysql.connection.cursor()
cursor.execute("SELECT * FROM facturas WHERE codigo =%s",[factura_id])
factura= cursor.fetchall()
cursor.close()
return render_template('factura.html', factura = factura[0])
#para editar productos
@app.route('/editar-producto/<producto_id>', methods = ['GET','POST'])
def editar_producto(producto_id):
if request.method == 'POST':
categoria = request.form['categoria']
nombre = request.form['nombre']
precio = request.form['precio']
cantidad = request.form['cantidad']
estado = request.form['estado']
cursor = mysql.connection.cursor()
cursor.execute("""
UPDATE productos
SET categoria = %s,
nombre =%s,
precio = %s,
cantidad = %s,
estado =%s
WHERE codigo = %s
""",(categoria, nombre ,precio, cantidad, estado, producto_id))
cursor.connection.commit()
flash('Has editado el producto correctamente!!')
return redirect(url_for('productos'))
cursor = mysql.connection.cursor()
cursor.execute("SELECT * FROM productos WHERE codigo =%s",[producto_id])
producto= cursor.fetchall()
cursor.close()
return render_template('registrar_producto.html', producto = producto[0])
@app.route('/editar-cliente/<cedula_id>', methods = ['GET','POST'])
def editar_cliente(cedula_id):
if request.method == 'POST':
nombre = request.form['nombre']
direccion = request.form['direccion']
telefono = request.form['telefono']
cursor = mysql.connection.cursor()
cursor.execute("""
UPDATE clientes
SET nombre = %s,
direccion = %s,
telefono =%s
WHERE cedula = %s
""",(nombre, direccion, telefono,cedula_id))
cursor.connection.commit()
flash('Has editado el cliente correctamente!!')
return redirect(url_for('clientes'))
cursor = mysql.connection.cursor()
cursor.execute("SELECT * FROM clientes WHERE cedula =%s",[cedula_id])
cliente= cursor.fetchall()
cursor.close()
return render_template('registrar_cliente.html', cliente = cliente[0])
@app.route('/editar-factura/<factura_id>', methods = ['GET','POST'])
def editar_factura(factura_id):
if request.method == 'POST':
cliente = request.form['cliente']
productos = request.form['productos']
cantidad = request.form['cantidad']
fecha = request.form['fecha']
total = request.form['total']
metodo_pago = request.form['metodo_pago']
cursor = mysql.connection.cursor()
cursor.execute("""
UPDATE facturas
SET cliente = %s,
productos = %s,
cantidad =%s,
fecha =%s,
total =%s,
metodo_pago =%s
WHERE codigo = %s
""",(cliente, productos, cantidad, fecha,total,metodo_pago,factura_id))
cursor.connection.commit()
flash('Has editado la factura correctamente!!')
return redirect(url_for('facturas'))
cursor = mysql.connection.cursor()
cursor.execute("SELECT * FROM facturas WHERE codigo =%s",[factura_id])
factura= cursor.fetchall()
cursor.close()
return render_template('registrar_factura.html', factura = factura[0])
if __name__ == '__main__':
app.run(debug=True)
| true |
96b98196bd977611faaa0cd6b6b3abbad8e06898 | Python | ShenXiaoJun/tf-work | /p41.py | UTF-8 | 963 | 2.953125 | 3 | [] | no_license | #encoding:utf-8
import tensorflow as tf
g1 = tf.Graph()
with g1.as_default():
# 在计算图g1中定义变量"v",并设置初始值为0
v = tf.get_variable("v", shape=[1], initializer=tf.zeros_initializer)
g2 = tf.Graph()
with g2.as_default():
#在计算图g2中定义变量"v",并设置初始值为1
v = tf.get_variable("v", shape=[1], initializer =tf.ones_initializer)
#在计算图g1中读取变量"v"的取值
with tf.Session(graph=g1) as sess:
tf.initialize_all_variables().run()
with tf.variable_scope("", reuse=True):
print("shenxj")
#在计算图g1中,变量"v"的取值应该为0,所以下面这行会输出[0.]
print(sess.run(tf.get_variable("v")))
#在计算图g2中读取变量"v"的取值
with tf.Session(graph=g2) as sess:
tf.initialize_all_variables().run()
with tf.variable_scope("", reuse=True):
#在计算图g2中,变量"v"的取值应该为1,所以下面这行会输出[1.]
print(sess.run(tf.get_variable("v")))
| true |
be058701f8fd91223107b8ff2a3672900adf74a3 | Python | yuftlens1/base_2 | /模块之导入使用.py | UTF-8 | 417 | 3.046875 | 3 | [] | no_license | # # import 包名.模块名 #导入包。
# import mypackage.test1,mypackage.test2
#
# # 包名.模块.功能() 调用功能
# mypackage.test1.info_print1()
# mypackage.test2.info_print2()
from mypackage import *
test1.info_print1()
test2.info_print2() #在包里的init文件里做了__all__ = ['test1'] 以控制 from mypackage import * 这样的导入方式。
| true |
e6301ee81d17e008cc45cceb1fc8562366f4d1b7 | Python | apyaks123/python_data_skim_trimp | /data_skim_trim.py | UTF-8 | 6,471 | 3.140625 | 3 | [] | no_license | import math
# Global variables
str = []
def readFile():
count = -1
with open("quotes.txt") as fp:
Lines = fp.readlines()
for line in Lines:
count += 1
x = {count, line.strip()}
str.append(line)
print("-------------------------------------------")
print("Line{}: {}".format(count, line.strip()))
def init():
self.next = None
data = None
return self
def add(self,data):
current = self
while current != None & current.next != None:
self.data = item
current = current.next
return self.data
def macromenu():
global item
print("-------------------------------------------")
print("-------------------------------------------")
#print("Please enter 1 - 9, to select which line you want to skim and trim. Thank you!!!")
keyboard = int(input("Please enter 0 - 9, to select which line you want to skim and trim:"))
print(keyboard)
print("-------------------------------------------")
print("-------------------------------------------")
if (keyboard == 0):
item = str[0]
print(item)
return item
elif (keyboard == 1):
item = str[1]
print(str[1])
return item
elif (keyboard == 2):
item = str[2]
print(str[2])
return item
elif (keyboard == 3):
item = str[3]
print(str[3])
return item
elif (keyboard == 4):
item = str[4]
print(str[4])
return item
elif (keyboard == 5):
item = str[5]
print(str[5])
return item
elif (keyboard == 6):
item = str[6]
print(str[6])
return item
elif (keyboard == 7):
item = str[7]
print(str[7])
return item
elif (keyboard == 8):
item = str[8]
print(str[8])
return item
elif (keyboard == 9):
item = str[9]
print(str[9])
return item
else:
"Please enter value from 0-9 and try again. Thank you!!!!"
macromenu()
def skim():
global skim
print("-------------------------------------------")
print("-------------------------------------------")
skim = int(input("Please enter 0 - 2, to select how many n to to skim:"))
print("-------------------------------------------")
print("-------------------------------------------")
return skim
def trim():
global trim
print("-------------------------------------------")
print("-------------------------------------------")
trim = int(input("Please enter 0 - 2, to select how many n to to grams/trims:"))
print("-------------------------------------------")
print("-------------------------------------------")
return trim
def skimTrim():
global sss
f = open('nskipmgram_quotes.txt', 'a+')
f.write("-------------------------------------------\n")
f.write("-------------------------------------------\n")
f.write('sentence: ' + item)
print('in skim trim')
if item:
if skim:
if trim:
x = item.split()
print(len(x))
y = skim
z = trim
w = len(x)
p = w/(y + z)
k = math.ceil(p)
leng = k + 1
print(leng)
#print(y)
f.write('Output of' + repr(y) + '-skip' + '-' + repr(z) + '-grams:\n')
f.write('Output sentence: ')
if (trim == 2):
counter = 0
index = 0
while (leng >= counter):
counter += 1
#f.write('This is a test\n')
f.write(x[index] + ' ' + x[w - (y + z - index + 1)] + ',')
print(x[index] + ' ' + x[w - (y + z - index + 1)] + ',')
#sss = (x[index] + ' ' + x[w - (y + z - index)] + ',')
#print >> f, sss
#print(sss)
index += 1
elif (trim == 3):
counter = 0
index = 0
## while (leng >= counter):
## counter += 1
#f.write('This is a test\n')
f.write(x[0] + ' ' + x[w - (y + z - 1)] + ' ' + x[w + 2 - (y + z - 2)] + ' ')
print(x[0] + ' ' + x[w - (y + z - 1)] + ' ' + x[w + 2 - (y + z - 2)] + ' ')
#sss = (x[index] + ' ' + x[w - (y + z - index)] + ',')
#print >> f, sss
#print(sss)
## index += 1
##
f.write("\n-------------------------------------------\n")
f.write("-------------------------------------------\n")
f.close()
def main():
readFile()
macromenu()
skim()
trim()
skimTrim()
main()
| true |
bfad4b29f72605a5ac81f7026b0cac63c07669d2 | Python | ingong/Algorithm_Python | /CodeUp/5-1:1차원배열/1402.py | UTF-8 | 200 | 3.3125 | 3 | [] | no_license | N = int(input())
numList = list(map(int, input().split()))
for item in numList[::-1]:
print(item, end=" ")
# 내 풀이
# for i in range(len(numList)-1, -1, -1):
# print(numList[i], end=" ") | true |
ed49d0d7c23a5529ddf64671d0d791b6039b6d02 | Python | sbobovyc/Tracker | /src/menubar.py | UTF-8 | 2,760 | 2.78125 | 3 | [] | no_license | """
Created on July 13, 2011
@author: sbobovyc
"""
try:
# Python2
import Tkinter as tk
except ImportError:
# Python3
import tkinter as tk
import tkFileDialog
import os
class GUI_menubar(tk.Menu):
def __init__(self, parent, controller):
self.parent = parent
self.name = "menubar"
self.controller = controller
self.controller.register(self, self.name)
# file types
self.file_types = [('all files', '.*'), ('', '.shp')]
# create a menu
tk.Menu.__init__(self, parent)
filemenu = tk.Menu(self, tearoff=0)
self.add_cascade(label="File", menu=filemenu)
# filemenu.add_command(label="New Project", command=self.callback())
# filemenu.add_command(label="Open Project", command=self.callback())
filemenu.add_command(label="Add Shapefile...", command=self.file_add_shapefile)
filemenu.add_command(label="Add Raster...", command=self.file_add_raster)
filemenu.add_command(label="Open...", command=self.file_open)
filemenu.add_command(label="Render", command=self.file_render)
# filemenu.add_command(label="Save", command=self.callback())
# filemenu.add_command(label="Save as", command=self.file_save)
# filemenu.add_command(label="Save Layers", command=self.file_save_layer)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=self.exit_callback)
helpmenu = tk.Menu(self, tearoff=0)
self.add_cascade(label="Help", menu=helpmenu)
helpmenu.add_command(label="About...", command=self.callback)
def callback(self):
print "called the callback!"
def file_open(self):
source_image_path = tkFileDialog.askopenfilename()
self.controller.open_image(source_image_path)
def file_add_shapefile(self):
source_path = tkFileDialog.askopenfilename()
self.controller.add_shapefile(source_path)
def file_add_raster(self):
source_path = tkFileDialog.askopenfilename()
self.controller.add_raster(source_path)
def file_render(self):
self.controller.render()
def file_save(self):
output_image_path = tkFileDialog.asksaveasfilename(filetypes=self.file_types)
self.controller.save_image(output_image_path)
def file_save_layer(self):
output_path = tkFileDialog.asksaveasfilename(filetypes=self.file_types)
basename, extension = os.path.splitext(output_path)
self.controller.save_layers(basename, extension)
def exit_callback(self):
self.parent.quit()
| true |
cdc98f2e6cf653bceba81ad0e6f31af6834a5d7c | Python | Megasteel32/Lab03 | /tempconv.py | UTF-8 | 615 | 3.28125 | 3 | [] | no_license | # By submitting this assignment, I agree to the following:
# Aggies do not lie, cheat, or steal, or tolerate those who do�
# I have not given or received any unauthorized aid on this assignment�
#
# Name: Anthony Matl, Luca Maddaleni, Landon Charles, Nathaniel Michaud
# Group: 8
# Section: 273
# Assignment: Lab 3 1d
# Date: 3 September 2020
farenheight = float(input("Enter temperature in degrees Farenheight"))
celcius = ((farenheight - 32) * 5/9)
#formula obtained from https://www.rapidtables.com/convert/temperature/fahrenheit-to-celsius.html
print("The new temperature is:", celcius, "degrees celcius.") | true |
dabbbb023ba6ce53efddc4731ee511b010a12b59 | Python | saulocamposi/lab_python | /classes/person.py | UTF-8 | 265 | 3.453125 | 3 | [] | no_license | class Person:
name = "Person Name"
def change_name(self, name_param):
self.name = name_param
person = Person()
print (person.name)
person.change_name("Saulera")
print (person.name)
class Hello:
hello = "hello"
hello = Hello()
print (Hello.hello)
| true |
6d5d00c0616d2ede742681b50f6b22b3f416d687 | Python | kaustubh-2406/KAM | /package/models.py | UTF-8 | 1,118 | 2.59375 | 3 | [] | no_license | from package import db
class Farmer(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), nullable=False)
hash_password = db.Column(db.String(50), nullable=False)
crops = db.relationship('Crop', backref='farmer', lazy=True)
def __repr__(self):
return f'<Farmer {self.id}>: {self.username} has {self.crops}'
class Trader(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), nullable=False)
hash_password = db.Column(db.String(50), nullable=False)
def __repr__(self):
return f'<Trader {self.id}>: {self.username}'
class Crop(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20), nullable=False)
qty = db.Column(db.Integer, nullable=False)
price = db.Column(db.Integer, nullable=False)
isVerified = db.Column(db.Boolean(), default=False)
desc = db.Column(db.String(150), default="")
owner = db.Column(db.Integer, db.ForeignKey('farmer.id'))
def __repr__(self):
return f'<Crop {self.id}>: {self.name} x {self.qty}' | true |
09a0733aa76c0e73769c3c0692236634f48a75ef | Python | frederico-prog/python | /Scrips-Python/adivinhacao1.py | UTF-8 | 2,569 | 3.5 | 4 | [] | no_license | numero_secreto = 42
total_de_pontos = 1000
nivel = int(input('Selecione o nível para o jogo: \n1- 20 Tentativas \n2- 10 Tentativas \n3- 5 Tentativas \n'))
if nivel == 1:
total_tentativa = 20
for rodada in range(0, total_tentativa):
print(f'Tentativa {rodada+1} de {total_tentativa}.')
chute = int(input('Digite o seu número: '))
print(f'Você digitou {chute}.')
acertou = numero_secreto == chute
maior = chute > numero_secreto
menor = chute < numero_secreto
if acertou:
print('Você acertou!')
break
elif maior:
print('Você errou! O seu chute é maior que o número secreto.')
total_de_pontos = total_de_pontos - (chute - numero_secreto)
elif menor:
print('Você errou! O seu chute é menor que o número secreto.')
total_de_pontos = total_de_pontos - (numero_secreto - chute)
elif nivel == 2:
total_tentativa = 10
for rodada in range(0, total_tentativa):
print(f'Tentativa {rodada + 1} de {total_tentativa}.')
chute = int(input('Digite o seu número: '))
print(f'Você digitou {chute}.')
acertou = numero_secreto == chute
maior = chute > numero_secreto
menor = chute < numero_secreto
if acertou:
print('Você acertou!')
break
elif maior:
print('Você errou! O seu chute é maior que o número secreto.')
total_de_pontos = total_de_pontos - (chute - numero_secreto)
elif menor:
print('Você errou! O seu chute é menor que o número secreto.')
total_de_pontos = total_de_pontos - (numero_secreto - chute)
else:
total_tentativa = 5
for rodada in range(0, total_tentativa):
print(f'Tentativa {rodada + 1} de {total_tentativa}.')
chute = int(input('Digite o seu número: '))
print(f'Você digitou {chute}.')
acertou = numero_secreto == chute
maior = chute > numero_secreto
menor = chute < numero_secreto
if acertou:
print('Você acertou!')
break
elif maior:
print('Você errou! O seu chute é maior que o número secreto.')
total_de_pontos = total_de_pontos - (chute - numero_secreto)
elif menor:
print('Você errou! O seu chute é menor que o número secreto.')
total_de_pontos = total_de_pontos - (numero_secreto - chute)
print('Fim de jogo!')
print(f'O seu total de pontos foi {total_de_pontos}.')
| true |
a3bfc554e74140c594e77b2ee441b97a5522e9f5 | Python | netpyoung/nf.task-flow | /invoke_based/tasks/utils/filetail.py | UTF-8 | 428 | 2.796875 | 3 | [
"MIT"
] | permissive | from multiprocessing import Process
import tailer
class FileTail:
"""A simple example class"""
def __init__(self, log_fpath):
open(log_fpath, 'a').close()
p = Process(target=self.f, args=(log_fpath,))
self.process = p
p.start()
def f(self, log_fpath):
for line in tailer.follow(open(log_fpath)):
print(line)
def stop(self):
self.process.terminate()
| true |
c4aa942b33f4b5ddfc47a12e5f19cb23abcc0a8f | Python | juarezpaulino/coderemite | /problemsets/Codeforces/Python/B967.py | UTF-8 | 211 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | """
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
I=lambda:map(int,input().split())
n,a,b=I()
x,*s=I()
s=sorted(s)[::-1]
S=x+sum(s)
for i in range(n):
if i:S-=s[i-1]
if x*a>=S*b:break
print(i)
| true |
de754b30f199e8a87e15a342623b8f2db35af988 | Python | Wanstey110/Mars-Orbiter | /orbiterGame++.py | UTF-8 | 11,865 | 3.34375 | 3 | [] | no_license | #! /usr/bin/env python3.7
import os
import math
import random
import pygame as pg
from time import sleep
currentPath = os.path.dirname(__file__)
##Setup color table
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
ltBlue = (173, 216, 230)
class Satellite(pg.sprite.Sprite):
"""Satellite object that rotates to face planet & crashes & burns."""
def __init__(self, background):
super().__init__()
self.background = background
currentPath = os.path.dirname(__file__)
self.imageSat = pg.image.load(os.path.join(currentPath, "satellite.png")).convert()
self.imageCrash = pg.image.load(os.path.join(currentPath, "satellite_crash.png")).convert()
self.image = self.imageSat
self.rect = self.image.get_rect()
self.image.set_colorkey(black) # sets transparent color
self.x = random.randrange(315, 425)
self.y = random.randrange(70, 180)
self.dx = random.choice([-3, 3])
self.dy = 0
self.heading = 0 # initializes dish orientation
self.fuel = 100
self.mass = 1
self.distance = 0 # initializes distance between satellite & planet
self.thrust = pg.mixer.Sound(os.path.join(currentPath,'thrust_audio.ogg'))
self.thrust.set_volume(0.07) # valid values are 0-1
def thruster(self, dx, dy):
"""Execute actions associated with firing thrusters."""
self.dx += dx
self.dy += dy
self.fuel -= 2
self.thrust.play()
def checkKeys(self):
"""Check if user presses arrow keys & call thruster() method."""
keys = pg.key.get_pressed()
# fire thrusters
if keys[pg.K_RIGHT]:
self.thruster(dx=0.05, dy=0)
elif keys[pg.K_LEFT]:
self.thruster(dx=-0.05, dy=0)
elif keys[pg.K_UP]:
self.thruster(dx=0, dy=-0.05)
elif keys[pg.K_DOWN]:
self.thruster(dx=0, dy=0.05)
def locate(self, planet):
"""Calculate distance & heading to planet."""
px, py = planet.x, planet.y
distx = self.x - px
disty = self.y - py
# get direction to planet to point dish
planetDirRadians = math.atan2(distx, disty)
self.heading = planetDirRadians * 180 / math.pi
self.heading -= 90 # sprite is traveling tail-first
self.distance = math.hypot(distx, disty)
def rotate(self):
"""Rotate satellite using degrees so dish faces planet."""
self.image = pg.transform.rotate(self.imageSat, self.heading)
self.rect = self.image.get_rect()
def path(self):
"""Update satellite's position & draw line to trace orbital path."""
lastCenter = (self.x, self.y)
self.x += self.dx
self.y += self.dy
pg.draw.line(self.background, white, lastCenter, (self.x, self.y))
def update(self):
"""Update satellite object during game."""
self.checkKeys()
self.rotate()
self.path()
self.rect.center = (self.x, self.y)
# change image to fiery red if in atmosphere
if self.dx == 0 and self.dy == 0:
self.image = self.imageCrash
self.image.set_colorkey(black)
class Planet(pg.sprite.Sprite):
"""Planet object that rotates & projects gravity field."""
def __init__(self):
super().__init__()
currentPath = os.path.dirname(__file__)
self.imageMars = pg.image.load(os.path.join(currentPath,"mars.png")).convert()
self.imageWater = pg.image.load(os.path.join(currentPath,"mars_water.png")).convert()
self.imageCopy = pg.transform.scale(self.imageMars, (100, 100))
self.imageCopy.set_colorkey(black)
self.rect = self.imageCopy.get_rect()
self.image = self.imageCopy
self.mass = 2000
self.x = 400
self.y = 320
self.rect.center = (self.x, self.y)
self.angle = math.degrees(0)
self.rotateBy = math.degrees(0.01)
def rotate(self):
"""Rotate the planet image with each game loop."""
lastCenter = self.rect.center
self.image = pg.transform.rotate(self.imageCopy, self.angle)
self.rect = self.image.get_rect()
self.rect.center = lastCenter
self.angle += self.rotateBy
def gravity(self, satellite):
"""Calculate impact of gravity on the satellite."""
G = 1.0 # gravitational constant for game
distx = self.x - satellite.x
disty = self.y - satellite.y
distance = math.hypot(distx, disty)
# normalize to a unit vector
distx /= distance
disty /= distance
# apply gravity
force = G * (satellite.mass * self.mass) / (math.pow(distance, 2))
satellite.dx += (distx * force)
satellite.dy += (disty * force)
def update(self):
"""Call the rotate method."""
self.rotate()
def calcEccentricity(distList):
"""Calculate & return eccentricity from list of radii."""
apoapsis = max(distList)
periapsis = min(distList)
eccentricity = (apoapsis - periapsis) / (apoapsis + periapsis)
return eccentricity
def instructLabel(screen, text, color, x, y):
"""Take screen, list of strings, color, & origin & render text to screen."""
instructFont = pg.font.SysFont(None, 25)
lineSpacing = 22
for index, line in enumerate(text):
label = instructFont.render(line, True, color, black)
screen.blit(label, (x, y + index * lineSpacing))
def boxLabel(screen, text, dimensions):
"""Make fixed-size label from screen, text & left, top, width, height."""
readoutFont = pg.font.SysFont(None, 27)
base = pg.Rect(dimensions)
pg.draw.rect(screen, white, base, 0)
label = readoutFont.render(text, True, black)
labelRect = label.get_rect(center=base.center)
screen.blit(label, labelRect)
def mappingOn(planet):
"""Show soil moisture image on Mars."""
lastCenter = planet.rect.center
planet.imageCopy = pg.transform.scale(planet.imageWater, (100, 100))
planet.imageCopy.set_colorkey(black)
planet.rect = planet.imageCopy.get_rect()
planet.rect.center = lastCenter
def mappingOff(planet):
"""Restore normal planet image."""
planet.imageCopy = pg.transform.scale(planet.imageMars, (100, 100))
planet.imageCopy.set_colorkey(black)
def castShadow(screen):
"""Add optional terminator & shadow behind planet to screen."""
shadow = pg.Surface((400, 100), flags=pg.SRCALPHA) # tuple is w,h
shadow.fill((0, 0, 0, 210)) # last number sets transparency
screen.blit(shadow, (0, 270)) # tuple is top left coordinates
def main():
"""Set-up labels & instructions, create objects & run the game loop."""
pg.init() # initialize pygame
# set-up display
os.environ['SDL_VIDEO_WINDOW_POS'] = '700, 100' # set game window origin
screen = pg.display.set_mode((800, 645), pg.FULLSCREEN)
pg.display.set_caption("Mars Orbiter")
background = pg.Surface(screen.get_size())
# enable sound mixer
pg.mixer.init()
introText = [
' The BNP Orbiter experienced an error during Orbit insertion.',
' Use thrusters to correct to a circular mapping orbit without',
' running out of propellant or burning up in the atmosphere.'
]
instructText1 = [
'Orbital altitude must be within 69-120 miles',
'Orbital Eccentricity must be < 0.1',
'Avoid top of atmosphere at 68 miles'
]
instructText2 = [
'Left Arrow = Decrease Dx',
'Right Arrow = Increase Dx',
'Up Arrow = Decrease Dy',
'Down Arrow = Increase Dy',
'Space Bar = Clear Path',
'Escape = Exit Full Screen'
]
# instantiate planet and satellite objects
planet = Planet()
planetSprite = pg.sprite.Group(planet)
sat = Satellite(background)
satSprite = pg.sprite.Group(sat)
# for circular orbit verification
distList = []
eccentricity = 1
eccentricityCalcInterval = 5 # optimized for 120 mile altitude
# time-keeping
clock = pg.time.Clock()
fps = 30
tickCount = 0
# for soil moisture mapping functionality
mappingEnabled = False
running = True
while running:
clock.tick(fps)
tickCount += 1
distList.append(sat.distance)
# get keyboard input
for event in pg.event.get():
if event.type == pg.QUIT: # close window
running = False
elif event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE:
screen = pg.display.set_mode((800, 645)) # exit full screen
elif event.type == pg.KEYDOWN and event.key == pg.K_SPACE:
background.fill(black) # clear path
elif event.type == pg.KEYUP:
sat.thrust.stop() # stop sound
mappingOff(planet) # turn-off moisture map view
elif mappingEnabled:
if event.type == pg.KEYDOWN and event.key == pg.K_m:
mappingOn(planet)
# get heading & distance to planet & apply gravity
sat.locate(planet)
planet.gravity(sat)
# calculate orbital eccentricity
if tickCount % (eccentricityCalcInterval * fps) == 0:
eccentricity = calcEccentricity(distList)
distList = []
##Loading Screen
if pg.time.get_ticks() <= 7000: # time in milliseconds
loadScrn = pg.image.load(os.path.join(currentPath,"loadingScrn.png")).convert()
screen.blit(loadScrn, (0,0))
# re-blit background for drawing command - prevents clearing path
screen.blit(background, (0, 0))
# Fuel/Altitude fail conditions
if sat.fuel <= 0:
instructLabel(screen, ['Fuel Depleted!'], red, 340, 195)
sat.fuel = 0
sat.dx = 2
elif sat.distance <= 68:
instructLabel(screen, ['Atmospheric Entry!'], red, 320, 195)
sat.dx = 0
sat.dy = 0
# enable mapping functionality
if eccentricity < 0.1 and sat.distance >= 69 and sat.distance <= 120:
mapInstruct = ['Press & hold M to map soil moisture']
instructLabel(screen, mapInstruct, ltBlue, 250, 175)
mappingEnabled = True
else:
mappingEnabled = False
planetSprite.update()
planetSprite.draw(screen)
satSprite.update()
satSprite.draw(screen)
# display intro text for 15 seconds
if pg.time.get_ticks() <= 15000: # time in milliseconds
instructLabel(screen, introText, green, 145, 100)
# display telemetry and instructions
boxLabel(screen, 'Dx', (70, 20, 75, 20))
boxLabel(screen, 'Dy', (150, 20, 80, 20))
boxLabel(screen, 'Altitude', (240, 20, 160, 20))
boxLabel(screen, 'Fuel', (410, 20, 160, 20))
boxLabel(screen, 'Eccentricity', (580, 20, 150, 20))
boxLabel(screen, '{:.1f}'.format(sat.dx), (70, 50, 75, 20))
boxLabel(screen, '{:.1f}'.format(sat.dy), (150, 50, 80, 20))
boxLabel(screen, '{:.1f}'.format(sat.distance), (240, 50, 160, 20))
boxLabel(screen, '{}'.format(sat.fuel), (410, 50, 160, 20))
boxLabel(screen, '{:.8f}'.format(eccentricity), (580, 50, 150, 20))
instructLabel(screen, instructText1, white, 10, 575)
instructLabel(screen, instructText2, white, 570, 510)
# add terminator & border
castShadow(screen)
pg.draw.rect(screen, white, (1, 1, 798, 643), 1)
pg.display.flip()
if __name__ == "__main__":
main() | true |
7f2877817fc0481ec9fc36e3c95f0d2f681cdd85 | Python | farheen04/fary | /test6.py | UTF-8 | 776 | 2.515625 | 3 | [] | no_license | from selenium import webdriver
import unittest #chropath
import time
class GoogleDemo(unittest.TestCase):
def setUp(self):
global driver
driver = webdriver.Firefox(executable_path='/home/juned8236/Desktop/Coaching_MP/geckodriver')
driver.get('https://www.google.com/')
driver.maximize_window()
def test(self):
a=driver.find_element_by_xpath('//body/div[1]/div[3]/form[1]/div[1]/div[1]/div[1]/div[1]/div[2]/input[1]')
a.send_keys('Mumtaj parveen mansoorie')
time.sleep(3)
driver.find_element_by_xpath('//body/div[1]/div[3]/form[1]/div[1]/div[1]/div[3]/center[1]/input[1]').click()
time.sleep(5)
def tearDown(self):
print('teardown method')
driver.close()
unittest.main() | true |
4a14b7c912a50725f37d7974b47f44eba483bc57 | Python | abhijf/CurWebScraper | /mainCurrencyData.py | UTF-8 | 600 | 2.796875 | 3 | [] | no_license | '''
Created on Dec 11, 2015
@author: abhijit
'''
import grabOHLC
import grabCurrencyNews
import mergeNewsOhlc
import getInput
from time import sleep
# print inputs
inp_start_dt,inp_end_dt,inp_year = getInput.get_inputs()
print("start_dt ",inp_start_dt)
print("end_dt ",inp_end_dt)
print("year ",inp_year)
# get ohlc info for the year
grabOHLC.getOhlc()
print("OHLC data received")
sleep(5)
# get news info for the year
grabCurrencyNews.getCurrencyNews()
print("News data received")
sleep(5)
# merge and export to output folder
mergeNewsOhlc.mergeFiles()
print("Merge completed for year ",inp_year) | true |
393d7acd4ca15b6b89cbac7517f11d6466ca437c | Python | ZouQi523/PythonExercise | /100example/3.py | UTF-8 | 1,022 | 4.125 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 02 16:36:35 2015
@author: ZouQi
"""
"""
题目:一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?
完全平方数的含义:如:0,1,4,9,16,25,36,49等
设一个自然数x 其完全平方数等于 x^2
1.使用str.isdigit()
判断一个字符串是否为数字
注意:使用这个只能判断,并不能进行类型转换
"""
import math
def InputData():
data=raw_input(u'请输入数字:')
if str.isdigit(data):
return int(data)
else:
print u'请重新输入'
return False
if __name__=='__main__':
SearchRange=False
while SearchRange == False:
SearchRange=InputData()
print type(SearchRange)
for i in range(1,SearchRange):
temp100 =math.sqrt(i+100)
temp168 =math.sqrt(i+268)
if temp100 == int(temp100) and temp168 == int(temp168):
print 'This num is %d' % i
| true |
05fe8b7f6fa30bbc16f2a128b69be27152886664 | Python | aherschend/OOP | /studentprogram.py | UTF-8 | 454 | 3.375 | 3 | [] | no_license |
import studentclass as sc
studentid = 1001
name = 'John'
dob = '1/1/2000'
classification = 'Junior'
# create instance called john
john = sc.Student(studentid, name, dob, classification)
# don't need to give it any parameters because it's not expecting any. We are already doing that when we create the instance
john.calc_age()
john.register()
print("Student age is:", john.get_age())
print("Student can register beween:", john.get_registration()) | true |
5efd84a25733976d5da01e796d23d7dfbf67e9dd | Python | Nightmare23h/discordbot | /botcmds/help.py | UTF-8 | 2,213 | 2.78125 | 3 | [
"MIT"
] | permissive | from discord.ext import commands
from discord import Embed
import random
class Help(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.color = 0x000000
@commands.command(
name='help',
brief='Erhalte Hilfe zu Commands',
description='Hilfe kommt!',
aliases=["hilfe","commands","command","?","cmds"],
help="Benutze /help <Kategorie/Befehl> für genauere Hilfe.",
usage="<Kategorie/Befehl>"
)
async def help(self, ctx, search:str='*'):
help_embed = ctx.getEmbed(title='Hilfe', color=self.color, inline=False)
def addCog(cog):
if not cog.qualified_name in ["Owneronly"]:
cog_commands = cog.get_commands()
commands_list = ''
for comm in cog_commands:
commands_list += f'**{comm.name}** - *{comm.brief}*\n'
help_embed.add_field(
name=cog.qualified_name,
value=commands_list+'\u200b',
inline=False
)
def addCommand(cmd):
help_text = ''
help_text += f'```/{cmd.name} - {cmd.brief}```\n' + f'Kurzbeschreibung: `{cmd.description}`\n' + f'Beschreibung: `{cmd.help}`\n\n'
if len(cmd.aliases) > 0:
help_text += f'Aliases: `/{"`, `/".join(cmd.aliases)}`\n'
else:
help_text += '\n'
help_text += f'Format: `/{cmd.name}{" "+cmd.usage if cmd.usage is not None else ""}`\n\n'
help_embed.description += help_text
cogs = dict((k.lower(), v) for k, v in dict(self.bot.cogs).items())
cmds = dict((c.name.lower(),c) for c in self.bot.commands)
if search == '*':
for cog in cogs:
addCog(cogs[cog])
elif search in cmds:
addCommand(cmds[search])
elif search in cogs:
addCog(cogs[search])
else:
raise commands.BadArgument("Ungültige(r) Kategorie/Befehl.\nBenutze den `/help` Befehl um alle Kategorien und Befehle zu sehen.")
await ctx.send(embed=help_embed)
return
def setup(bot):
bot.add_cog(Help(bot))
| true |
2c5e022a90d61c33c8344e9c3426a5fcf6d14ed4 | Python | zhuli19901106/codewars | /square-every-digit(AC).py | UTF-8 | 139 | 3.078125 | 3 | [] | no_license | def square_digits(num):
num = map(int, list(str(num)))
num = int(''.join(map(str, map(lambda x: x ** 2, num))))
return num
| true |
efe52a7b4e71865b76bf99953358b4a3775bd42f | Python | ljjb/JWE | /ChineseCharCrawler/ChineseCharCrawler/spiders/httpcn_spider.py | UTF-8 | 3,175 | 2.609375 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from ChineseCharCrawler.items import *
__author__ = 'Jian Xun'
class HttpcnSpider(CrawlSpider):
name = 'httpcn'
allowed_domains = ['tool.httpcn.com']
start_urls = [
'http://tool.httpcn.com/Zi/BuShou.html'
]
rules = (
Rule(LinkExtractor(allow=(r'tool\.httpcn\.com/Html/zi/BuShou',))),
Rule(LinkExtractor(allow=(r'/Html/Zi/[0-9]+/[a-zA-Z]+\.shtml',)),
callback='parse_char'),
)
def __init__(self):
CrawlSpider.__init__(self)
def parse_char(self, response):
self.logger.info('Character page: %s', response.url)
item = ChineseCharItem()
item['url'] = response.url
item['char'] = response.xpath('//div[@class="content_nav"]/text()[2]').extract()[0].split('>')[1].strip()
item['pinyin'] = response.xpath('//div[@id="div_a1"]/table/tr/td[2]/p/span[@class="pinyin"][1]/text()').extract()[0].strip()
ph_not = response.xpath('//div[@id="div_a1"]/table/tr/td[2]/p/span[@class="pinyin"][2]/text()').extract()
if len(ph_not) > 0:
item['phonetic_notation'] = ph_not[0].strip()
structures = response.xpath('//div[@id="div_a1"]/table/tr/td[2]/p//text()').extract()
# self.logger.info(str(structures))
for i in xrange(len(structures)):
mark = structures[i]
if u'部首:' in mark:
item['radical'] = structures[i + 1].strip()
if u'总笔画:' in mark:
item['stroke_count'] = structures[i + 1].strip()
structures = response.xpath('//div[@id="div_a1"]/p[1]//text()').extract()
for i in xrange(len(structures)):
mark = structures[i]
if u'五笔86:' in mark:
item['wubi86'] = structures[i + 1].strip()
if u'五笔98:' in mark:
item['wubi98'] = structures[i + 1].strip()
if u'仓颉:' in mark:
item['cangjie'] = structures[i + 1].strip()
if u'四角号码:' in mark:
item['four_corner'] = structures[i + 1].strip()
if u'UniCode:' in mark:
item['UniCode'] = structures[i + 1].strip()
item['is_normal'] = u'是否为常用字:是' in response.xpath('//div[@id="div_a1"]/div[1]/text()').extract()[0]
item['is_family_name'] = u'姓名学:姓' in response.xpath('//div[@id="div_a1"]/div[1]/text()').extract()[1]
item['components'] = item['char']
structures = response.xpath('//div[@id="div_a1"]/div[2]//text()').extract()
# self.logger.info(str(structures))
for i in xrange(len(structures)):
mark = structures[i]
if u'笔顺编号' in mark:
item['stroke_numbers'] = structures[i + 1].split(u':')[1].strip()
if u'汉字部件构造' in mark:
item['components'] = structures[i + 1].split(u':')[1].strip()
if u'笔顺读写' in mark:
item['strokes'] = structures[i + 1].split(u':')[1].strip()
yield item
| true |
365fdfff2dcfc615a446a10a966ade2dbedc070c | Python | cgu2022/NKC---Python-Curriculum | /Projects/cowsbulls.py | UTF-8 | 1,905 | 4.75 | 5 | [] | no_license | # used for generating a random number.
import random
# this function returns a list:
# the first element is the number of cows, the second element is the number of bulls
def compare_numbers(number, user_guess):
cowbull = [0,0] #cows, then bulls
for i in range(len(number)):
# if the digit matches, add one to the number of cows.
if number[i] == user_guess[i]:
cowbull[0]+=1
# if the digit does not match, add one to the number of bulls.
else:
cowbull[1]+=1
return cowbull
isPlaying = True # start by playing the game.
randomNumber = str(random.randint(1000,9999)) # random 4 digit number.
numGuesses = 0 # keeps track of the number of guesses.
print("Let's play a game of Cowbull!") #explanation
print("I will generate a number, and you have to guess the numbers one digit at a time.")
print("For every number in the wrong place, you get a cow. For every one in the right place, you get a bull.")
print("The game ends when you get 4 bulls.")
print("Type exit at any prompt to exit.")
# loops until the user quits or guesses the correct number.
while isPlaying:
user_guess = input("Give me your best guess! ")
if(user_guess == "exit"): # user wants to quit
break
elif(len(user_guess) != 4): # invalid guess
print("Your guess must be 4 digits long.")
else: # the guess is valid
cowbullcount = compare_numbers(randomNumber,user_guess)
numGuesses += 1 # increment the number of guesses.
print("You have " + str(cowbullcount[0]) + " cows and " + str(cowbullcount[1]) + " bulls.")
if cowbullcount[0]==4:
isPlaying = False # stop playing the game because the user won.
print("You win the game after " + str(numGuesses) + " guesses! The number was " + str(randomNumber) + ".")
else:
print("Your guess isn't quite right, try again.")
| true |
55c72cc43c8a799bed228949f0dfe2c23d219468 | Python | cgranade/qutip | /qutip/hardware_info.py | UTF-8 | 3,893 | 2.71875 | 3 | [
"BSD-3-Clause"
] | permissive | __all__ = ['hardware_info']
import multiprocessing
import os
import sys
import numpy as np
def _mac_hardware_info():
info = {}
results = {}
with os.popen('sysctl hw') as f:
lines = f.readlines()
for line in lines[1:]:
key, _, value = line.partition(':')
key = key.strip(' "').replace(' ', '_').lower().strip('hw.')
value = value.strip('.\n ')
info[key] = value
results.update({'cpus': int(info['physicalcpu'])})
# Mac OS currently doesn't not provide hw.cpufrequency on the M1
with os.popen('sysctl hw.cpufrequency') as f:
cpu_freq_lines = f.readlines()
if cpu_freq_lines:
# Yay, hw.cpufrequency present
results.update({
'cpu_freq': float(cpu_freq_lines[0].split(':')[1]) / 1000000,
})
else:
# No hw.cpufrequency, assume Apple M1 CPU (all are 3.2 GHz currently)
results['cpu_freq'] = 3.2
results.update({'memsize': int(int(info['memsize']) / (1024 ** 2))})
# add OS information
results.update({'os': 'Mac OSX'})
return results
def _linux_hardware_info():
results = {}
# get cpu number
sockets = 0
cores_per_socket = 0
frequency = 0.0
with open("/proc/cpuinfo") as f:
for l in [l.split(':') for l in f.readlines()]:
if (l[0].strip() == "physical id"):
sockets = np.maximum(sockets, int(l[1].strip()) + 1)
if (l[0].strip() == "cpu cores"):
cores_per_socket = int(l[1].strip())
if (l[0].strip() == "cpu MHz"):
frequency = float(l[1].strip()) / 1000.
results.update({'cpus': int(sockets * cores_per_socket)})
# get cpu frequency directly (bypasses freq scaling)
try:
with open(
"/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq") as f:
line = f.readlines()[0]
frequency = float(line.strip('\n')) / 1000000.
except Exception:
pass
results.update({'cpu_freq': frequency})
# get total amount of memory
mem_info = dict()
with open("/proc/meminfo") as f:
for l in [l.split(':') for l in f.readlines()]:
mem_info[l[0]] = l[1].strip('.\n ').strip('kB')
results.update({'memsize': int(mem_info['MemTotal']) / 1024})
# add OS information
results.update({'os': 'Linux'})
return results
def _freebsd_hardware_info():
results = {}
results.update({'cpus': int(os.popen('sysctl -n hw.ncpu').readlines()[0])})
results.update(
{'cpu_freq': int(os.popen('sysctl -n dev.cpu.0.freq').readlines()[0])})
results.update({'memsize': int(
os.popen('sysctl -n hw.realmem').readlines()[0]) / 1024})
results.update({'os': 'FreeBSD'})
return results
def _win_hardware_info():
try:
from comtypes.client import CoGetObject
winmgmts_root = CoGetObject(r"winmgmts:root\cimv2")
cpus = winmgmts_root.ExecQuery("Select * from Win32_Processor")
ncpus = 0
for cpu in cpus:
ncpus += int(cpu.Properties_['NumberOfCores'].Value)
except Exception:
ncpus = int(multiprocessing.cpu_count())
return {'os': 'Windows', 'cpus': ncpus}
def hardware_info():
"""
Returns basic hardware information about the computer.
Gives actual number of CPU's in the machine, even when hyperthreading is
turned on.
Returns
-------
info : dict
Dictionary containing cpu and memory information.
"""
if sys.platform == 'darwin':
out = _mac_hardware_info()
elif sys.platform == 'win32':
out = _win_hardware_info()
elif sys.platform in ['linux', 'linux2']:
out = _linux_hardware_info()
elif sys.platform.startswith('freebsd'):
out = _freebsd_hardware_info()
else:
out = {}
return out
if __name__ == '__main__':
print(hardware_info())
| true |
ebfd33fe07f867fc90d5841ed0a9b391eb59d8c1 | Python | gitter-badger/nohands | /nohands/box.py | UTF-8 | 1,800 | 2.75 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
# -*- coding: utf8 -*-
# Copyright (C) 2015 Jesse Butcher
#
# nohands comes with ABSOLUTELY NO WARRANTY. This is free software, and you
# are welcome to redistribute it under certain conditions. See the MIT Licence
# for details.
"""
nohands.box
Box drawing characters.
"""
CM = u'\u2713' # [✓] Check mark
XM = u'\u2717' # [✗] X mark
# Unicode characters:
BB = u'\u2610' # Ballot box
SB = u'\u2588' # Solid block
E = u'' # Empty
S = u' ' # Plain space
D = u'\u2014' # Em dash
WD = u'\u3030' # Wavy dash
VD = u'\uFE31' # Vertical em dash
# BOX DRAWINGS LIGHT
H1 = u'\u2500' # [─] HORIZONTAL
V1 = u'\u2502' # [│] VERTICAL
HV1 = u'\u253C' # [┼] VERTICAL AND HORIZONTAL
DR1 = u'\u250C' # [┌] DOWN AND RIGHT
DL1 = u'\u2510' # [┐] DOWN AND LEFT
UR1 = u'\u2514' # [└] UP AND RIGHT
UL1 = u'\u2518' # [┘] UP AND LEFT
VR1 = u'\u251C' # [├] VERTICAL AND RIGHT
VL1 = u'\u2524' # [┤] VERTICAL AND LEFT
DH1 = u'\u252C' # [┬] DOWN AND HORIZONTAL
UH1 = u'\u2534' # [┴] UP AND HORIZONTAL
# BOX DRAWINGS DOUBLE
H2 = u'\u2550' # [═] HORIZONTAL
V2 = u'\u2551' # [║] VERTICAL
HV2 = u'\u256C' # [╬] VERTICAL AND HORIZONTAL
DR2 = u'\u2554' # [╔] DOWN AND RIGHT
DL2 = u'\u2557' # [╗] DOWN AND LEFT
UR2 = u'\u255A' # [╚] UP AND RIGHT
UL2 = u'\u255D' # [╝] UP AND LEFT
VR2 = u'\u2560' # [╠] VERTICAL AND RIGHT
VL2 = u'\u2563' # [╣] VERTICAL AND LEFT
DH2 = u'\u2566' # [╦] DOWN AND HORIZONTAL
UH2 = u'\u2569' # [╩] UP AND HORIZONTAL
# MIXED
VRM = u'\u255F' # [╟] XX
VLM = u'\u2562' # [╢] XX
DHM = u'\u2564' # [╤] XX
UHM = u'\u2567' # [╧] XX
HVA = u'\u256A' # [╪] VERTICAL SINGLE AND HORIZONTAL DOUBLE
HVB = u'\u256B' # [╫] VERTICAL DOUBLE AND HORIZONTAL SINGLE
# vim:fileencoding=utf-8
| true |
428a2f66be5a60a92cd2e875c12549ead99da790 | Python | dmartin1/django-feeds | /feeds/utils.py | UTF-8 | 4,335 | 2.765625 | 3 | [] | no_license | # Code adapted from https://github.com/Rotten194/summarize.py
import imp
import itertools
import nltk
from nltk.corpus import stopwords
import string
import bs4
import re
import requests
from feeds.alchemyapi.alchemyapi import AlchemyAPI
from django.conf import settings
# Initialize the logging library
import logging
logger = logging.getLogger(__name__)
stop_words = stopwords.words('english')
LOWER_BOUND = .20 #The low end of shared words to consider
UPPER_BOUND = .90 #The high end, since anything above this is probably SEO garbage or a duplicate sentence
available_parsers = ["html.parser",]
try:
imp.find_module("lxml")
available_parsers.append("lxml")
except ImportError:
pass
try:
imp.find_module("html5lib")
available_parsers.append("html5lib")
except ImportError:
pass
def is_unimportant(word):
"""Decides if a word is ok to toss out for the sentence comparisons"""
return word in ['.', '!', ',', ] or '\'' in word or word in stop_words
def only_important(sent):
"""Just a little wrapper to filter on is_unimportant"""
return filter(lambda w: not is_unimportant(w), sent)
def compare_sents(sent1, sent2):
"""Compare two word-tokenized sentences for shared words"""
if not len(sent1) or not len(sent2):
return 0
return len(set(only_important(sent1)) & set(only_important(sent2))) / ((len(sent1) + len(sent2)) / 2.0)
def compare_sents_bounded(sent1, sent2):
"""If the result of compare_sents is not between LOWER_BOUND and
UPPER_BOUND, it returns 0 instead, so outliers don't mess with the sum"""
cmpd = compare_sents(sent1, sent2)
if cmpd <= LOWER_BOUND or cmpd >= UPPER_BOUND:
return 0
return cmpd
def compute_score(sent, sents):
"""Computes the average score of sent vs the other sentences (the result of
sent vs itself isn't counted because it's 1, and that's above
UPPER_BOUND)"""
if not len(sent):
return 0
return sum( compare_sents_bounded(sent, sent1) for sent1 in sents ) / float(len(sents))
def summarize_block(block):
"""Return the sentence that best summarizes block"""
sents = nltk.sent_tokenize(block)
word_sents = map(nltk.word_tokenize, sents)
d = dict( (compute_score(word_sent, word_sents), sent) for sent, word_sent in zip(sents, word_sents) )
return d[max(d.keys())]
def find_likely_body(b):
"""Find the tag with the most directly-descended <p> tags"""
return max(b.find_all(), key=lambda t: len(t.find_all('p', recursive=False)))
class Summary(object):
def __init__(self, url, parser="html.parser"):
self.url = url
if parser not in available_parsers:
logging.error("Available parsers are: %s" % (available_parsers,))
raise ImportError
try:
self.soup = bs4.BeautifulSoup(requests.get(url).text, parser)
except requests.exceptions.ConnectionError:
print "Connection error getting url data"
return None
self.title = self.soup.title.string if self.soup.title else None
if hasattr(settings, "ALCHEMY_API_KEY"):
api = AlchemyAPI(settings.ALCHEMY_API_KEY)
response = api.text('url', self.url)
if response.get('status', 'error') == 'OK':
if response.get('text', None) != None:
regex = re.compile(r'[\n\r\t]')
self.content = regex.sub(" ", response['text'])
else:
self.article_html = find_likely_body(self.soup)
parts = map(lambda p: re.sub('\s+', ' ', summarize_block(p.text)).strip(), self.article_html.find_all('p'))
parts = sorted(set(parts), key=parts.index) #dedpulicate and preserve order
self.parts = [ re.sub('\s+', ' ', summary.strip()) for summary in parts if filter(lambda c: c.lower() in string.letters, summary) ]
proposed_content = ''
for part in summary.parts:
if not getattr(settings, 'SUMMARIZE_WORD_COUNT_LIMIT', None) or len(proposed_content.split(' ')) < settings.SUMMARIZE_WORD_COUNT_LIMIT:
proposed_content = proposed_content + ' ' + part
self.content = proposed_content
def __unicode__(self):
return 'Summary of %s' % (self.url,)
| true |
d3175a6b81d584e5a22634066a481e2ce13af81e | Python | rashley2712/WFCreducer | /plotImages.py | UTF-8 | 1,091 | 2.953125 | 3 | [] | no_license | import matplotlib.pyplot
import numpy
def boostImage(imageData, lo=20, hi=99):
data = imageData
max = data.max()
dataArray = data.flatten()
pHi = numpy.percentile(dataArray, hi)
pLo = numpy.percentile(dataArray, lo)
range = pHi - pLo
scale = range/255
data = numpy.clip(data, pLo, pHi)
data-= pLo
data/=scale
return data
def plotImage(image, boost=False):
imageData = image.imageData
imageTitle = image.name
if boost: imageData = boostImage(imageData)
figure = matplotlib.pyplot.figure(figsize=(8, 8/1.618))
matplotlib.pyplot.xlabel("X (pixels)", size = 12)
matplotlib.pyplot.ylabel("Y (pixels)", size = 12)
figure.canvas.set_window_title(imageTitle)
imgplot = matplotlib.pyplot.imshow(imageData)
matplotlib.pyplot.draw()
matplotlib.pyplot.show(block=False)
return figure
def plotSources(sources, figure):
matplotlib.pyplot.figure(figure.number)
xpos = [ s['xcentroid'] for s in sources]
ypos = [ s['ycentroid'] for s in sources]
matplotlib.pyplot.scatter(xpos, ypos, color = 'r', alpha=0.5)
matplotlib.pyplot.draw()
matplotlib.pyplot.show(block = False)
| true |
04e07271ef6e8fb652f1282cd088ab464b5cbf0e | Python | sssilvar/CSD-AD | /test/explore_data/extract_and_organize_t1_t2.py | UTF-8 | 1,828 | 2.90625 | 3 | [] | no_license | import os
from os.path import join
from zipfile import ZipFile
import pandas as pd
def get_list_of_files_in_zip(zip_files):
"""
Recieves a list of zip files and
returns the contents
"""
files = {k: [] for k in zip_files}
for zip_file in zip_files:
print('[ INFO ] Loading: %s' % zip_file)
try:
with ZipFile(join(zip_file), 'r') as z:
files[zip_file] = files[zip_file] + z.namelist()
except Exception as e:
print(e)
return files
if __name__ == '__main__':
os.system('clear')
# Set files containing T1 and T2 zipped images
t1_zip_folder = '/run/media/ssilvari/Smith_2T_WD/Databases/ADNI_3T_3Y'
t2_zip_folder = '/run/media/ssilvari/Smith_2T_WD/Databases/ADNI_T2_FLAIR'
# Define output folder
t2_df = pd.read_csv(join(t2_zip_folder, 'T2_screening.csv'), index_col='Subject')
print(t2_df.head())
# TODO: Fields: IMAGEUID
# Define ADNI ZIP files
adni_zips = ['/disk/Datasets/ADNI/T1_BRAINMASK/brainmask_baseline.zip'] + [join(t2_zip_folder, 'T2_screening_%d.zip' % i) for i in range(1,11)] # [join(t1_zip_folder, 'ADNI1_Complete_3Yr_1.5T_%d.zip' % i) for i in range(1,11)] + \
# Get all the files inside ZIPs
files = get_list_of_files_in_zip(adni_zips)
# Start magic:
t1_and_t2 = []
for subject in t2_df.index:
find = {k:[] for k in files.keys()}
for key, val in files.items():
for v in val:
if subject in v:
print('%s Found in %s' % (subject, v))
find[key].append(v)
print('\n')
for key, val in find.items():
if len(val) >= 2:
t1_and_t2.append(1)
print('Total subjects with T1 and t2 * %d ' % len(t1_and_t2))
| true |
3a727a67b987657b796a00f68e47c179b3305b87 | Python | Chiil/smallprograms | /oo_fortran_cpp_python/oo_python.py | UTF-8 | 828 | 4.21875 | 4 | [] | no_license | class Animal:
def __init__(self, age, weight):
self.age = age
self.weight = weight
def print_age(self):
print(self.age)
def print_weight(self):
print(self.weight)
def make_sound(self):
raise RuntimeError("Cannot call base")
class Dog(Animal):
def __init__(self, age, weight):
Animal.__init__(self, age, weight)
self.sound = "Woof!"
def make_sound(self):
print(self.sound)
class Cat(Animal):
def __init__(self, age, weight):
Animal.__init__(self, age, weight)
self.sound = "Meew!"
def make_sound(self):
print(self.sound)
animal1 = Dog(10, 3)
animal2 = Cat(12, 1)
animal1.print_age()
animal1.print_weight()
animal1.make_sound()
animal2.print_age()
animal2.print_weight()
animal2.make_sound()
| true |
38156a36291797b7c02194bfcef2f0df0ce99007 | Python | Lex-DRL/renderdoc-py-stubs | /_pycharm_skeletons/renderdoc/LocalVariableMapping.py | UTF-8 | 3,684 | 2.59375 | 3 | [
"MIT"
] | permissive | # encoding: utf-8
# module renderdoc
# from P:\1-Scripts\_Python\Py-Autocomplete\renderdoc.pyd
# by generator 1.146
# no doc
# imports
import enum as __enum
from .SwigPyObject import SwigPyObject
class LocalVariableMapping(SwigPyObject):
"""
Maps the contents of a high-level local variable to one or more shader variables in a
:class:`ShaderDebugState`, with type information.
A single high-level variable may be represented by multiple mappings but only along regular
boundaries, typically whole vectors. For example an array may have each element in a different
mapping, or a matrix may have a mapping per row. The properties such as :data:`rows` and
:data:`elements` reflect the *parent* object.
Since locals don't always map directly this can change over time.
"""
def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass
def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass
def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass
def __hash__(self, *args, **kwargs): # real signature unknown
""" Return hash(self). """
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass
def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass
builtin = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""The shader builtin this variable corresponds to."""
columns = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""The number of columns in this variable."""
elements = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""The number of array elements in this variable."""
localName = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""The name and member of this local variable that's being mapped from."""
regCount = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""The number of valid entries in :data:`registers`."""
registers = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""
The registers that the components of this variable map to. Multiple ranges could refer
to the same register if a contiguous range is mapped to - the mapping is component-by-component to
greatly simplify algorithms at the expense of a small amount of storage space.
"""
rows = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""The number of rows in this variable - 1 for vectors, >1 for matrices."""
this = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
thisown = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
type = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""The variable type of the local being mapped from, if the register is untyped."""
__dict__ = None # (!) real value is ''
| true |
5dc5d92ffba563150627f90fe4fc673606c1e31e | Python | amussell/PiObjectFollower | /ArmControl.py | UTF-8 | 5,285 | 3.625 | 4 | [] | no_license | from Servo import Servo
from Direction import Direction, getImageCenter, getObjectCenter, getObjectDirection
from threading import Thread
import queue
import math
import numpy as np
from typing import Tuple, Boolean
class ArmControl:
"""Object to control a 2 axis servo controlled arm.
Given a queue with (obj, frame) objects this class can track an the object from the queue.
The data in (obj, frame) should be formated ((x,y,width,height), img: np.array)
"""
def __init__(self, horizontalControlPin: int, verticalControlPin: int) -> ArmControl:
self.horizontalControlPin = horizontalControlPin
self.verticalControlPin = verticalControlPin
self.horizontalServo = Servo(horizontalControlPin)
self.verticalServo = Servo(verticalControlPin)
self.tracking = False
def moveLeft(self) -> None:
"""Moves horizontal servo 1 degree counter clockwise
"""
self.horizontalServo.rotate(Direction.CounterClockwise, 1)
def moveRight(self) -> None:
"""Moves horizontal servo 1 degree Clockwise
"""
self.horizontalServo.rotate(Direction.Clockwise, 1)
def moveUp(self) -> None:
"""Moves vertical servo 1 degree Clockwise
"""
self.verticalServo.rotate(Direction.Clockwise, 1)
def moveDown(self) -> None:
"""Moves vertical servo 1 degree CounterClockwise
"""
self.verticalServo.rotate(Direction.CounterClockwise, 1)
def trackFace(self, cameraStream: queue) -> None:
"""Tracks a face/object given a queue that contains objects and the frame the object was captured in.
The queue object format is ((x,y,width,height), img: np.array)
This function runs until stopAsyncFaceTracking() is called.
Args:
cameraStream (queue): queue with objects and frames
"""
face = None
frame = None
# Get the first frame
while face is None or frame is None:
try:
face, frame = cameraStream.get_nowait()
except queue.Empty:
pass
self.tracking = True
while(self.tracking):
while(not faceCentered(face, frame) and self.tracking):
direction = getObjectDirection(face, frame)
if (direction[0] != Direction.NoDirection):
if (direction[0] == Direction.Left):
self.moveLeft()
elif (direction[0] == Direction.Right):
self.moveRight()
if (direction[1] != Direction.NoDirection):
if (direction[1] == Direction.Up):
self.moveUp()
elif (direction[1] == Direction.Down):
self.moveDown()
#Get the next image and face from queue
face, frame = nextFaceFromQueue(face, frame, cameraStream)
face, frame = nextFaceFromQueue(face, frame, cameraStream)
def trackFaceAsync(self, cameraStream: queue):
"""Calls trackFace on another thread. To stop that thread call stopAsyncFaceTracking().
The queue object format is ((x,y,width,height), img: np.array)
Args:
cameraStream (Tuple): queue with objects and frames
"""
followFaceTask = Thread(target=self.trackFace, args=[cameraStream])
followFaceTask.start()
def stopAsyncFaceTracking(self):
"""Call this function to stop trackFaceAsync thread.
"""
self.tracking = False
tolerance = .08 # How close as percentage of the width of a frame that the face must be to the center
def faceCentered(face: Tuple[int,int,int,int], frame: np.array) -> Boolean:
"""Detects if the face/object is close to the center of the frame.
Args:
face (Tuple[int,int,int,int]): (x,y,width,height) face bounding box
frame (np.array): image face was captured in
Returns:
[Boolean]: [description]
"""
allowablePixelDistance = frame.shape[1] * tolerance
faceCenter = getObjectCenter(face)
frameCenter = getImageCenter(frame)
faceDistanceFromCenter = math.hypot(faceCenter[0] - frameCenter[0], faceCenter[1] - frameCenter[1])
return faceDistanceFromCenter < allowablePixelDistance
def nextFaceFromQueue(face: Tuple[int,int,int,int], frame: np.array, faceQueue: queue):
"""Gets the next face/obj, frame pair from the queue. If a new pair is not available
it returns the face and frame that were passed in.
Args:
face (Tuple[int,int,int,int]): face/object (x,y,width,height)
frame (np.array): frame that face/object was detected in
faceQueue (queue): queue that stores face/object frame pairs (face/obj: Tuple[int,int,int,int], frame: np.array)
Returns:
(face/obj: Tuple[int,int,int,int], frame: np.array): the next face/obj frame pair
"""
nextFace = face
nextFrame = frame
if not faceQueue.empty():
try:
nextFace, nextFrame = faceQueue.get_nowait()
except queue.Empty:
pass # We will just use the latest image we have
return nextFace, nextFrame
| true |
a54da6e6569131977c2336452809adafac0f86e4 | Python | wangluyan128/AutoTest | /pyLocustDemo/UserBehavior3.py | UTF-8 | 1,405 | 2.734375 | 3 | [] | no_license | #保证并发测试数据唯一性,循环取数据
#所有并发虚拟用户共享同一份测试数据,保证并发虚拟用户使用的数据不重复,并且数据可循环重复使用。
#例如,模拟3用户并发登录账号,总共有9个账号,要求并发登录账号不相同,但数据可循环使用;加载示例如下表所示。
import queue
from locust import TaskSet, task, HttpLocust
class UserBehavior(TaskSet):
@task
def test_register(self):
try:
data = self.locust.user_data_queue.get()
except queue.Empty:
print('account data run out,test ended.')
exit(0)
print('register with user:{},pwd:{}'\
.format(data['username'],data['password']))
payload = {
'username':data['username'],
'password':data['password']
}
self.client.post('/register',data = payload)
self.locust.user_data_queue.put_nowait(data)
class WebsiteUser(HttpLocust):
host = 'https://debugtalk.com'
task_set = UserBehavior
user_data_queue = queue.Queue()
for index in range(100):
data = {
'username':'test%04d'%index,
'password':'pwd%04d' %index,
'email':'test%04d@debugtalk.test'%index,
'phone':'186%08d'%index,
}
user_data_queue.put_nowait(data)
min_wait = 1000
max_wait = 3000 | true |
0f4a3279c9e76945add2172833c10e73d4ad3975 | Python | bmdvpanga/sudoku_solver | /board/utils.py | UTF-8 | 2,296 | 3.625 | 4 | [] | no_license | from django.shortcuts import render
class SudokuSolver:
def __init__(self, request):
self.board = [ [" " for _ in range (9)] for _ in range(9) ]
for i in range(9):
for j in range(9):
key = str(i+1)+str(j+1)
self.board[i][j] = request.POST.get(key,'')
def check_board(self,board, coordinates, value):
''' Function takes the column and the row of the board that is validated
Parameters:
board
coordinates -> tuple, (Y, X)
value to be checked
Returns True if value being checked does not exist
'''
y = coordinates[0]
x = coordinates[1]
# check y
for i in range (0, 9):
if ( board[i][x] == value and i != y):
return False
#check x
for i in range (0, 9):
if ( board[y][i] == value and i != x):
return False
#check the box
box_x = ( x // 3) * 3
box_y = ( y // 3) * 3
for i in range(box_y, box_y + 3):
for j in range(box_x, box_x + 3):
if(board[i][j] == value and (i, j) != coordinates):
return False
return True
def solve_board(self,board):
''' Recursive function to individually fill out squares marked 0 (empty)
Backtracks if the solution is not correct
'''
for row in range(0,9):
for col in range(0,9):
#If the current location is empty, then we start brute forcing the guess value
if(board[row][col] == ""):
for guess in range(1,10):
if( self.check_board(board, (row,col), str(guess)) ):
board[row][col] = str(guess)
#Call the function with the updated board
if(self.solve_board(board)[0]):
return (True,self.board)
#if we are unable to solve this using the cur value, then we backrack and change position back to 0
board[row][col] = ""
return (False,self.board)
print(self.board)
return (True,self.board) | true |
ce57486baedaad99daaa6bc8a2d1b92616108983 | Python | philipwerner/code-katas | /grouped_by_commas/test_grouped_by_commas.py | UTF-8 | 2,310 | 3.03125 | 3 | [
"MIT"
] | permissive | import pytest
def test_group_by_commas():
"""Tests that commas are inserted properly."""
from grouped_by_commas import group_by_commas
n = 1
assert group_by_commas(n) == '1'
def test_group_by_commas2():
"""Tests that commas are inserted properly."""
from grouped_by_commas import group_by_commas
n = 10
assert group_by_commas(n) == '10'
def test_group_by_commas3():
"""Tests that commas are inserted properly."""
from grouped_by_commas import group_by_commas
n = 100
assert group_by_commas(n) == '100'
def test_group_by_commas4():
"""Tests that commas are inserted properly."""
from grouped_by_commas import group_by_commas
n = 1000
assert group_by_commas(n) == '1,000'
def test_group_by_commas5():
"""Tests that commas are inserted properly."""
from grouped_by_commas import group_by_commas
n = 10000
assert group_by_commas(n) == '10,000'
def test_group_by_commas6():
"""Tests that commas are inserted properly."""
from grouped_by_commas import group_by_commas
n = 100000
assert group_by_commas(n) == '100,000'
def test_group_by_commas7():
"""Tests that commas are inserted properly."""
from grouped_by_commas import group_by_commas
n = 1000000
assert group_by_commas(n) == '1,000,000'
def test_group_by_commas8():
"""Tests that commas are inserted properly."""
from grouped_by_commas import group_by_commas
n = 35235235
assert group_by_commas(n) == '35,235,235'
def test_group_by_commas9():
"""Tests that commas are inserted properly."""
from grouped_by_commas import group_by_commas
n = 789067
assert group_by_commas(n) == '789,067'
def test_group_by_commas10():
"""Tests that commas are inserted properly."""
from grouped_by_commas import group_by_commas
n = 1234567890
assert group_by_commas(n) == '1,234,567,890'
def test_group_by_commas11():
"""Tests that commas are inserted properly."""
from grouped_by_commas import group_by_commas
n = 9876543219876
assert group_by_commas(n) == '9,876,543,219,876'
def test_group_by_commas12():
"""Tests that commas are inserted properly."""
from grouped_by_commas import group_by_commas
n = 1357924680
assert group_by_commas(n) == '1,357,924,680'
| true |
590c6ea039a9533f567b3ef9124301d4d6cb2879 | Python | dodonmountain/algorithm | /2019_late/20191104/boj_2747_피보나치수.py | UTF-8 | 128 | 3.125 | 3 | [] | no_license | prev, pprev = 0, 1
now = 0
n = int(input())
for i in range(n):
now = prev + pprev
pprev = prev
prev = now
print(now) | true |
25074331a3c26d8ac16ae5f97aab57d80c39ecdd | Python | van123456/test_django | /build_pyenv.py | UTF-8 | 2,590 | 2.59375 | 3 | [] | no_license | #!/usr/bin/env python3
# -*-coding:utf-8-*-
# linux-centos7版本下搭建pyenv环境的自动化脚本
import os
import re
import time
__Author__ = "van"
class build_pyenv():
# 检查是否安装git,未安装就安装git
def check_git(self):
cmd = "rpm -qa|grep git-"
values = (os.popen(cmd)).readlines()
return_str = []
for value in values:
return_value = re.search(pattern="git", string=value)
if return_value == None:
pass
else:
return_str.append(return_value)
if return_str == []:
print("git未安装,正在尝试安装")
time.sleep(1)
cmd = "yum -y install git"
os.system(cmd)
else:
print("git已安装,请执行下一步")
print("当前git版本:")
cmd = "git version"
os.system(cmd)
time.sleep(1)
# 修改pyenv相关的环境变量并重新加载
def pyenv_env(self):
file = "/root/.bashrc"
with open(file, "r") as f:
values = f.readlines()
return_str = []
for value in values:
return_value = re.search(pattern="pyenv init -", string=value)
if return_value == None:
pass
else:
return_str.append(return_value)
if return_str == []:
print("未配置环境变量,尝试配置环境变量")
print("先设置pyenv的安装目录")
with open(file, "a") as f:
f.write(
"\n" + "export PYENV_ROOT=/opt/pyenv")
cmd = "source" + ' ' + file
os.system(cmd)
time.sleep(1)
cmd = "curl -L https://github.com/pyenv/pyenv-installer/raw/master/bin/pyenv-installer | bash"
os.system(cmd)
time.sleep(1)
with open(file, "a") as f:
f.write(
"\n" + "export PATH=\"/opt/pyenv/bin:$PATH\"" + "\n" + "eval \"$(pyenv init -)\"" + "\n" + "eval \"$(pyenv virtualenv-init -)\"")
cmd = "source" + ' ' + file
os.system(cmd)
print("已完成配置pyenv的环境变量重新加载")
else:
print("已配置pyenv的环境变量")
if __name__ == "__main__":
build_pyenv().check_git()
build_pyenv().pyenv_env()
| true |
50cbbef5df8ad51bcbf2c21c1ce6220076bd3ee5 | Python | bettle123/VisualizationFinal | /src/task1_v03_hist.py | UTF-8 | 1,639 | 2.671875 | 3 | [] | no_license | '''
@Author: Su Ming Yi
@Date: 12/04/2018
@Goal:
Get the histogram of one timestep
How to run it:
C:\python\Lib\site-packages\VTK\bin\vtkpython.exe task1_v03_hist.py
'''
import vtk
import vtk.util.numpy_support as VN
import numpy as np
import sys,os
import csv
import matplotlib.pyplot as plt
def main():
path = "yC31/";
# the variable name of data array which we used to analyze
daryName = "v03";
files = os.listdir(path);
#for i in range(0, 10):
for i in range(0, len(files)):
filename = path+files[i];
print(filename);
# data reader
reader = vtk.vtkXMLImageDataReader();
reader.SetFileName(filename);
reader.Update();
# specify the data array in the file to process
reader.GetOutput().GetPointData().SetActiveAttribute(daryName, 0);
# convert the data array to numpy array and get the min and maximum value
dary = VN.vtk_to_numpy(reader.GetOutput().GetPointData().GetScalars(daryName));
plt.hist(dary, color = "blue", bins = 20)
titlename = "Histogram of v03 timestep " +files[i][22:27]
plt.title(titlename)
savefilename = "plots/hists/v03_t_"+files[i][22:27]+".png";
plt.savefig(savefilename);
'''
x = [];
y = [];
for i in range(0, 10):
x.append(i);
y.append(i*3);
if(i>=5):
y.append(i*3);
plt.hist(y) # arguments are passed to np.histogram
plt.title("Histogram with 'auto' bins")
plt.savefig("plots/example_hist.png");
'''
if __name__ == '__main__':
main();
| true |
74d07bbc1abf4bc7d7a88266a169dd1865b14700 | Python | daniel-reich/ubiquitous-fiesta | /W3Hptw6ieTtrWNw4H_8.py | UTF-8 | 632 | 3.015625 | 3 | [] | no_license |
def bifid(s):
l = "abcdefghiklmnopqrstuvwxyz"
c, r, out = [], [], ""
if s[0].isupper():
pt = "".join([i.lower() for i in s if i.isalpha()])
for i in pt:
pos = l.index(i)
c.append(pos % 5)
r.append(pos // 5)
rc = r + c
for i in range(1, len(rc), 2):
out += l[rc[i - 1] * 5 + rc[i]]
elif s[0].islower():
for i in s:
pos = l.index(i)
c.append(pos // 5)
c.append(pos % 5)
for i in range(0, int(len(c) / 2), 1):
out += l[c[i] * 5 + c[i + int(len(c) / 2)]]
return out
| true |
855482bb0fa057b81e929485ca178dc994c58019 | Python | chitraderrob/NU-Homework | /Python Challenge/PyBank/Heena.py | UTF-8 | 2,392 | 3.53125 | 4 | [] | no_license | import os
import csv
#Lists
date = []
rev_change = []
profit = []
#Variables
month = 0
opening_profit = 0
profit_change = 0
total_profit = 0
#Open CSV
csvpath = os.path.join("..", "Resources", "budget_data.csv")
with open(csvpath, newline='') as csvfile:
csv_reader = csv.reader(csvfile, delimiter=',')
csv_header = next(csv_reader)
# The total number of months included in the dataset
for row in csv_reader:
profit.append(float(row[1]))
date.append(row[0])
print(month)
# The net total amount of "Profit/Losses" over the entire period
total_revenue = sum(profit)
print(total_revenue)
# # The average of the changes in "Profit/Losses" over the entire period
# close_profit = int(row[1])
# profit_change = close_profit - opening_profit
# profit_change.append(profit_change)
# total_profit = total_profit + profit_change
# opening_profit = close_profit
# average = int(total_profit/month)
# # The greatest increase in profits (date and amount) over the entire period
# greatest_increase = max(profit_change)
# greatest_increase_date = date[profit_change.index(greatest_increase)]
# # The greatest decrease in losses (date and amount) over the entire period
# greated_decrease = min(profit_change)
# greated_decrease_date = date[profit_change.index(greated_decrease)]
# # Print
# print("Financial Analysis")
# print("----------------------------")
# print(f"Total Monts: {month}")
# print(f"Total: ${total_profit}")
# print(f"Average Change: ${profit_change}")
# print(f"Greatest Increase in Profits: {greatest_increase_date} {greatest_increase}")
# print(f"Greatest Decrease in Profits: {greated_decrease_date} {greated_decrease}")
# #Export
# analysis = os.path.join('..', 'Resources', 'analysis.txt')
# with open(analysis, 'w') as text:
# analysis.write("Financial Analysis")
# analysis.write("----------------------------")
# analysis.write(f"Total Monts: {month}")
# analysis.write(f"Total: ${total_profit}")
# analysis.write(f"Average Change: ${profit_change}")
# analysis.write(f"Greatest Increase in Profits: {greatest_increase_date} {greatest_increase}")
# analysis.write(f"Greatest Decrease in Profits: {greated_decrease_date} {greated_decrease}") | true |
f13d8770272d0dea32558331d8c893280009c590 | Python | choijaehyeokk/BAEKJOON | /10989_수 정렬하기 3.py | UTF-8 | 268 | 3.140625 | 3 | [] | no_license | import sys
numbers = [0] * 10001
N = int(sys.stdin.readline().rstrip())
for _ in range(N):
A = int(sys.stdin.readline().rstrip())
numbers[A] += 1
for j in range(1, len(numbers)):
if numbers[j] != 0:
for k in range(numbers[j]):
print(j) | true |
08b343b5c764046b2efc0d502f7893567de69398 | Python | Arjun23-bot/OpenCV-introduction | /opencv introduction.py | UTF-8 | 487 | 2.671875 | 3 | [] | no_license | import cv2
import numpy as np
#requirements
OpenCV --> pip install opencv-python
# Displaying normal color image without a transparent background
#1 = ignore transparency
#-1 = normal color image of the color
#0 = grayscale
img = cv2.imread('C:/Users/paarj/Downloads/hp-omen-17-2019_f2j6.1200.jpg', -1)
img = cv2.resize(img, (0, 0), fx=1.0, fy=1.0 )
img = cv2.rotate(img, cv2.cv2.ROTATE_90_CLOCKWISE)
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
| true |
13dbc19d1156aacb7f59f5cd9374ccd9b276dd7c | Python | shiki7/Atcoder | /ARC041/A.py | UTF-8 | 104 | 3 | 3 | [] | no_license | x, y = map(int, input().split())
k = int(input())
if k <= y:
print(x+k)
else:
print(x+y-(k-y))
| true |
98647eea184e0e7ac44e23ff8ed757285b73e6c0 | Python | Manishsu1001/Memory-game | /main.py | UTF-8 | 5,889 | 3.359375 | 3 | [] | no_license | import random
import os
import time
#This will give me a box of required size
def createbox(n):
line = ''
for i in range(1+7*n):
line += '-'
line2 = ''
for i in range(1+7*n):
if i % 7 == 0:
line2 += '|'
else:
line2 += ' '
minature = [line]
for i in range(n):
minature.append(line2)
minature.append(line2)
minature.append(line)
return minature
def game(n,times,blinktime):
loaded = createbox(n)
#The blinking period code follows:
for itr in range(times):
os.system('cls')
x,y = random.randint(0,n-1),random.randint(0,n-1)
change = loaded[1+3*x][:3+7*y]+'**'+loaded[1+3*x][5+7*y:]
loaded[1+3*x],loaded[2+3*x] = change,change
print('\n\n')
for j in loaded:
print('\t\t\t\t\t\t',j)
change = loaded[1+3*x][:3+7*y]+' '+loaded[1+3*x][5+7*y:]
loaded[1+3*x],loaded[2+3*x] = change,change
history.append((x+1,y+1))
numhis.append(n*x+y+1)
time.sleep(blinktime)
os.system('cls')
print('\n\n')
for j in loaded:
print('\t\t\t\t\t\t',j)
time.sleep(blinktime*4/5)
# The asking from user period code follows
print('\n\n')
for i in range(len(numhis)):
trial = input('\t\t\t\t\t\t'+str(i+1)+': ')
try:
ip = trial.split()
if (int(ip[0]),int(ip[1])) != history[i]:
c = i
break
except:
if int(trial) != numhis[i]:
c = i
break
try:
print('\n\n\t\t\t\t\t\tYou lost! you remebered only',c,'words')
except:
print('\n\n\t\t\t\t\t\tcongrats you won')
def main_menu():
os.system('cls')
ip = -10
while(ip > 4 or ip < 1):
print('\t\t\t\tEnter the number corresponding to options to select!\n\n\n\n\n\n\n')
print('\t\t\t\t\t\t1. Quick Play')
print('\t\t\t\t\t\t2. Play Level Wise')
print('\t\t\t\t\t\t3. How to play?')
print('\t\t\t\t\t\t4. Quit')
try:
ip = int(input('Enter here: '))
except:
print('**************************************************Enter a valid option**************************************************\n')
os.system('cls')
if ip >4 or ip< 1:
print('**************************************************Enter a valid option**************************************************\n')
os.system('cls')
while ip == 1:
print('\n\n\t\t\t\t\tYou will have to remeber 5 blinks positions')
time.sleep(2)
game(3,5,1)
play_again()
if ip == 2:
ip = -10
while(ip > 5 or ip < 1):
print('\t\t\t\tEnter the number corresponding to options to select!\n\n\n\n\n\n\n')
print('\t\t\t\t\t\t1. Very Easy')
print('\t\t\t\t\t\t2. Easy')
print('\t\t\t\t\t\t3. Medium')
print('\t\t\t\t\t\t4. Hard')
print('\t\t\t\t\t\t5. Very Hard')
try:
ip = int(input('Enter here: '))
except:
print('**************************************************Enter a valid option**************************************************\n')
os.system('cls')
if ip >5 or ip< 1:
print('**************************************************Enter a valid option**************************************************\n')
os.system('cls')
while ip == 1:
print('\n\n\t\t\t\tYou will have to remeber 5 blinks positions')
time.sleep(4)
game(3,5,1)
play_again()
while ip == 2:
print('\t\t\t\tYou will have to remeber 5 blinks positions')
time.sleep(4)
game(5,5,1)
play_again()
while ip == 3:
print('\t\t\t\tYou will have to remeber 10 blinks positions')
time.sleep(4)
game(5,10,1.2)
play_again()
while ip == 4:
print('\t\t\t\tYou will have to remeber 10 blinks positions')
time.sleep(4)
game(8,10,1.2)
play_again()
while ip == 5:
print('\t\t\t\tYou will have to remeber 15 blinks positions')
time.sleep(4)
game(10,15,1.2)
play_again()
if ip == 3:
print('This is a memory game where you have to remeber the blinks and when asked, you have to type in which box the stars were blinked. Sounds interesting right? So GO AND PLAY')
input('\n\n\t\t\t\tPress ENTER/RETURN key to go back to main Menu')
main_menu()
while ip == 4:
check = input('\t\t\t\t\t\tAre you sure you want to leave\n\n\t\t\t\t\t\t\tYES/NO\n\t\t\t\t\t\t\tY/N\n\n\t\t\t\t\t\t\t')
if check in ['y','Y','Yes','yes','YES']:
print('Leaving...')
time.sleep(1)
quit()
elif check in ['n','N','NO','no','No','nO']:
print('\n\n\n\t\t\t\t\t\tGetting back to main menu!')
time.sleep(1)
main_menu()
else:
continue
def play_again():
while True:
check = input('\n\n\t\t\t\t\t\tDo you want to play again?\n\n\t\t\t\t\t\t\tYES/NO\n\t\t\t\t\t\t\tY/N\n\n\t\t\t\t\t\t')
if check in ['y','Y','Yes','yes','YES']:
os.system('cls')
break
elif check in ['n','N','NO','no','No','nO']:
print('Getting back to main menu!')
time.sleep(1)
main_menu()
else:
continue
os.system('cls')
if __name__ == '__main__':
history = []
numhis = []
main_menu()
| true |
abe915b46e55ae6c190def4a86b518311df3725c | Python | fadamsyah/computer-vision-with-pytorch | /Classification/lib/metrics.py | UTF-8 | 1,274 | 2.875 | 3 | [] | no_license | import torch
class AccuracyBinary():
def __init__(self, threshold=0.5):
self.name = 'acc'
self.target = 'max'
self.threshold = threshold
def __call__(self, y_true, y_pred):
'''
args:
y_true: numpy array with size (N, 1) or (N,)
y_pred: numpy array with size (N, 1) or (N,)
return:
mean of correct prediction
'''
label_true = y_true.astype(np.int32)
label_pred = y_pred.astype(np.float32)
label_pred[label_pred >= self.threshold] = 1
label_pred[label_pred < self.threshold] = 0
label_pred = label_pred.astype(np.int32)
return np.mean(label_true == label_pred)
class AccuracyCategorical():
def __init__(self):
self.name = 'acc'
self.target = 'max'
def __call__(self, labels, outputs):
'''
args:
y_true: torch tensor with size
(N,1) or (N,)
y_pred: torch tensor with size (N,C)
return:
mean of correct prediction
'''
_, predicted = torch.max(outputs.data, 1)
return (predicted == labels).sum().item() / labels.size()[0]
| true |
19a92070d209b3cdac47b061975f600efe47aca0 | Python | jm4l1/meme-generator | /src/QuoteEngine/TXTIngestor.py | UTF-8 | 1,201 | 3.1875 | 3 | [] | no_license | """TXT Ingestor."""
from typing import List
from .IngestorInterface import IngestorInterface, CannotIngestException
from .QuoteModel import QuoteModel
class TXTIngestor(IngestorInterface):
"""Concrete Implementation of IngestorInterface for ingesting TXT type files."""
allowed_extensions = ['txt']
def __init__(self):
"""Create TXTIngestor."""
pass
@classmethod
def parse(cls, path: str) -> List[QuoteModel]:
"""Parse input file into list of QuoteModel objects.
Parameters:
path {str} : The path of the input file to be tested.
Returns
list[QuoteModel] : list of model objects parse from file
Raises:
CannotIngestException
"""
if not cls.can_ingest(path):
raise CannotIngestException('cannot ingest exception')
quotes = []
with open(path, 'r') as input_file:
row = input_file.readline().strip()
while row:
body, author = row.split("-")
body = body.replace("\"", "")
quotes.append(QuoteModel(body, author))
row = input_file.readline().strip()
return quotes
| true |
30a990ae2071bfc90799e58521e2555d02fbcde8 | Python | jedzej/tietopythontraining-basic | /students/myszko_pawel/lesson_01_basics/14_Total cost.py | UTF-8 | 493 | 4.53125 | 5 | [] | no_license | # A cupcake costs A dollars and B cents. Determine, how many dollars and cents should one pay for N cupcakes.
# A program gets three numbers: A, B, N. It should print two numbers: total cost in dollars and cents.
# Read an integer:
A = int(input())
B = int(input())
N = int(input())
# Print a value:
cup_cost_in_cents = A*100 + B
total_cost_in_cents = cup_cost_in_cents * N
cost_in_dol = total_cost_in_cents // 100
cost_in_cen = total_cost_in_cents % 100
print(cost_in_dol)
print(cost_in_cen) | true |
5ce6c9839cd59a7d51a49a9d9feeeded502f8546 | Python | mcncm/cavy-python | /tests/test_loops.py | UTF-8 | 926 | 2.96875 | 3 | [] | no_license | from .templates import stmt_test_template, circuit_test_template
import circuits.gates as gates
# def circuit_test_template(code: str, gates_expected: List[Tuple[type, List[int]]]):
def test_simple_for_loop():
stmt_test_template("""
for i in 0..3 {
print(i);
}
""",
['0', '1', '2'])
def test_squares_loop():
stmt_test_template("""
for i in 0..4 {
print(i * i);
}
""",
['0', '1', '4', '9'])
def test_simple_qubit_loop():
circuit_test_template("""
q <- ?false;
for i in 0..3 {
q <- ~q;
}
""",
[(gates.NotGate, [0])] * 3)
def test_two_qubit_loop():
"""This test should pass *only* any circuit optimizations enabled.
"""
circuit_test_template("""
q <- ?false;
r <- ?false;
for stage in 0..4 {
q <- ~q;
if q {
r <- ~r;
}
}
""",
[(gates.NotGate, [0]), (gates.CnotGate, [0, 1])] * 4)
| true |
c91fdd71b6e42718ec3d03a793d3538bb1d2c3a5 | Python | jinwooahnKHU/Pandas_practice | /Pandas_Dataframe_prac_2.py | UTF-8 | 878 | 3.90625 | 4 | [] | no_license | import pandas as pd
import numpy as np
from random import randint
#Series 연산
#=> Numpy Array에서 사용한 연산자들을 활용할 수 있다.
A = pd.Series([2,4,6], index = [0,1,2])
B = pd.Series([1,3,5], index = [1,2,3])
#index끼리 덧셈을 한다.
print(A + B)
#맞지 않는 index여서 값이 비어있는 곳은 NaN으로 처리가 되는데
#맞지 않는 값을 0으로 해서 더한다.
print(A.add(B, fill_value = 0))
#DataFrame 연산
C = pd.DataFrame(np.random.randint(0,10,(2,2)), columns = list("AB"))
D = pd.DataFrame(np.random.randint(0,10,(3,3)), columns = list("BAC"))
print(C + D)
print(C.add(D, fill_value = 0))
#집계함수 적용가능
data = {"A" : [i + 5 for i in range(3)],
"B" : [i ** 2 for i in range(3)]}
df = pd.DataFrame(data)
print(df['A'].sum())
print(df.sum())
print(df.mean())
| true |
bf8e02c55ddc49dcdfbe4e27b70dcaea689fd318 | Python | AdamZhouSE/pythonHomework | /Code/CodeRecords/2930/60727/255871.py | UTF-8 | 180 | 3.234375 | 3 | [] | no_license | a=int(input())
b=input().split(' ')
b=list(map(int,b))
lim=0
for i in range(1,a-1):
if (b[i]<b[i-1] and b[i]<b[i+1]) or (b[i]>b[i-1] and b[i]>b[i+1]):
lim+=1
print(lim) | true |
34514a1939713f6092f63be2bc8f106f07aef70f | Python | SeanDougherty/team8 | /ProcessingUnit.py | UTF-8 | 4,921 | 2.84375 | 3 | [] | no_license |
class ProcessingUnit(object):
def __init__(self, processing_rate, desired_max_buffer_size):
self.packetBuffer = []
self.packetsDone = []
self.latency = []
self.throughput = []
self.maxBufferSize = desired_max_buffer_size
self.actualMaxBufferSize = 0
self.currentBufferSize = 0
self.processingRate = processing_rate
self.bufferSizeRunningTotal = []
def get_packet_buffer(self):
return self.packetBuffer
def get_max_buffer_size(self):
return self.actualMaxBufferSize
def get_current_buffer_size(self):
return self.currentBufferSize
def calculate_buffer_size(self):
if (self.currentBufferSize > self.actualMaxBufferSize):
self.actualMaxBufferSize = self.currentBufferSize
return self.currentBufferSize
def get_packets_from_done_buffer(self):
return self.packetsDone
def empty_done_buffer(self):
self.packetsDone = []
# Churns through packetBuffer for one simulated millisecond
def process_data(self, ms_being_simulated):
# Create a copy of the processing rate to keep track of how much "processing power" we have left
processing_power = self.processingRate
#print(self.packetBuffer)
#print("packetbuffer[0][0]: " + str(self.packetBuffer[0][0]))
#print("packetbuffer[0][1]: " + str(self.packetBuffer[0][1]))
# print("packetbuffer[0] length: "+ str(len(self.packetBuffer[0])))
# print("packetbuffer length: "+ str(len(self.packetBuffer)))
# print("currentBufferSize: " + str(self.currentBufferSize))
# Process packets in the packetBuffer until your processing power runs out or the packetBuffer is emptied
while processing_power > 0 and len(self.packetBuffer) > 0:
# If there are more packets in the next packetLoad than can be processed in this cycle,
# simply subtract the processing rate from your packetsLeft and update your metrics
if self.packetBuffer[0][0] > processing_power :
self.latency.append(ms_being_simulated - self.packetBuffer[0][1])
self.throughput.append(processing_power)
#print("self.currentBufferSize = " + self.currentBufferSize)
self.currentBufferSize = self.currentBufferSize - processing_power
#print(self.packetBuffer[0]) #debugging
packets_left_to_do = self.packetBuffer[0][0] - processing_power
time_added_to_system = self.packetBuffer[0][1]
packets_done_in_this_cycle = processing_power
self.packetsDone.append((packets_done_in_this_cycle, time_added_to_system))
# print("self.packetDone.append in if: " + str((packets_done_in_this_cycle, time_added_to_system)))
del self.packetBuffer[0]
self.packetBuffer.insert(0, (packets_left_to_do, time_added_to_system))
#print(self.packetBuffer[0]) #debugging
processing_power = 0
# Else if you have enough processing power to process the entire packet_load,
# remove that packet_load and update your metrics
else:
self.latency.append(ms_being_simulated - self.packetBuffer[0][1])
self.throughput.append(self.packetBuffer[0][0])
self.currentBufferSize = self.currentBufferSize - self.packetBuffer[0][0]
self.packetsDone.append(self.packetBuffer[0])
processing_power -= self.packetBuffer[0][0]
# print("self.packetBuffer[0] in else: " + str(self.packetBuffer[0]))
del self.packetBuffer[0]
def add_packets_from_input_list(self, packets_to_process, ms_being_simulated):
packets_to_add = packets_to_process[ms_being_simulated][0]
# print("packets_to_process: " + str(packets_to_process)) #debugging
time_added_to_system = ms_being_simulated
self.packetBuffer.append((packets_to_add, time_added_to_system))
# print("packets_to_add: " + str(packets_to_add)) #debugging
self.currentBufferSize += packets_to_add
self.calculate_buffer_size()
# Add any packets from the done buffer of the previous processing unit. We assume there is no transfer time and
# that all 'processed' packets are able to be passed immediately to the next processing unit
# in the chain.
def add_packets_from_prior_proc_unit(self, proc_unit):
packets_to_add_list = proc_unit.get_packets_from_done_buffer()
for packets_to_add in packets_to_add_list:
self.packetBuffer.append(packets_to_add)
# print("packets being added = " + str(packets_to_add))#debugging
self.currentBufferSize += packets_to_add[0]
self.calculate_buffer_size()
proc_unit.empty_done_buffer()
| true |
1a10a5763d93a1074ad5da9abcf0c9dff2c86583 | Python | TayeeChang/algorithm | /深度优先搜索/Restore IP Addresses.py | UTF-8 | 881 | 2.953125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
# @Time : 2021/5/31 16:18
# @Author : haojie zhang
from typing import List
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
def traceback(s, index, dot, tmp):
if index == len(s) and dot == 4:
res.append('.'.join(tmp))
return
if len(s) - index > (4-dot) * 3: # 多了---剪枝
return
if len(s) - index < (4-dot) * 1: # 少了--剪枝
return
for i in range(index, len(s)):
if i > index and s[index] == '0':
break
if 0 <= int(s[index:i+1]) <= 255:
traceback(s, i+1, dot+1, tmp+[s[index:i+1]])
return
res = []
traceback(s, 0, 0, [])
return res
s = "010010"
obj = Solution()
print(obj.restoreIpAddresses(s)) | true |
3c4e380c6a3dc4c719999f2643b1b7349982c669 | Python | technology-nation-slovakia/meet-room-restapi | /app/sql.py | UTF-8 | 1,590 | 2.859375 | 3 | [] | no_license | # native SQL statements execution module
from app import app, db
from app.console_log import console_log, sql_log
import re
import sqlalchemy.exc
def runSQL(statement):
try:
# log statement
sql_log(statement, 'note')
# execute SQL statement
result = db.engine.execute(statement)
# SELECT statement handling
if re.search(r"^\s*SELECT", statement, re.I):
# transforn result to array of rows
rows = [dict(row) for row in result.fetchall()]
sql_log('Selected {} rows'.format(len(rows)), 'info')
if len(rows) == 1: # in case of result contains single item => return object
rows = rows[0]
elif len(rows) == 0: # empty result
rows = {}
return rows
# INSERT statement handling
elif re.search(r"^\s*INSERT", statement, re.I):
sql_log('Inserted ID: {}'.format(result.lastrowid), 'info')
return result.lastrowid
# DELETE statement handling
elif re.search(r"^\s*DELETE", statement, re.I):
sql_log('Deleted {} rows'.format(result.rowcount), 'info')
return result.rowcount
# UPDATE statement handling
elif re.search(r"^\s*UPDATE", statement, re.I):
sql_log('Updated {} rows'.format(result.rowcount), 'info')
return result.rowcount
# if constraint violated, return None
except sqlalchemy.exc.IntegrityError as err:
console_log('Integrity Error - ' + str(err.orig), 'fail')
return None
| true |
d1c3056e2e0f49d16541c3fdaa7a1241fcf563c2 | Python | YWaller/StrategoProject | /SAI.py | UTF-8 | 8,594 | 2.734375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import random
import numpy as np
from copy import copy,deepcopy
import re
import getboards
sys_random = random.SystemRandom()
pd = {} #piececonversions
pd['1b'] = 1
pd['2b'] = 2
pd['3b'] = 3
pd['4b'] = 4
pd['5b'] = 5
pd['6b'] = 6
pd['7b'] = 7
pd['8b'] = 8
pd['9b'] = 9
pd['10b'] = 10
pd['11b'] = 11
pd['0b'] = 0
pd['1'] = -1
pd['1r'] = 21
pd['2r'] = 22
pd['3r'] = 23
pd['4r'] = 24
pd['5r'] = 25
pd['6r'] = 26
pd['7r'] = 27
pd['8r'] = 28
pd['9r'] = 29
pd['10r'] = 30
pd['0r'] = 20
pd['11r'] = 31
ld = {}
ld[-1] = -1
ld[21] = 1
ld[22] = 2
ld[23] = 3
ld[24] = 4
ld[25] = 5
ld[26] = 6
ld[27] = 7
ld[28] = 8
ld[29] = 9
ld[30] = 10
ld[20] = 0
ld[31] = 11
ld[-1] = -1
ld[1] = 1
ld[2] = 2
ld[3] = 3
ld[4] = 4
ld[5] = 5
ld[6] = 6
ld[7] = 7
ld[8] = 8
ld[9] = 9
ld[10] = 10
ld[0] = 0
ld[11] = 11
def manhattan_dist(move): #order doesn't matter
a = move[0][0]
b = move[0][1]
c = move[1][0]
d = move[1][1]
mandist = abs(a-c)+abs(b-d)
print(mandist,"man dist")
return mandist
#functions copied from main with ai as needed:
def casx(x):
if(x < 150 or x > 650):
return -1
else:
return int((x-150)/50)
def casy(y):
if(y < 50 or y > 550):
return -1
else:
return int((y-50)/50)
class TwoWayDict(dict): #I needed a two way dictionary for my number/board position pairs, so...
def __setitem__(self, key, value):
# Remove any previous connections with these values
if key in self:
del self[key]
if value in self:
del self[value]
dict.__setitem__(self, key, value)
dict.__setitem__(self, value, key)
def __delitem__(self, key):
dict.__delitem__(self, self[key])
dict.__delitem__(self, key)
def __len__(self):
"""Returns the number of connections"""
return dict.__len__(self) // 2
class AI_Player():
def __init__(self,color,board):
self.color = color
self.totalAllies = {'11':6,'10':1,'9':1,'8':1,'7':1,'6':2,'5':2,'4':2,'3':5,'2':7,'1':1,'0':1}
self.totalEnemies = {'11':6,'10':1,'9':1,'8':1,'7':1,'6':2,'5':2,'4':2,'3':5,'2':7,'1':1,'0':1}
self.hiddenornotdict = dict.fromkeys(range(0, 100), 0) #as pieces are positively identified, we'll change their hidden dict value from 0 to 1
self.hiddenornotdict['-1'] = 0
self.turncount = 0
def rank_value_calc(self,totalAllies,totalEnemies):
#Our pieces
basevalue=dict()
rankdifffactor=1.45
for i in range(12):
basevalue[str(i)]= 0.0
basevalue[str(1)] = .05
for i in range(2,11):
if (self.totalAllies[str(i-1)]+self.totalAllies[str(i)] > 0) and (self.totalEnemies[str(i-1)]+self.totalEnemies[str(i)]>0):
basevalue[str(i)] = basevalue[str(i-1)]*rankdifffactor
else:
basevalue[str(i)] = basevalue[str(i-1)]
#gets the highest value of basevalue for scaling
highest = max(basevalue.values())
#scale all the values and then add a value
for i in range(11):
basevalue[str(i)] = float(basevalue[str(i)])/float(highest)+(.5/sum(basevalue.values()))
#specific pieces with alternate values
#if there's an enemy spy, reduce the 10's importance
if self.totalEnemies[str(1)] != 0:
basevalue[str(10)] = basevalue[str(10)]*.8
#highest = max(basevalue.itervalues(), key=(lambda key: basevalue[key]))
highest = max(basevalue.values())
basevalue[str(1)] = basevalue[str(10)]/2
basevalue[str(0)] = highest+.5
basevalue[str(11)] = highest/2
#if there are fewer than 3 miners, make them more valuable
if self.totalAllies[str(3)] >= 3:
basevalue[str(3)] = basevalue[str(3)]*((4-self.totalAllies[str(3)])/2)
#if there are fewer than 3 scouts, make them more valuable
if self.totalAllies[str(2)] >= 3:
basevalue[str(2)] = basevalue[str(2)]*((4-self.totalAllies[str(2)])/3)
#if enemy unit is hidden and has moved, make its value higher than the 2
#if its hidden and has moved, make its value
return basevalue
def read_in_go(self,board_version_moves,turncount,previous_move,board,piecelist):
#this function houses the main AI logic
def check_unit_ai(move): #given a board position, finds the matching class object and return its identifier
for piece in piecelist:
if (move[0],move[1]) == piece.get_pos():
return piece.identifier
for piece in piecelist:
print(piece.get_pos())
print(move,"move")
self.allyrankvalues = self.rank_value_calc(self.totalAllies,self.totalEnemies)
self.enemyrankvalues = self.rank_value_calc(self.totalEnemies,self.totalAllies)
#this board should be numbered 1-60, with -1s filling in the other spaces. It lets us know where each specific piece is.
#make initial board...
ai_board = np.asarray(board)
x=0
y=0
for row in ai_board:
x=0
for piece in row:
ai_board[y,x] = pd[re.sub(r'[\W_]+', '', ai_board[y,x])]
x+=1
y+=1
ai_board = ai_board.astype(int)
allmovesforfunc = []
for option in board_version_moves:
yps = option[0]-1 #y
xps = option[1]
ypt = casy(option[2].rect.centery)-1
xpt = casx(option[2].rect.centerx)
move = ((ypt,xpt),(yps,xps)) #MOVE[0] IS SOURCE
allmovesforfunc.append(move)
#print(self.hiddenornotdict)
deletion_indices = []
deletioncounter = 0
for move in allmovesforfunc: #all of this code is to get the AI to not attack pieces it has learned are larger than whatever the piece its focused on is
if self.hiddenornotdict[check_unit_ai((move[0][1],move[0][0]+1))] == 1: #check if the unit is hidden or not #tuple(reversed(move[0]))
if ld[ai_board[move[1]]] > ld[ai_board[move[0]]]: #if the unit at this position is bigger than this piece, remove the move from consideration
#so to make this a "memory" index, pick a random number between 1 and 10; if it's lower than whatever, don't assign the move, and make that piece hidden again
deletion_indices.append(copy(deletioncounter))
print("NOT THAT DUMB")
deletioncounter+=1
if len(deletion_indices) < len(allmovesforfunc): #prevents us from removing all our valid moves, but it's a bad place to be in if they're all attacking pieces bigger than us...
for index in reversed(deletion_indices):
print("move deleted: ",allmovesforfunc[index])
del allmovesforfunc[index]
#for the objective function, sum the number of allied pieces that are hidden and subtract the number of enemy pieces that are
ai_board = np.asarray(ai_board)
#[((1,0),(0,0)),((0,1),(0,0))]
self.turncount+=2
#if turncount is low, we don't really need to spend too much time on our move. Let's speed things up a bit...
recursion_send = 7
if self.turncount < 50:
recursion_send = 6
elif self.turncount < 30:
recursion_send = 5
elif self.turncount < 10:
recursion_send = 4
movestrengths = getboards.move_strength_ultimate([ai_board],allmovesforfunc,recursion_send) #current board, move list, recursion_depth; I don't recommend values above 10
justnumbers = []
for move in movestrengths:
#print(move)
justnumbers.append(copy(move))
print(justnumbers)
random.shuffle(justnumbers) #so if a couple have the same value, we'll get a random one of the best, since max takes the first occurrence of that value
move = board_version_moves[justnumbers.index(max(justnumbers))]
print("move selection complete.")
return move
| true |
bf3249b52e0bb7fc9d8f2f694f39db8b78e09e09 | Python | Anoopsmohan/Ignite-Solutions- | /que1.py | UTF-8 | 216 | 3.25 | 3 | [] | no_license | import sys,re
def main():
str1=raw_input("Enter the string: ")
#re.sub() used to find each word and reverse it
print re.sub(r'[-\w]+', lambda w:w.group()[::-1],str1)
if __name__=='__main__':
main()
| true |
4786a55e9b5f430f967a46f3373235f423d03cea | Python | hrGuTou/DHMS-Custom-Pizza | /order.py | UTF-8 | 917 | 3.265625 | 3 | [] | no_license | """
Individual order
class order
- pizza type
- topping
- sauce
- customer name
- customer phone number
"""
class OrderPizza():
def __init__(self,pizza_type, cust_name, cust_phonenum, toppings, sauce):
self.type = pizza_type
self.name = cust_name
self.phonenumber = cust_phonenum
self.toppings = toppings
self.sauce = sauce
#list_pizza=[] # emty list to store the selected pizza
def setType(self, newType):
self.type = newType
def setName(self, newName):
self.name = newName
def setNumber(self, newPhone):
self.phonenumber = newPhone
def setTopping(self, newTopping):
self.toppings = newTopping
def setSauce(self, newSauce):
self.sauce = newSauce
def __str__(self):
return f"\n Customer Name: {self.name},\n Customer Phone Number: {self.phonenumber},\n Type of Pizza: {self.type},\n Toppings: {self.toppings},\n Sauce: {self.sauce}\n"
| true |
bb993b073273962d489cf35113dce937c0216d11 | Python | JavierLavados/ComputacionGrafica | /PeceraEDP/Peces.py | UTF-8 | 22,865 | 2.828125 | 3 | [] | no_license | # coding=utf-8
"""
Daniel Calderon, CC3501, 2019-2
Projections example
"""
import glfw
from OpenGL.GL import *
import OpenGL.GL.shaders
import numpy as np
import sys
import transformations as tr
import basic_shapes as bs
import easy_shaders as es
import scene_graph as sg
import lighting_shaders as ls
import local_shapes as l
PROJECTION_ORTHOGRAPHIC = 0
PROJECTION_FRUSTUM = 1
PROJECTION_PERSPECTIVE = 2
# A class to store the application control
class Controller:
def __init__(self):
self.fillPolygon = True
self.projection = PROJECTION_ORTHOGRAPHIC
# We will use the global controller as communication with the callback function
controller = Controller()
def on_key(window, key, scancode, action, mods):
if action != glfw.PRESS:
return
global controller
if key == glfw.KEY_SPACE:
controller.fillPolygon = not controller.fillPolygon
elif key == glfw.KEY_1:
print('Orthographic projection')
controller.projection = PROJECTION_ORTHOGRAPHIC
elif key == glfw.KEY_2:
print('Frustum projection')
controller.projection = PROJECTION_FRUSTUM
elif key == glfw.KEY_3:
print('Perspective projection')
controller.projection = PROJECTION_PERSPECTIVE
elif key == glfw.KEY_ESCAPE:
glfw.set_window_should_close(window, True)
import numpy as np
import matplotlib.pyplot as mpl
from mpl_toolkits.mplot3d import Axes3D
def generateT(t):
return np.array([[1, t, t**2, t**3]]).T
def hermiteMatrix(P1, P2, T1, T2):
# Generate a matrix concatenating the columns
G = np.concatenate((P1, P2, T1, T2), axis=1)
# Hermite base matrix is a constant
Mh = np.array([[1, 0, -3, 2], [0, 0, 3, -2], [0, 1, -2, 1], [0, 0, -1, 1]])
return np.matmul(G, Mh)
def bezierMatrix(P0, P1, P2, P3):
# Generate a matrix concatenating the columns
G = np.concatenate((P0, P1, P2, P3), axis=1)
# Bezier base matrix is a constant
Mb = np.array([[1, -3, 3, -1], [0, 3, -6, 3], [0, 0, 3, -3], [0, 0, 0, 1]])
return np.matmul(G, Mb)
def plotCurve(ax, curve, label, color=(0,0,1)):
xs = curve[:, 0]
ys = curve[:, 1]
zs = curve[:, 2]
ax.plot(xs, ys, zs, label=label, color=color)
# M is the cubic curve matrix, N is the number of samples between 0 and 1
def evalCurve(M, N):
# The parameter t should move between 0 and 1
ts = np.linspace(0.0, 1.0, N)
# The computed value in R3 for each sample will be stored here
curve = np.ndarray(shape=(N, 3), dtype=float)
for i in range(len(ts)):
T = generateT(ts[i])
curve[i, 0:3] = np.matmul(M, T).T
return curve
def createAleta(N):
R0L = np.array([[0, 0.5, 0]]).T
R1L = np.array([[-0.5, 0.1, 0]]).T
R2L = np.array([[-0.3, -0.5, 0]]).T
R3L = np.array([[0, -0.5, 0]]).T
GMbL = bezierMatrix(R0L, R1L, R2L, R3L) # Puntos de control
bezierCurveLeft = evalCurve(GMbL, N)
R0R = np.array([[0, 0.5, 0]]).T
R1R = np.array([[0.5, 0.1, 0]]).T
R2R = np.array([[0.3, -0.5, 0]]).T
R3R = np.array([[0, -0.5, 0]]).T
GMbR = bezierMatrix(R0R, R1R, R2R, R3R) # Puntos de control
bezierCurveRight = evalCurve(GMbR, N)
vertexDataList = []
indicesList = []
for index in range(len(bezierCurveLeft)):
vertex = bezierCurveLeft[index]
vertexDataList.extend(vertex)
vertexDataList.extend([0, 0, 0])
vertex = bezierCurveRight[index]
vertexDataList.extend(vertex)
vertexDataList.extend([0, 0, 0])
for index in range(2*len(bezierCurveLeft)):
indicesList += [index, index + 1, index + 2]
# Here the new shape will be stored
return bs.Shape(vertexDataList,indicesList)
def createAleta2(N):
R0L = np.array([[0, 0.5, 0]]).T
R1L = np.array([[-0.5, 0.1, 0]]).T
R2L = np.array([[-0.6, -0.5, 0]]).T
R3L = np.array([[-0.2, 0.7 , 0]]).T
R4L = np.array([[0, 0, 0]]).T
GMbL = bezierMatrix(R0L, R1L, R2L, R3L) # Puntos de control
bezierCurveLeft = evalCurve(GMbL, N)
R0R = np.array([[0, 0.5, 0]]).T
R1R = np.array([[0.5, 0.1, 0]]).T
R2R = np.array([[0.6, -0.7, 0]]).T
R3L = np.array([[0.2, 0.8, 0]]).T
R3R = np.array([[0, 0, 0]]).T
GMbR = bezierMatrix(R0R, R1R, R2R, R3R) # Puntos de control
bezierCurveRight = evalCurve(GMbR, N)
vertexDataList = []
indicesList = []
for index in range(len(bezierCurveLeft)):
vertex = bezierCurveLeft[index]
vertexDataList.extend(vertex)
vertexDataList.extend([0, 0, 0])
vertex = bezierCurveRight[index]
vertexDataList.extend(vertex)
vertexDataList.extend([0, 0, 0])
for index in range(2*len(bezierCurveLeft)):
indicesList += [index, index + 1, index + 2]
# Here the new shape will be stored
return bs.Shape(vertexDataList,indicesList)
def createPezA():
GpuCuerpo=esfera=es.toGPUShape(l.esfera(30,30,[57/255, 1, 20/255]))
GpuOjo=es.toGPUShape(l.generateCirculo(15))
GpuAletas=es.toGPUShape(createAleta(20))
Cuerpo = sg.SceneGraphNode("Cuerpo")
Cuerpo.transform=tr.matmul([tr.translate(0,0,0.9),tr.scale(2,0.6,1)])
Cuerpo.childs+=[GpuCuerpo]
Body = sg.SceneGraphNode("Body")
Body.childs+=[Cuerpo]
Cola1 = sg.SceneGraphNode("Cola1")
Cola1.transform=tr.matmul([tr.rotationY(-2),tr.rotationX(3.14/2),tr.scale(1.4,2,1)])
Cola1.childs+=[GpuAletas]
Cola2 = sg.SceneGraphNode("Cola2")
Cola2.transform=tr.matmul([tr.rotationY(5),tr.rotationX(3.14/2),tr.scale(1.4,2,1)])
Cola2.childs+=[GpuAletas]
ColaMov1 = sg.SceneGraphNode("ColaMov1")
ColaMov1.childs+=[Cola1]
ColaMov2 = sg.SceneGraphNode("ColaMov2")
ColaMov2.childs+=[Cola2]
ColaF1 = sg.SceneGraphNode("ColaF1")
ColaF1.transform=tr.translate(-2.5,0,0.6)
ColaF1.childs+=[ColaMov1]
ColaF2 = sg.SceneGraphNode("ColaF2")
ColaF2.transform=tr.translate(-2.5,0,1),
ColaF2.childs+=[ColaMov2]
ColaF = sg.SceneGraphNode("ColaF")
ColaF.childs+=[ColaF1]
ColaF.childs+=[ColaF2]
Cresta1 = sg.SceneGraphNode("Cresta1")
Cresta1.transform=tr.matmul([tr.translate(0.5,0,1.5),tr.rotationY(2.8),tr.rotationX(3.14/2),tr.scale(1.4,2,1)])
Cresta1.childs+=[GpuAletas]
Cresta2 = sg.SceneGraphNode("Cresta2")
Cresta2.transform=tr.matmul([tr.translate(0.1,0,1.3),tr.rotationY(2.8),tr.rotationX(3.14/2),tr.scale(1.4,2,1)])
Cresta2.childs+=[GpuAletas]
Aleta1 = sg.SceneGraphNode("Aleta1")
Aleta1.transform=tr.matmul([tr.translate(0,-0.6,0.2),tr.rotationZ(0.5),tr.rotationY(4),tr.rotationX(3.14/2),tr.scale(1.3,1.3,1.5)])
Aleta1.childs+=[GpuAletas]
Aleta2 = sg.SceneGraphNode("Aleta2")
Aleta2.transform=tr.matmul([tr.translate(0,0.6,0.2),tr.rotationZ(-0.5),tr.rotationY(4),tr.rotationX(3.14/2),tr.scale(1.3,1.3,1.5)])
Aleta2.childs+=[GpuAletas]
Ojo1 = sg.SceneGraphNode("Ojo1")
Ojo1.transform=tr.matmul([tr.translate(1,0.53,1),tr.rotationZ(-0.1),tr.rotationX(3.14/2),tr.scale(0.2,0.3,0.2)])
Ojo1.childs+=[GpuOjo]
Ojo2 = sg.SceneGraphNode("Ojo2")
Ojo2.transform=tr.matmul([tr.translate(1,-0.53,1),tr.rotationZ(0.1),tr.rotationX(3.14/2),tr.scale(0.2,0.3,0.2)])
Ojo2.childs+=[GpuOjo]
Aletas = sg.SceneGraphNode("Aletas")
Aletas.childs+=[Aleta1]
Aletas.childs+=[Aleta2]
Aletas.childs+=[ColaF]
Aletas.childs+=[Cresta1]
Aletas.childs+=[Cresta2]
Ojos = sg.SceneGraphNode("Ojos")
Ojos.childs+=[Ojo1]
Ojos.childs+=[Ojo2]
todo = sg.SceneGraphNode("todo")
todo.childs+=[Body]
todo.childs+=[Aletas]
todo.childs+=[Ojos]
return todo
def createPezB():
GpuCuerpo=esfera=es.toGPUShape(l.esfera(30,30,[225/255,35/255,1/255]))
GpuOjo=es.toGPUShape(l.generateCirculo(15))
GpuAletas=es.toGPUShape(createAleta(20))
GpuAletas2=es.toGPUShape(createAleta2(20))
Cuerpo = sg.SceneGraphNode("Cuerpo")
Cuerpo.transform=tr.matmul([tr.translate(0,0,0.9),tr.scale(4,0.6,1)])
Cuerpo.childs+=[GpuCuerpo]
Body = sg.SceneGraphNode("Body")
Body.childs+=[Cuerpo]
Cola1 = sg.SceneGraphNode("Cola1")
Cola1.transform=tr.matmul([tr.rotationY(3.14/2),tr.rotationX(3.14/2),tr.scale(-1,2,1)])
Cola1.childs+=[GpuAletas2]
Cola2 = sg.SceneGraphNode("Cola2")
Cola2.transform=tr.matmul([tr.rotationY(3.14/2),tr.rotationX(3.14/2),tr.scale(1,2,1)])
Cola2.childs+=[GpuAletas2]
ColaMov1 = sg.SceneGraphNode("ColaMov1")
ColaMov1.childs+=[Cola1]
ColaMov2 = sg.SceneGraphNode("ColaMov2")
ColaMov2.childs+=[Cola2]
ColaF1 = sg.SceneGraphNode("ColaF1")
ColaF1.transform=tr.translate(-4.5,0,1.2)
ColaF1.childs+=[ColaMov1]
ColaF2 = sg.SceneGraphNode("ColaF2")
ColaF2.transform=tr.translate(-4.5,0,0.8)
ColaF2.childs+=[ColaMov2]
ColaF = sg.SceneGraphNode("ColaF")
ColaF.childs+=[ColaF1]
ColaF.childs+=[ColaF2]
Cresta1 = sg.SceneGraphNode("Cresta1")
Cresta1.transform=tr.matmul([tr.translate(-0.5,0,1.8),tr.rotationY(2.3),tr.rotationX(3.14/2),tr.scale(1,1,1)])
Cresta1.childs+=[GpuAletas]
Cresta2 = sg.SceneGraphNode("Cresta2")
Cresta2.transform=tr.matmul([tr.translate(-0.55,0,2.25),tr.rotationY(5.44),tr.rotationX(3.14/2),tr.scale(0.2,1,1)])
Cresta2.childs+=[GpuAletas]
Cresta3 = sg.SceneGraphNode("Cresta3")
Cresta3.transform=tr.matmul([tr.translate(-0.75,0,2.24),tr.rotationY(5.44),tr.rotationX(3.14/2),tr.scale(0.2,1,1)])
Cresta3.childs+=[GpuAletas]
Cresta4 = sg.SceneGraphNode("Cresta4")
Cresta4.transform=tr.matmul([tr.translate(-0.95,0,2.2),tr.rotationY(5.44),tr.rotationX(3.14/2),tr.scale(0.2,1,1)])
Cresta4.childs+=[GpuAletas]
Cresta5 = sg.SceneGraphNode("Cresta5")
Cresta5.transform=tr.matmul([tr.translate(-1.15,0,2.1),tr.rotationY(5.44),tr.rotationX(3.14/2),tr.scale(0.2,1,1)])
Cresta5.childs+=[GpuAletas]
Aleta1 = sg.SceneGraphNode("Aleta1")
Aleta1.transform=tr.matmul([tr.translate(0.5,-0.6,0.3),tr.rotationZ(0.4),tr.rotationY(3.14/2),tr.rotationX(3.14/2),tr.scale(0.7,1.5,1.5)])
Aleta1.childs+=[GpuAletas]
Aleta2 = sg.SceneGraphNode("Aleta2")
Aleta2.transform=tr.matmul([tr.translate(0.5,0.6,0.3),tr.rotationZ(-0.4),tr.rotationY(3.14/2),tr.rotationX(3.14/2),tr.scale(0.7,1.5,1.5)])
Aleta2.childs+=[GpuAletas]
Ojo1 = sg.SceneGraphNode("Ojo1")
Ojo1.transform=tr.matmul([tr.translate(2,0.55,1.2),tr.rotationZ(-0.1),tr.rotationX(3.14/2),tr.scale(0.2,0.3,0.2)])
Ojo1.childs+=[GpuOjo]
Ojo2 = sg.SceneGraphNode("Ojo2")
Ojo2.transform=tr.matmul([tr.translate(2,-0.55,1.2),tr.rotationZ(0.1),tr.rotationX(3.14/2),tr.scale(0.2,0.3,0.2)])
Ojo2.childs+=[GpuOjo]
Aletas = sg.SceneGraphNode("Aletas")
Aletas.childs+=[Aleta1]
Aletas.childs+=[Aleta2]
Aletas.childs+=[ColaF]
Aletas.childs+=[Cresta1]
Aletas.childs+=[Cresta2]
Aletas.childs+=[Cresta3]
Aletas.childs+=[Cresta4]
Aletas.childs+=[Cresta5]
Ojos = sg.SceneGraphNode("Ojos")
Ojos.childs+=[Ojo1]
Ojos.childs+=[Ojo2]
todo = sg.SceneGraphNode("todo")
todo.childs+=[Body]
todo.childs+=[Aletas]
todo.childs+=[Ojos]
return todo
def createPezC():
GpuCuerpo=esfera=es.toGPUShape(l.esfera(30,30,[1,128/255,0]))
GpuOjo=es.toGPUShape(l.generateCirculo(15))
GpuAletas=es.toGPUShape(createAleta(20))
GpuAletas2=es.toGPUShape(createAleta2(20))
Cuerpo = sg.SceneGraphNode("Cuerpo")
Cuerpo.transform=tr.matmul([tr.translate(0,0,0.9),tr.scale(3,0.7,2)])
Cuerpo.childs+=[GpuCuerpo]
Body = sg.SceneGraphNode("Body")
Body.childs+=[Cuerpo]
Cola1 = sg.SceneGraphNode("Cola1")
Cola1.transform=tr.matmul([tr.rotationY(3.14/2),tr.rotationX(3.14/2),tr.scale(-2,3,1)])
Cola1.childs+=[GpuAletas2]
Cola2 = sg.SceneGraphNode("Cola2")
Cola2.transform=tr.matmul([tr.rotationY(3.14/2),tr.rotationX(3.14/2),tr.scale(2,3,1)])
Cola2.childs+=[GpuAletas2]
ColaMov1 = sg.SceneGraphNode("ColaMov1")
ColaMov1.childs+=[Cola1]
ColaMov2 = sg.SceneGraphNode("ColaMov2")
ColaMov2.childs+=[Cola2]
ColaF1 = sg.SceneGraphNode("ColaF1")
ColaF1.transform=tr.translate(-4,0,1.5)
ColaF1.childs+=[ColaMov1]
ColaF2 = sg.SceneGraphNode("ColaF2")
ColaF2.transform=tr.translate(-4,0,0.5)
ColaF2.childs+=[ColaMov2]
ColaF = sg.SceneGraphNode("ColaF")
ColaF.childs+=[ColaF1]
ColaF.childs+=[ColaF2]
Cresta1 = sg.SceneGraphNode("Cresta1")
Cresta1.transform=tr.matmul([tr.translate(-0.5,0,2.3),tr.rotationY(3.14/2),tr.rotationX(3.14/2),tr.scale(4,5,1)])
Cresta1.childs+=[GpuAletas]
Cresta2 = sg.SceneGraphNode("Cresta2")
Cresta2.transform=tr.matmul([tr.translate(-0.5,0,-0.4),tr.rotationY(3.14/2),tr.rotationX(3.14/2),tr.scale(4,5,1)])
Cresta2.childs+=[GpuAletas]
Aleta1 = sg.SceneGraphNode("Aleta1")
Aleta1.transform=tr.matmul([tr.translate(0,-0.75,0.3),tr.rotationZ(0.4),tr.rotationY(3.14/2),tr.rotationX(3.14/2),tr.scale(2,1.3,1.5)])
Aleta1.childs+=[GpuAletas]
Aleta2 = sg.SceneGraphNode("Aleta2")
Aleta2.transform=tr.matmul([tr.translate(0,0.75,0.3),tr.rotationZ(-0.4),tr.rotationY(3.14/2),tr.rotationX(3.14/2),tr.scale(2,1.3,1.5)])
Aleta2.childs+=[GpuAletas]
Ojo1 = sg.SceneGraphNode("Ojo1")
Ojo1.transform=tr.matmul([tr.translate(1.4,0.72,1),tr.rotationZ(-0.1),tr.rotationX(3.14/2),tr.scale(0.2,0.3,0.2)])
Ojo1.childs+=[GpuOjo]
Ojo2 = sg.SceneGraphNode("Ojo2")
Ojo2.transform=tr.matmul([tr.translate(1.4,-0.72,1),tr.rotationZ(0.1),tr.rotationX(3.14/2),tr.scale(0.2,0.3,0.2)])
Ojo2.childs+=[GpuOjo]
Aletas = sg.SceneGraphNode("Aletas")
Aletas.childs+=[Aleta1]
Aletas.childs+=[Aleta2]
Aletas.childs+=[ColaF]
Aletas.childs+=[Cresta1]
Aletas.childs+=[Cresta2]
Ojos = sg.SceneGraphNode("Ojos")
Ojos.childs+=[Ojo1]
Ojos.childs+=[Ojo2]
todo = sg.SceneGraphNode("todo")
todo.childs+=[Body]
todo.childs+=[Aletas]
todo.childs+=[Ojos]
return todo
if __name__ == "__main__":
# Initialize glfw
if not glfw.init():
sys.exit()
width = 600
height = 600
window = glfw.create_window(width, height, "Modelos de peces", None, None)
if not window:
glfw.terminate()
sys.exit()
glfw.make_context_current(window)
# Connecting the callback function 'on_key' to handle keyboard events
glfw.set_key_callback(window, on_key)
# Assembling the shader program
pipeline3D = es.SimpleModelViewProjectionShaderProgram()
pipeline3DTexture= es.SimpleTextureModelViewProjectionShaderProgram()
pipelinePhong = ls.SimplePhongShaderProgram()
pipelinePhongTexture=ls.SimpleTexturePhongShaderProgram()
# Telling OpenGL to use our shader program
# Setting up the clear screen color
glClearColor(0.15, 0.15, 0.15, 1.0)
# As we work in 3D, we need to check which part is in front,
# and which one is at the back
glEnable(GL_DEPTH_TEST)
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
# Creating shapes on GPU memory
AXE=es.toGPUShape(bs.createAxis(100))
gpupez1=createPezA()
gpupez2=createPezB()
gpupez3=createPezC()
import random
t0 = glfw.get_time()
camera_theta = np.pi/4
angulo =0
reversa=False
while not glfw.window_should_close(window):
# Using GLFW to check for input events
glfw.poll_events()
# Getting the time difference from the previous iteration
t1 = glfw.get_time()
dt = t1 - t0
t0 = t1
if (glfw.get_key(window, glfw.KEY_LEFT) == glfw.PRESS):
camera_theta -= 2 * dt
if (glfw.get_key(window, glfw.KEY_RIGHT) == glfw.PRESS):
camera_theta += 2* dt
# Setting up the view transform
camX = 5 * np.sin(camera_theta)
camY = 5* np.cos(camera_theta)
viewPos = np.array([camX, camY, 2])
#viewPos = np.array([0, 0, 10])
view = tr.lookAt(
viewPos,
np.array([0,0,0]),
np.array([0,0,1])
)
# Setting up the projection transform
if controller.projection == PROJECTION_ORTHOGRAPHIC:
projection = tr.ortho(-8, 8, -8, 8, 0.1, 100)
elif controller.projection == PROJECTION_FRUSTUM:
projection = tr.frustum(-5, 5, -5, 5, 9, 100)
elif controller.projection == PROJECTION_PERSPECTIVE:
projection = tr.perspective(60, float(width)/float(height), 0.1, 100)
else:
raise Exception()
# Clearing the screen in both, color and depth
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
# Filling or not the shapes depending on the controller state
if (controller.fillPolygon):
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
else:
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
# Drawing shapes with different model transformations
###############################################################################
# pez3=dt/2 y 0.05
# pez2= dt y 0.1
# pez1= dt*2 y 0.1
if reversa==False:
angulo+=dt*2
if angulo>0.1:
reversa=True
elif reversa==True:
angulo-=dt*2
if angulo<-0.1:
reversa=False
#########################################################################
glUseProgram(pipelinePhong.shaderProgram)
glUniform3f(glGetUniformLocation(pipelinePhong.shaderProgram, "La"), 1.0, 1.0, 1.0)
glUniform3f(glGetUniformLocation(pipelinePhong.shaderProgram, "Ld"), 1.0, 1.0, 1.0)
glUniform3f(glGetUniformLocation(pipelinePhong.shaderProgram, "Ls"), 1.0, 1.0, 1.0)
glUniform3f(glGetUniformLocation(pipelinePhong.shaderProgram, "Ka"), 0.2, 0.2, 0.2)
glUniform3f(glGetUniformLocation(pipelinePhong.shaderProgram, "Kd"), 0.9, 0.5, 0.5)
glUniform3f(glGetUniformLocation(pipelinePhong.shaderProgram, "Ks"), 1.0, 1.0, 1.0)
glUniform3f(glGetUniformLocation(pipelinePhong.shaderProgram, "lightPosition"), -5, -5, 5)
glUniform3f(glGetUniformLocation(pipelinePhong.shaderProgram, "viewPosition"), viewPos[0], viewPos[1], viewPos[2])
glUniform1ui(glGetUniformLocation(pipelinePhong.shaderProgram, "shininess"), 100)
glUniform1f(glGetUniformLocation(pipelinePhong.shaderProgram, "constantAttenuation"), 0.0001)
glUniform1f(glGetUniformLocation(pipelinePhong.shaderProgram, "linearAttenuation"), 0.03)
glUniform1f(glGetUniformLocation(pipelinePhong.shaderProgram, "quadraticAttenuation"), 0.01)
glUniformMatrix4fv(glGetUniformLocation(pipelinePhong.shaderProgram, "projection"), 1, GL_TRUE, projection)
glUniformMatrix4fv(glGetUniformLocation(pipelinePhong.shaderProgram, "view"), 1, GL_TRUE, view)
Cuerpo = sg.findNode(gpupez1, "Body")
Cuerpo2 = sg.findNode(gpupez2, "Body")
Cuerpo2.transform= tr.translate(0,3,0)
Cuerpo3 = sg.findNode(gpupez3, "Body")
Cuerpo3.transform=tr.translate(0,-3,0)
sg.drawSceneGraphNode(Cuerpo,pipelinePhong, "model")
sg.drawSceneGraphNode(Cuerpo2,pipelinePhong, "model")
sg.drawSceneGraphNode(Cuerpo3,pipelinePhong, "model")
#############################################################################################################
glUseProgram(pipelinePhongTexture.shaderProgram)
glUniform3f(glGetUniformLocation(pipelinePhongTexture.shaderProgram, "La"), 1.0, 1.0, 1.0)
glUniform3f(glGetUniformLocation(pipelinePhongTexture.shaderProgram, "Ld"), 1.0, 1.0, 1.0)
glUniform3f(glGetUniformLocation(pipelinePhongTexture.shaderProgram, "Ls"), 1.0, 1.0, 1.0)
glUniform3f(glGetUniformLocation(pipelinePhongTexture.shaderProgram, "Ka"), 0.7, 0.7, 0.7)
glUniform3f(glGetUniformLocation(pipelinePhongTexture.shaderProgram, "Kd"), 0.9, 0.5, 0.5)
glUniform3f(glGetUniformLocation(pipelinePhongTexture.shaderProgram, "Ks"), 1.0, 1.0, 1.0)
glUniform3f(glGetUniformLocation(pipelinePhongTexture.shaderProgram, "lightPosition"), 0, 0, 10)
glUniform3f(glGetUniformLocation(pipelinePhongTexture.shaderProgram, "viewPosition"), viewPos[0], viewPos[1], viewPos[2])
glUniform1ui(glGetUniformLocation(pipelinePhongTexture.shaderProgram, "shininess"), 100)
glUniform1f(glGetUniformLocation(pipelinePhongTexture.shaderProgram, "constantAttenuation"), 0.01)
glUniform1f(glGetUniformLocation(pipelinePhongTexture.shaderProgram, "linearAttenuation"), 0.03)
glUniform1f(glGetUniformLocation(pipelinePhongTexture.shaderProgram, "quadraticAttenuation"), 0.01)
glUniformMatrix4fv(glGetUniformLocation(pipelinePhongTexture.shaderProgram, "projection"), 1, GL_TRUE, projection)
glUniformMatrix4fv(glGetUniformLocation(pipelinePhongTexture.shaderProgram, "view"), 1, GL_TRUE, view)
#############################################################
glUseProgram(pipeline3D.shaderProgram)
glUniformMatrix4fv(glGetUniformLocation(pipeline3D.shaderProgram, "projection"), 1, GL_TRUE, projection)
glUniformMatrix4fv(glGetUniformLocation(pipeline3D.shaderProgram, "view"), 1, GL_TRUE, view)
# glUniformMatrix4fv(glGetUniformLocation(pipeline3D.shaderProgram, "model"), 1, GL_TRUE, tr.identity())
# pipeline3D.drawShape(AXE,GL_LINES)
Aletas1 = sg.findNode(gpupez1, "Aletas")
Cola1 = sg.findNode(gpupez1, "ColaF")
Cola1.transform=tr.rotationZ(angulo)
Aletas2 = sg.findNode(gpupez2, "Aletas")
Aletas2.transform=tr.translate(0,3,0)
Cola2 = sg.findNode(gpupez2, "ColaF")
Cola2.transform=tr.rotationZ(angulo)
Aletas3 = sg.findNode(gpupez3, "Aletas")
Aletas3.transform=tr.translate(0,-3,0)
Cola3 = sg.findNode(gpupez3, "ColaF")
Cola3.transform=tr.rotationZ(angulo)
sg.drawSceneGraphNode(Aletas1,pipeline3D, "model")
sg.drawSceneGraphNode(Aletas2,pipeline3D, "model")
sg.drawSceneGraphNode(Aletas3,pipeline3D, "model")
Ojos = sg.findNode(gpupez1, "Ojos")
Ojos2 = sg.findNode(gpupez2, "Ojos")
Ojos2.transform=tr.translate(0,3,0)
Ojos3 = sg.findNode(gpupez3, "Ojos")
Ojos3.transform=tr.translate(0,-3,0)
sg.drawSceneGraphNode(Ojos,pipeline3D, "model")
sg.drawSceneGraphNode(Ojos2,pipeline3D, "model")
sg.drawSceneGraphNode(Ojos3,pipeline3D, "model")
glfw.swap_buffers(window)
glfw.terminate()
| true |
5c383deafb987981714ca0c2ba12c4965e168903 | Python | goel-aman/Erp-Backend-Code | /server/core/lib/transactional_manager.py | UTF-8 | 4,803 | 2.84375 | 3 | [] | no_license | """
Transaction manager : This is used for all achieving the transactional behaviour accross multiple
medium like databases, files, web service connection, etc. If any one of the medium fails, this will
rollback remaining all medium which are involved.
"""
import sys
import inspect
from datetime import datetime
from core.lib.dbmanager import MySqlDBManager
class TransactionalManager(object):
"""
:Note: Performs transaction behaviour which involves database, files and webservice
transaction
"""
def __init__(self, cursor_type=None):
self.storage_mapping = {
"MYSQL": MySqlDBManager
}
self.modes = ["READWRITE", "READ", "SECONDARY_DB"]
self.cursor_type = cursor_type
self.__database_conn_objects = {}
def GetDatabaseConnection(self, mode):
"""
:Note: Get new connection if the given section is not participated yet else returns
old connection
:Args:
section : LOAN/ACCOUNT/..
mode : READ / READWRITE
:Returns:
database wrapper object
"""
# logger.info("Inside TransactionalManager.get_database_connection ")
server_mode = None
if mode not in self.modes:
# logger.debug("Given mode value is not exists - section : %s, mode = %s", section, mode)
raise ValueError("Database Mode not exists")
else:
server_mode = mode
# storage = ConfigManager.getConfigManager(section='DBCREDENTIALS',
#
old_db_con_obj = self.__database_conn_objects.get(mode)
if old_db_con_obj and old_db_con_obj.is_connected():
# logger.debug("Returning already participated database connection object for the \
# section : %s, mode : %s ", section, mode)
return old_db_con_obj
# logger.debug("creating the database connection object for the section : %s, mode : %s, \
# storage : %s ", section, mode, storage)
new_db_con_obj = self.storage_mapping['MYSQL'](server_mode, cursor_type=self.cursor_type)
self.__database_conn_objects[mode] = new_db_con_obj
# logger.debug("Returning New database connection object for the section : %s, mode : %s",
# section, mode)
# Getting details of Caller which create a new db connection
# parentframe = sys._getframe(1)
# method_name = parentframe.f_code.co_name
# module = inspect.getmodule(parentframe).__name__
# if 'self' in parentframe.f_locals:
# class_name = parentframe.f_locals['self'].__class__.__name__
# else:
# class_name = None
conn_id = new_db_con_obj.connection_id
# logger.debug("Module:Class:Method <--> connection_id :: %s:%s:%s <--> %s", module,class_name,method_name, conn_id)
return new_db_con_obj
def end(self):
"""
:Note: Ends the transactions - database, file, webservice
:Args:
self.__database_conn_objects
self.__file_obj_list
self.__webservice_conn_obj_list
:Returns:
None
"""
# logger.info("Inside TransactionalManager.end")
# close the database connection objects
for mode, db_conn_obj in self.__database_conn_objects.items():
# logger.sensitive("Closing database connection object for the section : %s", section)
db_conn_obj.close()
self.__database_conn_objects = {}
def save(self):
"""
:Note: It commits all transaction
:Args:
self.__database_conn_objects
self.__file_obj_list
self.__webservice_conn_obj_list
:Returns:
None
"""
# logger.info("Inside TransactionalManager.save")
# commit the database transaction
for mode, db_conn_obj in self.__database_conn_objects.items():
# logger.debug("Committing the database connection object for the section : %s", section)
db_conn_obj.commit()
def revertback(self):
"""
:Note: It rollback all transaction
:Args:
self.__database_conn_objects
self.__file_obj_list
self.__webservice_conn_obj_list
:Returns: None
"""
# logger.info("Inside TransactionalManager.revertback")
# rollback the database transaction
for section, db_conn_obj in self.__database_conn_objects.items():
# logger.debug("Rollbacking the database connection object for the section : %s", section)
db_conn_obj.rollback()
def __del__(self):
self.end()
if __name__ == '__main__':
pass
| true |
e71b2032bf63b70f31b21cd04fc202c9043ff4a7 | Python | Durrant-David/machineLearning | /prove3/main.py | UTF-8 | 4,708 | 2.96875 | 3 | [] | no_license | import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neighbors import KNeighborsRegressor
# function to get the NN
def knn_display(x, y, nn=3, reg=0):
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=42)
if reg:
knn = KNeighborsRegressor(n_neighbors=nn)
else:
knn = KNeighborsClassifier(n_neighbors=nn)
knn.fit(x_train, y_train)
print(knn.score(x_test, y_test))
#
# Start the car data training
#
# Define the headers since the data does not have any
car_header = ["buying", "maint", "doors", "persons", "lug_boot", "safety", "class"]
car_cleanup_data = {"buying": {"vhigh": 4, "high": 3, "med": 2, "low": 1},
"maint": {"vhigh": 4, "high": 3, "med": 2, "low": 1},
"doors": {"5more": 5},
"persons": {"more": 6},
"lug_boot": {"small": 1, "med": 2, "big": 3},
"safety": {"low": 1, "med": 2, "high": 3},
"class": {"vgood": 4, "good": 3, "acc": 2, "unacc": 2}}
car = pd.read_csv("data/car.data", names=car_header)
obj_car = car.select_dtypes(include=['object']).copy()
obj_car.replace(car_cleanup_data, inplace=True)
x = obj_car.drop(["class"], axis=1)
y = obj_car["class"]
knn_display(x, y, 8)
#
# Start the mpg data training
#
mpg_header = ["mpg", "cylinders", "displacement",
"horsepower", "weight", "acceleration",
"model_year", "origin", "car_name"]
mpg_cleanup_data = {"horsepower": {"?": np.NaN}}
mpg = pd.read_csv("data/auto-mpg.data", names=mpg_header, delim_whitespace=True)
obj_mpg = mpg
obj_mpg.replace(mpg_cleanup_data, inplace=True)
obj_mpg['car_name'] = obj_mpg['car_name'].astype('category')
obj_mpg["car_name_cat"] = obj_mpg['car_name'].cat.codes
obj_mpg.dropna(inplace=True)
x = obj_mpg.drop(["mpg", "car_name"], axis=1)
y = obj_mpg["mpg"]
knn_display(x, y, 10, 1)
#
# Start the mpg with mean missing data
#
obj_mpg['horsepower'] = obj_mpg['horsepower'].astype(float)
mean_cylinders = obj_mpg['cylinders'].mean()
mean_displacement = obj_mpg['displacement'].mean()
mean_horsepower = obj_mpg['horsepower'].mean()
mean_weight = obj_mpg['weight'].mean()
mean_acceleration = obj_mpg['acceleration'].mean()
mean_model_year = obj_mpg['model_year'].mean()
mean_origin = obj_mpg['origin'].mean()
obj_mpg['cylinders'] = obj_mpg['cylinders'] - mean_cylinders
obj_mpg['displacement'] = obj_mpg['displacement'] - mean_displacement
obj_mpg['horsepower'] = obj_mpg['horsepower'] - mean_horsepower
obj_mpg['weight'] = obj_mpg['weight'] - mean_weight
obj_mpg['acceleration'] = obj_mpg['acceleration'] - mean_acceleration
obj_mpg['model_year'] = obj_mpg['model_year'] - mean_model_year
obj_mpg['origin'] = obj_mpg['origin'] - mean_origin
x = obj_mpg.drop(["mpg", "car_name"], axis=1)
y = obj_mpg["mpg"]
knn_display(x, y, 10, 1)
#
# Start the math data training
#
math_cleanup_data = {"school": {"GP": 0, "MS": 1},
"sex": {"F": 0, "M": 1},
"address": {"R": 0, "U": 1},
"famsize": {"LE3": 0, "GT3": 1},
"Pstatus": {"A": 0, "T": 1},
"schoolsup": {"no": 0, "yes": 1},
"famsup": {"no": 0, "yes": 1},
"paid": {"no": 0, "yes": 1},
"activities": {"no": 0, "yes": 1},
"nursery": {"no": 0, "yes": 1},
"higher": {"no": 0, "yes": 1},
"internet": {"no": 0, "yes": 1},
"romantic": {"no": 0, "yes": 1}}
math = pd.read_csv("data/student/student-mat.csv", sep=";")
obj_math = math
obj_math.replace(math_cleanup_data, inplace=True)
obj_math["Mjob"] = obj_math["Mjob"].astype('category')
obj_math["Fjob"] = obj_math["Fjob"].astype('category')
obj_math["reason"] = obj_math["reason"].astype('category')
obj_math["guardian"] = obj_math["guardian"].astype('category')
obj_math["Mjob_cat"] = obj_math["Mjob"].cat.codes
obj_math["Fjob_cat"] = obj_math["Fjob"].cat.codes
obj_math["reason_cat"] = obj_math["reason"].cat.codes
obj_math["guardian_cat"] = obj_math["guardian"].cat.codes
x = obj_math.drop(["Mjob", "Fjob", "reason", "guardian", "G3"], axis=1)
y = obj_math["G3"]
knn_display(x, y, 9, 1)
#
# Start the math one hot
#
obj_math2 = math
obj_math2 = pd.get_dummies(obj_math, columns=["Mjob", "Fjob", "reason", "guardian"],
prefix=["Mjob", "Fjob", "reason", "guardian"]).head()
# obj_math.replace(math_cleanup_data, inplace=True)
# print(obj_math)
x = obj_math2.drop(["G3"], axis=1)
y = obj_math2["G3"]
knn_display(x, y, 3, 1)
| true |
f5813546fbd1145aed328210a24d30721e8cbe47 | Python | aliensmart/calculator | /buttons.py | UTF-8 | 1,366 | 3.890625 | 4 | [] | no_license | import tkinter
window = tkinter.Tk()
window.title("Calculator")
#creating two frame, top and bottom
top_frame = tkinter.Frame(window).pack()
bottom_frame = tkinter.Frame(window).pack(side="bottom")
#now, create some widget
btn1 = tkinter.Button(top_frame, text= "button1", bg = "#3498db", fg = "white").pack(side= "right")
btn2 = tkinter.Button(top_frame, text="Button2", bg = "#3498db", fg = "white").pack(side= "left")
btn3 = tkinter.Button(bottom_frame, text = "button3", bg = "#16a085", fg = "white").pack(side = "bottom")
btn4 = tkinter.Button(bottom_frame, text = "button4", bg = "#16a085", fg = "white").pack(side = "bottom")
window.mainloop()
# # creating 2 frames TOP and BOTTOM
# top_frame = tkinter.Frame(window).pack()
# bottom_frame = tkinter.Frame(window).pack(side = "bottom")
# # now, create some widgets in the top_frame and bottom_frame
# btn1 = tkinter.Button(top_frame, text = "Button1",bg = "#16a085" , fg = "red").pack()# 'fg - foreground' is used to color the contents
# btn2 = tkinter.Button(top_frame, text = "Button2", fg = "green").pack()# 'text' is used to write the text on the Button
# btn3 = tkinter.Button(bottom_frame, text = "Button2", fg = "purple").pack(side = "left")# 'side' is used to align the widgets
# btn4 = tkinter.Button(bottom_frame, text = "Button2", fg = "orange").pack(side = "left")
# window.mainloop() | true |
65bc4b2c8c48b654c1d085925f2ae20c106ee2c2 | Python | leeyungyu/practice | /crypto_trading/module/function.py | UTF-8 | 2,809 | 2.90625 | 3 | [] | no_license | from bs4 import BeautifulSoup
from urllib.request import urlopen
import requests
import datetime
import pandas as pd
import numpy as np
def data_crawl(a, b, c, d): # 과거 데이터를 크롤링한다.
# cryptocompare 사이트로 바이낸스 정보 크롤링
# 이게 쉬워서 했는데 바이낸스에서 바로 긁어오는게 더 빠를 듯
url = 'https://min-api.cryptocompare.com/data/histohour?fsym={}&tsym={}&limit={}&aggregate={}&e=Binance'.format(a,b, c, d)
page = requests.get(url)
data = page.json()['Data']
df = pd.DataFrame(data)
df['timestamp'] = [datetime.datetime.fromtimestamp(d) for d in df.time]
#df = df[['timestamp', 'time', 'close', 'volumeto']]
return df
def exchange_rate(): # 네이버 검색결과로 환율정보 크롤링
url = 'https://search.naver.com/search.naver?where=nexearch&sm=top_hty&fbm=1&ie=utf8&query=1%EB%8B%AC%EB%9F%AC'
web = urlopen(url)
source = BeautifulSoup(web, 'html.parser')
box = source.find('div', {'class' : 'rate_tlt'})
a = box.find('strong').get_text()
exrate = float(a.replace(',','')) # 환율의 쉼표를 제거해주고 숫자로 변환
return exrate
def slope(x, y, limit = 2): # limit시간동안의 변동을 최소제곱법 기울기로 보는 함수
slope = []
for i in range(limit-1, len(x)):
x_lim = np.array(list(range(limit)))
y_lim = np.array(y[i-limit+1:i+1])
A = np.vstack([x_lim, np.ones(len(x_lim))]).T # 일차함수는 y = Ap, A = [x,1], p = [m,c]로 구할 수 있음.
m = np.linalg.lstsq(A, y_lim)[0][0]
slope.append(m)
slope_array = np.array([0]*(limit-1) + slope)
return slope_array
def ma(x, y, limit = 2 , gap = 1): # 이동평균(moving average)내는 함수
ma_list = []
for i in range(len(y)-limit+1):
mean = np.mean(y[i:i+limit:gap])
ma_list.append(mean)
ma_array = np.array([0]*(limit-1) + ma_list)
return ma_array
def load_csv(coin_list): #csv 데이터 로딩.
history = {}
for coin in coin_list:
data_sheet = pd.read_csv('data_csv/data_{}_KRW.csv'.format(coin), encoding='utf-8')
history[coin] = data_sheet
return history
def softmax(x):
if x.ndim == 2:
x = x.T
x = x - np.max(x, axis=0)
y = np.exp(x) / np.sum(np.exp(x), axis=0)
return y.T
x = x - np.max(x) # 오버플로 대책
return np.exp(x) / np.sum(np.exp(x))
def cross_entropy_error(y, t):
if y.ndim == 1:
t = t.reshape(1, t.size)
y = y.reshape(1, y.size)
# 훈련 데이터가 원-핫 벡터라면 정답 레이블의 인덱스로 반환
if t.size == y.size:
t = t.argmax(axis=1)
batch_size = y.shape[0]
return -np.sum(np.log(y[np.arange(batch_size), t] + 1e-7)) / batch_size
| true |
a0d910a108ad71f643d7df80f8ccfed832a06abd | Python | ByeBug/crawl | /statistic.py | UTF-8 | 2,088 | 3.203125 | 3 | [] | no_license | """
统计爬虫数据库中的情况
"""
import os
import configparser
import pymysql
if not os.path.isfile('myconfig.cfg'):
print("myconfig.cfg doesn't exist")
exit()
config = configparser.RawConfigParser()
config.read('myconfig.cfg', encoding='utf-8')
try:
crawl_db_host = config['crawl_db']['host']
crawl_db_port = int(config['crawl_db']['port'])
crawl_db_user = config['crawl_db']['user']
crawl_db_passwd = config['crawl_db']['passwd']
crawl_db_db = config['crawl_db']['db']
conn = pymysql.connect(host=crawl_db_host, port=crawl_db_port,
user=crawl_db_user, passwd=crawl_db_passwd,
db=crawl_db_db, charset='utf8')
cursor = conn.cursor()
except Exception as e:
print('Connect to crawl_db failed')
print(e)
exit()
# 总计
sql = """SELECT COUNT(*) FROM crawl"""
cursor.execute(sql)
total = cursor.fetchone()[0]
# 已爬
sql = """SELECT COUNT(*) FROM crawl
WHERE crawled_date > '2000-01-01'"""
cursor.execute(sql)
crawled = cursor.fetchone()[0]
# 未爬
sql = """SELECT COUNT(*) FROM crawl
WHERE crawled_date = '2000-01-01'"""
cursor.execute(sql)
no_crawl = cursor.fetchone()[0]
# 按level统计
sql = """SELECT `level`, count(*) FROM crawl
WHERE crawled_date > '2000-01-01'
GROUP BY `level`"""
cursor.execute(sql)
level_stat = cursor.fetchall()
# 按id统计
sql = """SELECT right(`unique`, 1) as `id`, count(*)
FROM crawl WHERE crawled_date > '2000-01-01'
GROUP BY `id`"""
cursor.execute(sql)
id_result = cursor.fetchall()
id_stat = []
for i in range(8):
id_stat.append((i, id_result[2*i][1] + id_result[2*i+1][1]))
# 输出
print('=== 概览 ===')
print('{}: {}'.format('总计', total))
print('{}: {}'.format('已爬', crawled))
print('{}: {}'.format('未爬', no_crawl))
print('\n=== 按 level 统计 ===')
for i in level_stat:
print('{:>2}: {}'.format(i[0], i[1]))
print('\n=== 按 id 统计 ===')
for i in id_stat:
print('{}: {}'.format(i[0], i[1]))
cursor.close()
conn.close()
| true |
73f4e8a45ef0db327848009b58339f6b852db3c6 | Python | pstrinkle/thesis-source | /fall2012/identify_stopwords.py | UTF-8 | 3,109 | 2.90625 | 3 | [] | no_license | #! /usr/bin/python
__author__ = 'tri1@umbc.edu'
# Patrick Trinkle
# Spring 2012
#
# This attempts to collate the tweet files and remove duplicates
# given an entire folder of xml files, instead of using sort/uniq
# on a per file basis.
#
# Run tweets_by_user.py
import sys
import sqlite3
from json import dumps
from operator import itemgetter
import boringmatrix
sys.path.append("../modellib")
import vectorspace
def usage():
"""."""
print "usage: %s X <sqlite_db> <cleaned_tokens.out> <dict.out> <newstops.out> <singles.out>" % sys.argv[0]
print "\tX the first so many tokens to consider stop words."
print "\tcleaned_tokens.out := sorted, cleaned document frequency dictionary."
print "\tdict.out := alphabetically sorted tokens."
print "\tnewstops.out := top X tokens."
print "\tsingles.out := the singletons for the entire dataset."
def main():
"""."""
# Did they provide the correct args?
if len(sys.argv) != 7:
usage()
sys.exit(-1)
# --------------------------------------------------------------------------
# Parse the parameters.
top_count = int(sys.argv[1])
database_file = sys.argv[2]
output_name = sys.argv[3]
dict_out = sys.argv[4]
stop_out = sys.argv[5]
singles_out = sys.argv[6]
# this won't return the 3 columns we care about.
query = "select id, cleaned_text from tweets;"
conn = sqlite3.connect(database_file)
conn.row_factory = sqlite3.Row
curr = conn.cursor()
# --------------------------------------------------------------------------
# Search the database file for certain things.
docs = {}
stopwords = []
for row in curr.execute(query):
# skip ones that have no value, also instead of having to re-clean.
if len(row['cleaned_text']) > 0:
docs[row['id']] = boringmatrix.localclean(row['cleaned_text'])
print "processing %d docs" % len(docs)
doc_length, doc_freq, doc_termfreq = vectorspace.build_termfreqs(docs, stopwords)
singles = vectorspace.build_singletons(doc_freq)
print "total terms: %d" % sum([doc_length[key] for key in doc_length])
# print doc_freq
# print doc_termfreq
for single in singles:
del doc_freq[single]
sorted_tokens = sorted(
doc_freq.items(),
key=itemgetter(1), # (1) is value
reverse=True)
top_count = min(top_count, len(sorted_tokens))
for idx in xrange(0, top_count):
stopwords.append(sorted_tokens[idx][0])
print "len(stop): %d" % len(stopwords)
with open(output_name, 'w') as fout:
fout.write(dumps(sorted_tokens, indent=4))
with open(dict_out, 'w') as dout:
dout.write(dumps(sorted(doc_freq), indent=4))
with open(stop_out, 'w') as sout:
sout.write(dumps(stopwords, indent=4))
with open(singles_out, 'w') as sout:
sout.write(dumps(singles, indent=4))
# --------------------------------------------------------------------------
# Done.
conn.close()
if __name__ == "__main__":
main()
| true |
58f0a5656f8ce856bc7100b331858c65d9274458 | Python | TextDatasetCleaner/deduplicator | /app.py | UTF-8 | 485 | 2.625 | 3 | [
"MIT"
] | permissive | from flask import Flask, jsonify, render_template, request
from deduplicator import Deduplicator # noqa: I001
app = Flask(__name__)
duplicator = Deduplicator()
def showdedupl(string):
return duplicator.isduplicate(string)
@app.route('/')
def my_form():
return render_template('index.html')
@app.route('/', methods=['POST'])
def my_form_post():
text = request.form['input']
return jsonify({'data': showdedupl(text)})
if __name__ == '__main__':
app.run()
| true |
459d9e7ea595b5465148da35f23552caf08bb65c | Python | pytorch/botorch | /botorch/utils/safe_math.py | UTF-8 | 9,409 | 3.09375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
r"""
Special implementations of mathematical functions that
solve numerical issues of naive implementations.
.. [Maechler2012accurate]
M. Mächler. Accurately Computing log (1 - exp (-| a|))
Assessed by the Rmpfr package. Technical report, 2012.
"""
from __future__ import annotations
import math
from typing import Tuple, Union
import torch
from botorch.exceptions import UnsupportedError
from botorch.utils.constants import get_constants_like
from torch import finfo, Tensor
from torch.nn.functional import softplus
_log2 = math.log(2)
_inv_sqrt_3 = math.sqrt(1 / 3)
# Unary ops
def exp(x: Tensor, **kwargs) -> Tensor:
info = finfo(x.dtype)
maxexp = get_constants_like(math.log(info.max) - 1e-4, x)
return torch.exp(x.clip(max=maxexp), **kwargs)
def log(x: Tensor, **kwargs) -> Tensor:
info = finfo(x.dtype)
return torch.log(x.clip(min=info.tiny), **kwargs)
# Binary ops
def add(a: Tensor, b: Tensor, **kwargs) -> Tensor:
_0 = get_constants_like(0, a)
case = a.isinf() & b.isinf() & (a != b)
return torch.where(case, _0, a + b)
def sub(a: Tensor, b: Tensor) -> Tensor:
_0 = get_constants_like(0, a)
case = (a.isinf() & b.isinf()) & (a == b)
return torch.where(case, _0, a - b)
def div(a: Tensor, b: Tensor) -> Tensor:
_0, _1 = get_constants_like(values=(0, 1), ref=a)
case = ((a == _0) & (b == _0)) | (a.isinf() & a.isinf())
return torch.where(case, torch.where(a != b, -_1, _1), a / torch.where(case, _1, b))
def mul(a: Tensor, b: Tensor) -> Tensor:
_0 = get_constants_like(values=0, ref=a)
case = (a.isinf() & (b == _0)) | (b.isinf() & (a == _0))
return torch.where(case, _0, a * torch.where(case, _0, b))
def log1mexp(x: Tensor) -> Tensor:
"""Numerically accurate evaluation of log(1 - exp(x)) for x < 0.
See [Maechler2012accurate]_ for details.
"""
log2 = get_constants_like(values=_log2, ref=x)
is_small = -log2 < x # x < 0
return torch.where(
is_small,
(-x.expm1()).log(),
(-x.exp()).log1p(),
)
def log1pexp(x: Tensor) -> Tensor:
"""Numerically accurate evaluation of log(1 + exp(x)).
See [Maechler2012accurate]_ for details.
"""
mask = x <= 18
return torch.where(
mask,
(lambda z: z.exp().log1p())(x.masked_fill(~mask, 0)),
(lambda z: z + (-z).exp())(x.masked_fill(mask, 0)),
)
def logexpit(X: Tensor) -> Tensor:
"""Computes the logarithm of the expit (a.k.a. sigmoid) function."""
return -log1pexp(-X)
def logdiffexp(log_a: Tensor, log_b: Tensor) -> Tensor:
"""Computes log(b - a) accurately given log(a) and log(b).
Assumes, log_b > log_a, i.e. b > a > 0.
Args:
log_a (Tensor): The logarithm of a, assumed to be less than log_b.
log_b (Tensor): The logarithm of b, assumed to be larger than log_a.
Returns:
A Tensor of values corresponding to log(b - a).
"""
return log_b + log1mexp(log_a - log_b)
def logmeanexp(
X: Tensor, dim: Union[int, Tuple[int, ...]], keepdim: bool = False
) -> Tensor:
"""Computes `log(mean(exp(X), dim=dim, keepdim=keepdim))`.
Args:
X: Values of which to compute the logmeanexp.
dim: The dimension(s) over which to compute the mean.
keepdim: If True, keeps the reduced dimensions.
Returns:
A Tensor of values corresponding to `log(mean(exp(X), dim=dim))`.
"""
n = X.shape[dim] if isinstance(dim, int) else math.prod(X.shape[i] for i in dim)
return torch.logsumexp(X, dim=dim, keepdim=keepdim) - math.log(n)
def log_softplus(x: Tensor, tau: Union[float, Tensor] = 1.0) -> Tensor:
"""Computes the logarithm of the softplus function with high numerical accuracy.
Args:
x: Input tensor, should have single or double precision floats.
tau: Decreasing tau increases the tightness of the
approximation to ReLU. Non-negative and defaults to 1.0.
Returns:
Tensor corresponding to `log(softplus(x))`.
"""
check_dtype_float32_or_float64(x)
tau = torch.as_tensor(tau, dtype=x.dtype, device=x.device)
# cutoff chosen to achieve accuracy to machine epsilon
upper = 16 if x.dtype == torch.float32 else 32
lower = -15 if x.dtype == torch.float32 else -35
mask = x / tau > lower
return torch.where(
mask,
softplus(x.masked_fill(~mask, lower), beta=(1 / tau), threshold=upper).log(),
x / tau + tau.log(),
)
def smooth_amax(X: Tensor, tau: Union[float, Tensor] = 1e-3, dim: int = -1) -> Tensor:
"""Computes a smooth approximation to `max(X, dim=dim)`, i.e the maximum value of
`X` over dimension `dim`, using the logarithm of the `l_(1/tau)` norm of `exp(X)`.
Note that when `X = log(U)` is the *logarithm* of an acquisition utility `U`,
`logsumexp(log(U) / tau) * tau = log(sum(U^(1/tau))^tau) = log(norm(U, ord=(1/tau))`
Args:
X: A Tensor from which to compute the smoothed amax.
tau: Temperature parameter controlling the smooth approximation
to max operator, becomes tighter as tau goes to 0. Needs to be positive.
Returns:
A Tensor of smooth approximations to `max(X, dim=dim)`.
"""
# consider normalizing by log_n = math.log(X.shape[dim]) to reduce error
return torch.logsumexp(X / tau, dim=dim) * tau # ~ X.amax(dim=dim)
def check_dtype_float32_or_float64(X: Tensor) -> None:
if X.dtype != torch.float32 and X.dtype != torch.float64:
raise UnsupportedError(
f"Only dtypes float32 and float64 are supported, but received {X.dtype}."
)
def log_fatplus(x: Tensor, tau: Union[float, Tensor] = 1.0) -> Tensor:
"""Computes the logarithm of the fat-tailed softplus.
NOTE: Separated out in case the complexity of the `log` implementation increases
in the future.
"""
return fatplus(x, tau=tau).log()
def fatplus(x: Tensor, tau: Union[float, Tensor] = 1.0) -> Tensor:
"""Computes a fat-tailed approximation to `ReLU(x) = max(x, 0)` by linearly
combining a regular softplus function and the density function of a Cauchy
distribution. The coefficient `alpha` of the Cauchy density is chosen to guarantee
monotonicity and convexity.
Args:
x: A Tensor on whose values to compute the smoothed function.
Returns:
A Tensor of values of the fat-tailed softplus.
"""
def _fatplus(x: Tensor) -> Tensor:
alpha = 1e-1 # guarantees monotonicity and convexity (TODO: ref + Lemma 4)
return softplus(x) + alpha * cauchy(x)
return tau * _fatplus(x / tau)
def fatmax(X: Tensor, dim: int, tau: Union[float, Tensor] = 1.0) -> Tensor:
"""Computes a smooth approximation to amax(X, dim=dim) with a fat tail.
Args:
X: A Tensor from which to compute the smoothed amax.
tau: Temperature parameter controlling the smooth approximation
to max operator, becomes tighter as tau goes to 0. Needs to be positive.
standardize: Toggles the temperature standardization of the smoothed function.
Returns:
A Tensor of smooth approximations to `max(X, dim=dim)` with a fat tail.
"""
if X.shape[dim] == 1:
return X.squeeze(dim)
M = X.amax(dim=dim, keepdim=True)
Y = (X - M) / tau # NOTE: this would cause NaNs when X has Infs.
M = M.squeeze(dim)
return M + tau * cauchy(Y).sum(dim=dim).log() # could change to mean
def log_fatmoid(X: Tensor, tau: Union[float, Tensor] = 1.0) -> Tensor:
"""Computes the logarithm of the fatmoid. Separated out in case the implementation
of the logarithm becomes more complex in the future to ensure numerical stability.
"""
return fatmoid(X, tau=tau).log()
def fatmoid(X: Tensor, tau: Union[float, Tensor] = 1.0) -> Tensor:
"""Computes a twice continuously differentiable approximation to the Heaviside
step function with a fat tail, i.e. `O(1 / x^2)` as `x` goes to -inf.
Args:
X: A Tensor from which to compute the smoothed step function.
tau: Temperature parameter controlling the smoothness of the approximation.
Returns:
A tensor of fat-tailed approximations to the Heaviside step function.
"""
X = X / tau
m = _inv_sqrt_3 # this defines the inflection point
return torch.where(
X < 0,
2 / 3 * cauchy(X - m),
1 - 2 / 3 * cauchy(X + m),
)
def cauchy(x: Tensor) -> Tensor:
"""Computes a Lorentzian, i.e. an un-normalized Cauchy density function."""
return 1 / (1 + x.square())
def sigmoid(X: Tensor, log: bool = False, fat: bool = False) -> Tensor:
"""A sigmoid function with an optional fat tail and evaluation in log space for
better numerical behavior. Notably, the fat-tailed sigmoid can be used to remedy
numerical underflow problems in the value and gradient of the canonical sigmoid.
Args:
X: The Tensor on which to evaluate the sigmoid.
log: Toggles the evaluation of the log sigmoid.
fat: Toggles the evaluation of the fat-tailed sigmoid.
Returns:
A Tensor of (log-)sigmoid values.
"""
Y = log_fatmoid(X) if fat else logexpit(X)
return Y if log else Y.exp()
| true |
06c2620a64bc07ec2d11bf9fbfc182bbf4ac049d | Python | sologuboved/rgbm | /goodreads_librarian.py | UTF-8 | 2,599 | 3.046875 | 3 | [] | no_license | from datetime import datetime
from unidecode import unidecode
from basic_operations import *
from global_vars import *
class Librarian(object):
def __init__(self, books_json, shelf, starting_date):
self.books_json = books_json
self.shelf = shelf
self.starting_date = starting_date
self.to_read = list()
self.collect_books()
def __str__(self):
string = ''
ind = 1
for book in self.to_read:
string += "%d\nauthor: %s\ntitle: %s\n<%s>\n<%s>\n\n" % (ind,
book[AUTHOR], book[TITLE],
book[ABBR_AUTHOR], book[ABBR_TITLE])
ind += 1
return string
def collect_books(self):
all_books = load_json(self.books_json)
for book in all_books:
if self.shelf in book[SHELVES]:
try:
starting_date = datetime.strptime(self.starting_date, "%d.%m.%Y")
except TypeError:
starting_date = None
if starting_date:
date = datetime.strptime(book[DATE], "%b %d, %Y") # "Jan 01, 1995"
if date < starting_date:
continue
author = book[AUTHOR]
title = book[TITLE]
abbr_author = ''.join(char if char != "'" else " " for char in unidecode(author.split(',')[0]))
abbr_title = ''.join([unidecode(char) for char in title.split(':')[0] if char.isalnum() or char == ' '])
self.to_read.append({AUTHOR: author,
TITLE: title,
ABBR_AUTHOR: abbr_author,
ABBR_TITLE: abbr_title})
def find_namesakes(self):
names = dict()
for book in self.to_read:
name = book[ABBR_AUTHOR]
books_by = names.get(name, list())
books_by.append((book[AUTHOR], book[TITLE]))
names[name] = books_by
for name in names:
books_by = names[name]
if len(books_by) > 1:
print(name)
print()
for book in books_by:
author, title = book
print(author)
print(title)
print()
print('----------------')
print()
if __name__ == '__main__':
grb = Librarian(GR_JSON, TO_READ_SHELF, None)
print(grb)
| true |
48e5e0f788897c2bf5875d36e3cb4f20a1aee49c | Python | zengerlet/1d_sp_solver | /src/sp_functions.py | UTF-8 | 11,386 | 2.6875 | 3 | [] | no_license | import numpy as np
import scipy.integrate as integ
import scipy.constants as const
import matplotlib.pyplot as plt
def wf_weights(WF_array, EV, nocs, ef, temp):
""" Helper function to calculate the exponential part of the delectron density """
WF_weights = np.zeros(nocs)
# sum up small values (exponential factor for higher energies) first to prevent from numerical errors
for i in xrange(nocs-1,-1,-1):
exparg = -(EV[i] - ef)*const.e/const.k/temp
# approximate for large arguments
if exparg > 100.:
WF_weights[i] = exparg
else: WF_weights[i] = np.log(1 + np.exp(exparg))
return WF_weights
def sigma_z(x_array, eDens_array):
""" Calculation of sigma of electron density """
x_array = x_array.T[0,:]
z1 = (integ.simps(x_array*eDens_array,x_array)/integ.simps(eDens_array,x_array))**2
z2 = integ.simps(x_array**2*eDens_array,x_array)/integ.simps(eDens_array,x_array)
return np.sqrt(z2-z1)
def normalize(f, ss):
""" Normalize wave function """
N = integ.simps(f*f, dx=ss)
c = 1.0/np.sqrt(N)
f_norm = c*f
return f_norm
def netCharge(DOP_array, ss):
""" Integrate charge density array in z-direction """
DOP_net_charge = integ.simps(DOP_array, dx=ss)
return DOP_net_charge
def eDensity(WF_array, m_eff_array_q, EV, ef, temp, nelq, nocs, oW=False):
""" Calculate eDensity from wave functions considering fermi-dirac distribution and density of states """
density = np.zeros(nelq + 1)
Weights = wf_weights(WF_array, EV, nocs, ef, temp)
for i in xrange(nocs-1,-1,-1):
density = density + WF_array[i]**2*Weights[i]
if oW:
print 'Weights of wave functions = ', Weights
# multiply by constants and density of states
DOS = m_eff_array_q*const.m_e/const.pi/const.hbar**2
density = density*temp*const.k*DOS
return density
def findFermi(net_Doping, WF_array, EV, m_eff_array_q, temp, ss, nelq, nocs):
""" Find fermi level using charge neutrality condition """
intervalok = True
#start with ef_min = -1.0, ef_max = 1.0
ef_min = -1.0
ef_max = 1.0
# check if given interval is ok
D_ef_min = eDensity(WF_array, m_eff_array_q, EV, ef_min, temp, nelq, nocs)
D_ef_max = eDensity(WF_array, m_eff_array_q, EV, ef_max, temp, nelq, nocs)
net_Density_min = -netCharge(D_ef_min, ss) + net_Doping
net_Density_max = -netCharge(D_ef_max, ss) + net_Doping
# extend initial interval if necessary
ei = 0
while (net_Density_max < 0 and net_Density_min < 0) or (net_Density_max > 0 and net_Density_min > 0):
if net_Density_max < 0 and net_Density_min < 0:
ef_min = ef_min - (ef_max - ef_min)
#print 'Interval adjusted. ef_min new = ', ef_min
if net_Density_max > 0 and net_Density_min > 0:
ef_max = ef_max + (ef_max - ef_min)
#print 'Interval adjusted. ef_max new = ', ef_max
# calculate desities with new ef values
D_ef_min = eDensity(WF_array, m_eff_array_q, EV, ef_min, temp, nelq, nocs)
D_ef_max = eDensity(WF_array, m_eff_array_q, EV, ef_max, temp, nelq, nocs)
net_Density_min = -netCharge(D_ef_min, ss) + net_Doping
net_Density_max = -netCharge(D_ef_max, ss) + net_Doping
ei += 1
if ei > 100:
intervalok = False
break
if intervalok == False:
print 'could not find right interval!'
return 0
ii = 0
while abs(net_Density_min - net_Density_max) > net_Doping*1e-12:
# calculate density for fermi level between ef_min and ef_max
ef_middle = (ef_max + ef_min)/2
D_ef_middle = eDensity(WF_array, m_eff_array_q, EV, ef_middle, temp, nelq, nocs)
net_Density_middle = -netCharge(D_ef_middle, ss) + net_Doping
#print net_Density_middle
if net_Density_middle < 0:
ef_max = ef_middle
D_ef_max = eDensity(WF_array, m_eff_array_q, EV, ef_max, temp, nelq, nocs)
net_Density_max = -netCharge(D_ef_max, ss) + net_Doping
elif net_Density_middle > 0:
ef_min = ef_middle
D_ef_min = eDensity(WF_array, m_eff_array_q, EV, ef_min, temp, nelq, nocs)
net_Density_min = -netCharge(D_ef_min, ss) + net_Doping
#print 'delta E = ', ef_max - ef_min
#print 'ef_max = ', ef_max
#print abs(net_Density_min - net_Density_max)
if net_Density_min < 0 or net_Density_max > 0:
print 'error'
break
ii += 1
# check if converged
D_ef_final = eDensity(WF_array, m_eff_array_q, EV, ef_max, temp, nelq, nocs)
net_Density_final = -netCharge(D_ef_final, ss) + net_Doping
#print net_Density_final
#print ii
#print ef_max
#print ef_min
print 'new fermi level =', ef_max
return ef_max
def V_ex(eDens_array, epsilon_array_q, m_eff_array_q):
""" Exchange correlation term """
a_star = 4.0*np.pi*const.epsilon_0*epsilon_array_q*(const.hbar**2)/(const.m_e*m_eff_array_q*const.e**2)
r_s_inv = np.where(eDens_array>0., ((4.0/3*np.pi*a_star**3*eDens_array)**(1./3.)), 0.)
Ry_star = (const.e**2)/(8.0*np.pi*const.epsilon_0*epsilon_array_q*a_star)
V_ex = (-2.0*Ry_star)/(np.pi**(2.0/3)*(4.0/9)**(1.0/3))*r_s_inv + \
(-2.0*Ry_star)/(np.pi**(2.0/3)*(4.0/9)**(1.0/3))*(0.7734/21)*np.log(1.0 + 21.0*r_s_inv)
return V_ex
def plot_output(x, x_q, pot_tot_array_p, doping_n_array, eDens_array, nel, ef, time_ex, noit, target_error_p,
error_p, target_error_d, error_d, nocs, E, PSI, ss, gs, nomaxit, exchange_correlation_term, DEBUG, DEBUG_level,
fraction_in_dx_centers, fraction_of_free_charges_on_surface, surface_charge_array, temp, linear_solver, surface_charge_on):
""" Output all relevant information and write into file """
if DEBUG and (DEBUG_level==1 or DEBUG_level==2):
plt.figure()
plt.plot(x, pot_tot_array_p)
for k in xrange(nocs):
print "E[" + str(k) + "]=" + str(E[k])
plt.plot(x_q, PSI[k]/np.max(abs(PSI[k])) + E[k])
plt.title('Conduction band, wave functions, fermi level')
plt.show()
# calculate sigma_z for file name
s_z = sigma_z(x_q, eDens_array)
if exchange_correlation_term:
myfile = open('output_ex_' + str(nel) + '_' + str(fraction_in_dx_centers) + '_' + str(round(fraction_of_free_charges_on_surface,3)) + '_' + str(round(s_z,3)) + '.txt', 'w')
else: myfile = open('output_' + str(nel) + '_' + str(fraction_in_dx_centers) + '_' + str(round(fraction_of_free_charges_on_surface,3)) + '_' + str(round(s_z,3)) + '.txt', 'w')
doping_sheet_density_cm = netCharge(doping_n_array, ss)*1e-4
myfile.write('doping sheet density = ' + str('%.6e' % doping_sheet_density_cm) + ' cm^-2\n') # convert from m^-2 to cm^-2 and write to output file
electron_sheet_density_cm = -netCharge(eDens_array, ss)*1e-4
myfile.write('electron sheet density = ' + str('%.6e' % electron_sheet_density_cm) + ' cm^-2\n')
surface_charge_sheet_density_cm = netCharge(surface_charge_array, ss)*1e-4
myfile.write('surface charge sheet density = ' + str('%.6e' % surface_charge_sheet_density_cm) + ' cm^-2\n')
total_sheet_density_cm = (netCharge(doping_n_array, ss)-netCharge(eDens_array, ss)+netCharge(surface_charge_array, ss))*1e-4
myfile.write('total sheet density = ' + str('%.6e' % total_sheet_density_cm) + ' cm^-2\n')
myfile.write('fraction_in_dx_centers = ' + str(fraction_in_dx_centers) + '\n')
myfile.write('fraction_of_free_charges_on_surface = ' + str(fraction_of_free_charges_on_surface) + '\n')
myfile.write('eigenvalues = ' + str(E) + ' eV\n')
myfile.write('final weights of wavefunctions = ' + str(wf_weights(PSI, E, nocs, ef, temp)) + '\n')
myfile.write('converged at step ' + str(noit) + '\n')
myfile.write('max number of iterations = ' + str(nomaxit) + '\n')
myfile.write('target error poisson = ' + str(target_error_p) + ' V\n')
myfile.write('error poisson = ' + str(error_p) + ' V\n')
myfile.write('target error electron density = ' + str(target_error_d) + ' m^-3\n')
myfile.write('error electron density = ' + str(error_d) + ' m^-3\n')
myfile.write('number of elements = ' + str(nel) + '\n')
myfile.write('number of considered states of schroedinger equation = ' + str(nocs) + '\n')
myfile.write('exchange correlation = ' + str(exchange_correlation_term) + '\n')
myfile.write('calculation time = ' + str(time_ex) + ' sec\n')
myfile.write('fermi level = ' + str(ef) + ' eV\n')
myfile.write('grid spacing = ' + str(gs) + ' nm\n')
myfile.write('sigma_z = ' + str(s_z) + ' nm\n')
myfile.write('temperature = ' + str(temp) + ' K\n')
myfile.write('linear solver = ' + str(linear_solver) + '\n')
myfile.write('surface charge = ' + str(surface_charge_on))
myfile.close()
# save file with electron density array in 1e24 m^-3 or equivalent 1e18 cm^-3
if exchange_correlation_term:
np.savetxt('eDens_array_ex_' + str(nel) + '_' + str(fraction_in_dx_centers) + '_' + str(round(fraction_of_free_charges_on_surface,3)) + '_' + str(round(s_z,3)) + '.out', eDens_array*1e-24)
else: np.savetxt('eDens_array_' + str(nel) + '_' + str(fraction_in_dx_centers) + '_' + str(round(fraction_of_free_charges_on_surface,3)) + '_' + str(round(s_z,3)) + '.out', eDens_array*1e-24)
if exchange_correlation_term:
np.savetxt('pot_tot_array_p_ex_' + str(nel) + '_' + str(fraction_in_dx_centers) + '_' + str(round(fraction_of_free_charges_on_surface,3)) + '_' + str(round(s_z,3)) + '.out', pot_tot_array_p)
else: np.savetxt('pot_tot_array_p_' + str(nel) + '_' + str(fraction_in_dx_centers) + '_' + str(round(fraction_of_free_charges_on_surface,3)) + '_' + str(round(s_z,3)) + '.out', pot_tot_array_p)
if exchange_correlation_term:
np.savetxt('Psi_ex_' + str(nel) + '_' + str(fraction_in_dx_centers) + '_' + str(round(fraction_of_free_charges_on_surface,3)) + '_' + str(round(s_z,3)) + '.out', np.hstack([x_q,PSI.T]))
else: np.savetxt('Psi_' + str(nel) + '_' + str(fraction_in_dx_centers) + '_' + str(round(fraction_of_free_charges_on_surface,3)) + '_' + str(round(s_z,3)) + '.out', np.hstack([x_q,PSI.T]))
print 'doping net charge = ', netCharge(doping_n_array, ss)
print 'eDensity net charge = ', netCharge(eDens_array, ss)
print 'total net charge = ', netCharge(doping_n_array, ss)-netCharge(eDens_array, ss)+netCharge(surface_charge_array, ss)
print 'fraction_in_dx_centers = ', fraction_in_dx_centers
print 'fraction_of_free_charges_on_surface = ', fraction_of_free_charges_on_surface
print 'eigenvalues = ', E
print 'final weights of wavefunctions = ', wf_weights(PSI, E, nocs, ef, temp)
print 'converged at step', noit
print 'target error_p =', target_error_p
print 'error_p =', error_p
print 'target error_d =', target_error_d
print 'error_d =', error_d
print 'number of elements =', nel
print 'number of considered states of schroedinger equation =', nocs
print 'exchange correlation =', exchange_correlation_term
print 'sigma_z =', s_z
print 'temperature = ', temp
print 'linear solver = ', linear_solver
print 'surface charge = ', surface_charge_on
print 'calculation time =', time_ex
| true |
6ffb32f14f4a828afaaaa50aa5b04458ac024484 | Python | muhammad-masood-ur-rehman/Skillrack | /Python Programs/find-am-or-pm.py | UTF-8 | 981 | 4.125 | 4 | [
"CC0-1.0"
] | permissive | Find AM or PM
A string S which represents the time in 24 hour format HH:MM is passed as input. The program must find if it is AM or PM and print it as output. If an invalid time is passed as input, the program must print INVALIDINPUT
Boundary Conditions: 12:00 is noon and PM must be printed as output. 00:00 or 24:00 is midnight and AM must be printed as output.
Input Format: First line will contain the string value S which represents the time in HH:MM format.
Output Format: The first line will contain the output which is either AM or PM IMPORTANT: The output is case sensitive. Hence print AM or PM in upper case.
Sample Input/Output:
Example 1: Input:
13:44
Output:
PM
Example 2: Input:
12:00
Output:
PM
Example 3: Input:
32:70
Output:
INVALIDINPUT
Example 4: Input:
05:32
Output:
AM
Code:
from datetime import datetime
n=input()
h,m=n.split(":")
if int(h)>=0 and int(h)<23:
d=datetime.strptime(n,"%H:%M")
print(d.strftime("%p"))
else:
print("INVALIDINPUT")
| true |
166b0e57ccaa16e9d4ed21ab64dc0f185388aeb6 | Python | guptaraghav01/100DaysOfCode | /day_10/simple calculator/calculator.py | UTF-8 | 2,834 | 4.5625 | 5 | [] | no_license | from art import logo
# Add
def add(n1, n2):
return n1 + n2
# Subtract
def subtract(n1, n2):
return n1 - n2
# Multiply
def multiply(n1, n2):
return n1 * n2
# Divide
def divide(n1, n2):
return n1 / n2
operations = {
"+": add,
"-": subtract,
"*": multiply,
"/": divide,
}
def calculator():
print(logo)
num1 = float(input("What's the first number?\n"))
for symbol in operations:
print(symbol)
should_continue = True
while should_continue:
operation_symbol = input("Pick an operation :\n")
num2 = float(input("What's the next number?\n"))
calculation_function = operations[operation_symbol]
answer = calculation_function(num1, num2)
print(f"{num1} {operation_symbol} {num2} = {answer}")
choice = input(
f"""Type \n1. To continue calulating with {answer}. \n2. To start a new calculation.\n3. To end the program.\n""")
if choice == "1":
num1 = answer
elif choice == "2":
should_continue = False
calculator()
else:
should_continue = False
calculator()
# Output
# _____________________
# | _________________ |
# | | Pythonista 0. | | .----------------. .----------------. .----------------. .----------------.
# | |_________________| | | .--------------. || .--------------. || .--------------. || .--------------. |
# | ___ ___ ___ ___ | | | ______ | || | __ | || | _____ | || | ______ | |
# | | 7 | 8 | 9 | | + | | | | .' ___ | | || | / \ | || | |_ _| | || | .' ___ | | |
# | |___|___|___| |___| | | | / .' \_| | || | / /\ \ | || | | | | || | / .' \_| | |
# | | 4 | 5 | 6 | | - | | | | | | | || | / ____ \ | || | | | _ | || | | | | |
# | |___|___|___| |___| | | | \ `.___.'\ | || | _/ / \ \_ | || | _| |__/ | | || | \ `.___.'\ | |
# | | 1 | 2 | 3 | | x | | | | `._____.' | || ||____| |____|| || | |________| | || | `._____.' | |
# | |___|___|___| |___| | | | | || | | || | | || | | |
# | | . | 0 | = | | / | | | '--------------' || '--------------' || '--------------' || '--------------' |
# | |___|___|___| |___| | '----------------' '----------------' '----------------' '----------------'
# |_____________________|
# What's the first number?
# 3
# +
# -
# *
# /
# Pick an operation :
# +
# What's the next number?
# 5
# 3.0 + 5.0 = 8.0
# Type
# 1. To continue calulating with 8.0.
# 2. To start a new calculation.
# 3. To end the program.
# 1
# Pick an operation :
# *
# What's the next number?
# 2
# 8.0 * 2.0 = 16.0
# Type
# 1. To continue calulating with 16.0.
# 2. To start a new calculation.
# 3. To end the program.
# 3
| true |
c561289146aa0c68c966ce46cf4d39f5180ff134 | Python | TanushreeVedula14/18031J0068_Python | /Python/Module 2/Assignment 2_3.py | UTF-8 | 239 | 4.46875 | 4 | [] | no_license | # Write a function to display give number is odd or even.
def odd_even(num):
if num % 2 == 0:
print("{} is even.".format(num))
else:
print("{} is odd.".format(num))
num = int(input("Enter num = "))
odd_even(num)
| true |
fbe38f93059eb2b5df63f7871bf1bd755eefa723 | Python | faisalshahbaz/python-email | /emailwithheader.py | UTF-8 | 428 | 3.234375 | 3 | [] | no_license | # Imports SMTP Library
import smtplib
# Sender and Receiver
sender = 'sender@example.com'
receivers = ['receiver@example.com']
# Message
message = """
From: Sender <sender@example.com>
To: Receiver <receiver@example.com>
Subject: Welcome
Welcome Guest!!'
"""
try:
smtpObj = smtplib.SMTP('localhost', 1025)
smtpObj.sendmail(sender, receivers, message)
print("Email sent")
except smtplib.SMTPException:
print("Error sending email")
finally:
smtpObj.quit()
| true |
e17504e6eb700c2daf48d30bca3a2fe021e12ce0 | Python | Simonforyou/eai_tutorials | /src/eai_tutorials/scripts/find_contours.py | UTF-8 | 1,225 | 2.65625 | 3 | [] | no_license | #!/usr/bin/env python
import cv2
import numpy as np
img = cv2.pyrDown(cv2.imread("../images/cross.jpg",cv2.IMREAD_UNCHANGED))
cv2.imshow("original",img)
ret, thresh = cv2.threshold(cv2.cvtColor(img.copy(),cv2.COLOR_BGR2GRAY),127,255,cv2.THRESH_BINARY)
image, contours, hier = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
x,y,w,h = cv2.boundingRect(c)
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
rect = cv2.minAreaRect(c)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img,[box],0,(0,255,0),2)
(x,y),radius = cv2.minEnclosingCircle(c)
center = (int(x),int(y))
radius = int(radius)
img = cv2.circle(img, center,radius, (0,0,255), 2)
epsilon = 0.01 * cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, epsilon, True)
hull = cv2.convexHull(c)
length_hull=len(hull)-2
if length_hull>2:
for i in range(0,len(hull)-2):
cv2.line(img,(hull[i][0][0],hull[i][0][1]),(hull[i+1][0][0],hull[i+1][0][1]),(255,255,0),2)
cv2.line(img,(hull[0][0][0],hull[0][0][1]),(hull[i+1][0][0],hull[i+1][0][1]),(255,255,0),1)
cv2.imshow('Original',image)
cv2.imshow('Contours',img)
cv2.waitKey()
cv2.destroyAllWindows()
| true |
5b28577fb5aa92144d9fc91ffa5444ef17db3c6e | Python | igornfaustino/facialRecognition | /main.py | UTF-8 | 1,029 | 2.71875 | 3 | [] | no_license | # Author: Igor N Faustino
# Mail: igornfaustino@gmail.com
# TODO Next: Support to many faces
import cv2
import sys
import data_utils
import face_utils
import numpy as np
# Get user values
try:
train_path = sys.argv[1]
except IndexError as ex:
print("please enter a training folder path")
exit(-1)
except:
exit(-1)
subjects = ["", "Igor"]
print("preparing data....")
faces, labels = data_utils.prepare_training_data(train_path)
print("done...")
print("Total faces: ", len(faces))
print("Total labels: ", len(labels))
print("training....")
face_recognizer = cv2.face.LBPHFaceRecognizer_create()
face_recognizer.train(faces, np.array(labels))
print("Done...")
video_capture = cv2.VideoCapture(0)
while True:
ret, frame = video_capture.read()
image = face_utils.predict(frame, face_recognizer, subjects)
# Display the resulting frame
cv2.imshow('Video', image)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows() | true |
781849e6712a5ea18e4da9ccdc8c74a1936c92d6 | Python | dorianmeade/life3educate-webhook-python | /server.py | UTF-8 | 347 | 2.703125 | 3 | [] | no_license | from flask import Flask
from flask import request, jsonify
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
@app.route('/api/v1', methods=['GET'])
def getType():
if 'type' in request.args:
mytype = request.args['type']
else:
mytype = "none"
return jsonify(type=mytype)
app.run() | true |
271cfcc399971a755c8ca33e98c3acc1a5679918 | Python | aissata0315/TP-PYTHON | /Exercice9.py | UTF-8 | 474 | 3.234375 | 3 | [] | no_license | #coding : utf-8
import math as m
heuredep = input("heure de depart")
heuredep = int(heuredep)
minutedep = input("minute de depart")
minutedep = int(minutedep)
hdar = input("heure d'arrive")
hdar = int(hdar)
minutedar = input("minute d'arrivee")
minutedar = int(minutedar)
Hdep_mn = heuredep*60 + minutedep
Hdar_mn = hdar*60 + minutedar
duree_en_mn = (Hdar_mn - Hdep_mn)
heure_dure = m.floor(duree_en_mn/60)
minute_duree = duree_en_mn%60
print(heure_dure,minute_duree) | true |
7232baa094959306fd46487733e6a195584c8ae8 | Python | JoshTheRoadie/DiceTactics | /SpritesheetLoader.py | UTF-8 | 1,053 | 2.84375 | 3 | [] | no_license | ## PYGAME BASIC SETUP TEMPLATE
import pygame, sys, random, DT_EventHandler
from pygame.locals import *
FPS = 60
WINDOWWIDTH = 640
WINDOWHEIGHT = 480
econ_dice = pygame.image.load('economydice.png')
def main():
global FPSCLOCK
pygame.init()
FPSCLOCK = pygame.time.Clock()
SCREEN = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
while True:
animateSpritesheet(SCREEN, econ_dice)
DT_EventHandler.checkForQuit()
pygame.display.update()
FPSCLOCK.tick(FPS)
def animateSpritesheet(surface, spritesheet):
index_list = [0,1,2,3,4,5]
target_pos = surface.get_rect().center
wait_times = range(0, 400, 20)
for delay in wait_times:
sprite_index = random.choice(index_list)
current_frame = sprite_index * 32
surface.blit(spritesheet, target_pos, (current_frame, 0, 32, 32))
DT_EventHandler.checkForQuit()
pygame.display.update()
pygame.time.wait(delay)
FPSCLOCK.tick(FPS)
if __name__ == '__main__':
main()
| true |
1e7fa2ccc6c2ecf6f5e45b1a3deed1eeee37be8d | Python | JYadav1/NetflixDataAnalysis | /Jacob/cleaning/merge.py | UTF-8 | 287 | 2.828125 | 3 | [] | no_license | import pandas as pd
df1 = pd.read_csv (r'netflix_titles.csv')
df2 = pd.read_csv (r'netflix_IMDB_scores.csv')
df3 = pd.read_csv (r'netflix_sentiment_scores.csv')
df4 = df1.combine_first(df2)
df5 = df4.combine_first(df3)
df5.to_csv('new_netflix.csv', index=False)
print(df5) | true |
12473f07e8b12956c258ec28e4a7586c6333b821 | Python | maxandix/lotto-game | /lotto_game/LottoGame.py | UTF-8 | 1,878 | 3.5 | 4 | [] | no_license | import random
import os
from .Ticket import Ticket
from .tools import yes_or_no
class LottoGame:
def __init__(self):
self.player = Ticket('Ваш билет')
self.computer = Ticket('Билет компьютера')
self.user_made_a_mistake = False
self.player_won = False
self.computer_won = False
self.barrels = list(range(1, 91))
random.shuffle(self.barrels)
self._game_over = False
def run(self):
if self._game_over:
raise Exception('Game over')
for barrel in self.barrels:
os.system('cls||clear')
print(f'Текущий боченок: {barrel}')
print(self.player)
print(self.computer)
if self.user_made_a_mistake or self.player_won or self.computer_won:
self._game_over = True
return True
user_answered_yes = yes_or_no('Вычеркнуть число?')
self.user_made_a_mistake = user_answered_yes != self.player.has(barrel)
if self.player.has(barrel):
self.player.cross_out(barrel)
if self.computer.has(barrel):
self.computer.cross_out(barrel)
self.player_won = self.player.is_finished()
self.computer_won = self.computer.is_finished()
def get_the_result_of_game(self):
if self.user_made_a_mistake:
return 'Будте внимательнее! Вы ошиблись. Игра окончена.'
elif self.player_won and self.computer_won:
return 'Ничья!'
elif self.player_won:
return 'Вы победили!'
elif self.computer_won:
return 'Компьютер выйграл'
else:
return 'Oops! чтото пошло не так. Никто не победил.'
| true |
9099c451ced1a2dfd36df68a56baa8bbc1acfe67 | Python | ragegit/sync_measure | /rasterplotMatrix.py | UTF-8 | 15,436 | 2.953125 | 3 | [] | no_license | import numpy as np
import itertools as it
import random as rn
import matplotlib.pyplot as plt
from matplotlib import cm
from create_matrix_SR_SI_AR_AI import* # functions to creat matrices or change existing ones:
# SR(N,Tmax),SI(N,Tmax),AR(N,Tmax),AI(N,Tmax),
# SR_noisy(N,Tmax),AR_noisy(N,Tmax)
# mixed(N,Tmax,popspikes)
# add_noise(raster), smaller_step(raster)
from measures import * # has functions to calculate measures defined by Renart, Brunel, ... in it:
# Renart_measure(raster), fano_factor, my_measure
#N=1000 # number of neurons
#Tmax=2000 # number of timesteps
def main(N,Tmax):
# different raster plots named by their features--------------------------------------------------------------
rasterSR = SR(N,Tmax)
noisy_rasterSR = add_noise(rasterSR)
smaller_step_rasterSR = smaller_step(rasterSR)
smaller_step_noisy_rasterSR = add_noise(smaller_step_rasterSR)
smaller_step_more_noisy_rasterSR = add_noise(smaller_step_noisy_rasterSR)
rasterAR = AR(N,Tmax)
rasterSI = SI(N,Tmax)
rasterAI = AI(N,Tmax)
Mixed5 = mixed(N,Tmax,5) # create a raster, which is mostly SI, but has 5 population spikes
Mixed10 = mixed(N,Tmax,10)
Mixed20 = mixed(N,Tmax,20)
rasterPo = Poisson(N,Tmax)
#decreasing synchrony
rasterlist = increase_noise(rasterSI, 20)
crucial_rasters = [rasterlist[0],rasterlist[1],rasterlist[2],rasterlist[20]]
Renart_measure_list = map(Renart_measure, crucial_rasters)
fano_factor_list = map(fano_factor, crucial_rasters)
my_measure_list = map(my_measure, crucial_rasters)
plt.rcParams.update({'font.size':15})
#plot measure outcomes along axis
fig = plt.figure()
a = fig.add_subplot(3,1,1)
plt.plot(Renart_measure_list,len(Renart_measure_list)*[0], 'o')
plt.title("Renart measure")
a = fig.add_subplot(3,1,2)
plt.plot(fano_factor_list,len(fano_factor_list)*[0], 'o')
plt.title("fano factor")
a = fig.add_subplot(3,1,3)
plt.plot(my_measure_list,len(my_measure_list)*[0], 'o')
plt.title("My measure")
#plot rasters--------------------------------------------------------------
plt.matshow(rasterSI[:,0:200],cmap=cm.binary)
plt.xlabel("time bin")
plt.ylabel("neuron number")
plt.title("Synchronous Irregular state")
plt.savefig('Pictures/SI')
plt.matshow(rasterlist[1][:,0:200],cmap=cm.binary)
plt.xlabel("time bin")
plt.ylabel("neuron number")
plt.title("Some synchrony left from the Synchronous Irregular state")
plt.savefig('Pictures/noisy_SI_1')
plt.matshow(rasterlist[2][:,0:200],cmap=cm.binary)
plt.xlabel("time bin")
plt.ylabel("neuron number")
plt.title("Some synchrony left from the Synchronous Irregular state")
plt.savefig('Pictures/noisy_SI_2')
plt.matshow(rasterlist[20][:,0:200],cmap=cm.binary)
plt.xlabel("time bin")
plt.ylabel("neuron number")
plt.title("No synchrony left from the Synchronous Irregular state")
plt.savefig('Pictures/noisy_SI_3')
plt.matshow(rasterSR[:,0:200],cmap=cm.binary)
plt.xlabel("time bin")
plt.ylabel("neuron number")
plt.title("Synchronous Regular state")
plt.savefig('Pictures/SR')
plt.matshow(smaller_step_rasterSR[:,0:200],cmap=cm.binary)
plt.xlabel("time bin")
plt.ylabel("neuron number")
plt.title("Synchronous Regular state with smaller time bin")
plt.savefig('Pictures/small_bin_SR')
plt.matshow(smaller_step_noisy_rasterSR[:,0:200],cmap=cm.binary)
plt.xlabel("time bin")
plt.ylabel("neuron number")
plt.title("Smaller time bin - still SR?")
plt.savefig('Pictures/noisy_SR')
plt.matshow(smaller_step_more_noisy_rasterSR[:,0:200],cmap=cm.binary)
plt.xlabel("time bin")
plt.ylabel("neuron number")
plt.title("very noisy SR")
plt.savefig('Pictures/very_noisy_SR')
plt.matshow(rasterAI[:,0:200],cmap=cm.binary)
plt.xlabel("time bin")
plt.ylabel("neuron number")
plt.title("Asynchronous Irregular state")
plt.savefig('Pictures/AI')
plt.matshow(rasterAR[:,0:200],cmap=cm.binary)
plt.xlabel("time bin")
plt.ylabel("neuron number")
plt.title("Asynchronous Regular state")
plt.savefig('Pictures/AR')
plt.matshow(Mixed5[:,0:200],cmap=cm.binary)
plt.xlabel("time bin")
plt.ylabel("neuron number")
plt.title("Mixed state")
plt.savefig('Pictures/Mixed5')
plt.matshow(Mixed10[:,0:200],cmap=cm.binary)
plt.xlabel("time bin")
plt.ylabel("neuron number")
plt.title("Mixed state")
plt.savefig('Pictures/Mixed10')
plt.matshow(Mixed20[:,0:200],cmap=cm.binary)
plt.xlabel("time bin")
plt.title("Mixed state")
plt.ylabel("neuron number")
plt.savefig('Pictures/Mixed20')
plt.matshow(rasterPo[:,0:200],cmap=cm.binary)
plt.xlabel("time bin")
plt.title("Poisson state")
plt.ylabel("neuron number")
plt.savefig('Pictures/Poisson')
plt.show()
## plot rasters in subplot--------------------------------------------------------------
fig = plt.figure(2000)
a = fig.add_subplot(2,2,1)
plt.plot(np.where(rasterSR[:,0:200]==1)[0],np.where(rasterSR[:,0:200]==1)[1], '|')
plt.xlabel("time bin")
plt.ylabel("neuron number")
plt.title("Synchronous Regular state")
a = fig.add_subplot(2,2,2)
plt.plot(np.where(rasterAR[:,0:200]==1)[0],np.where(rasterAR[:,0:200]==1)[1], '|')
plt.xlabel("time bin")
plt.ylabel("neuron number")
plt.title("Asynchronous Regular state")
a = fig.add_subplot(2,2,3)
plt.plot(np.where(rasterSI[:,0:200]==1)[0],np.where(rasterSI[:,0:200]==1)[1], '|')
plt.xlabel("time bin")
plt.ylabel("neuron number")
plt.title("Synchronous Irregular state")
a = fig.add_subplot(2,2,4)
plt.plot(np.where(rasterAI[:,0:200]==1)[0],np.where(rasterAI[:,0:200]==1)[1], '|')
plt.xlabel("time bin")
plt.ylabel("neuron number")
plt.title("Asynchronous Irregular state")
plt.show()
## evaluate data with different measures------------------------------------------------------------------------
## population rate
## timebin as large as the step width
#popSR0 = poprate(rasterSR,0,1) # calculation of pop. rate for a timebin as large as the step width for SR
#popSR1 = poprate(rasterSR,1,2)
#popSR2 = poprate(rasterSR,2,3)
#popSR6 = poprate(rasterSR,6,7)
#popAR0 = poprate(rasterAR,0,1) # calculation of pop. rate for a timebin as large as the step width for AR
#popAR1 = poprate(rasterAR,1,2)
#popAR2 = poprate(rasterAR,2,3)
#popAR6 = poprate(rasterAR,6,7)
#popSR0 = poprate(rasterSR,0,1) # calculation of pop. rate for a timebin as large as the step width for SR
#popSR1 = poprate(rasterSR,1,2)
#popSR2 = poprate(rasterSR,2,3)
#popSR6 = poprate(rasterSR,6,7)
#popAI0 = poprate(rasterAI,0,1) # calculation of pop. rate for a timebin as large as the step width for AI
#popAI1 = poprate(rasterAI,1,2)
#popAI2 = poprate(rasterAI,2,3)
#popAI6 = poprate(rasterAI,6,7)
## timebin as large as the step width
#ratelistSR1 = map(poprate,[rasterSR]*Tmax,range(0,Tmax-1),range(1,Tmax)) # calculation of pop. rate for a timebin as large as the step width for SR
#ratelistAR1 = map(poprate,[rasterAR]*Tmax,range(0,Tmax-1),range(1,Tmax)) # calculation of pop. rate for a timebin as large as the step width for AR
#ratelistSI1 = map(poprate,[rasterSI]*Tmax,range(0,Tmax-1),range(1,Tmax))
#ratelistAI1 = map(poprate,[rasterAI]*Tmax,range(0,Tmax-1),range(1,Tmax))
## timebin twice as large as the step width
#x = range(0,Tmax-1,2)
#y = range(2,Tmax,2)
#B = len(x)
#ratelistSR2 = map(poprate,[rasterSR]*B,x,y) # calculation of pop. rate for a timebin as large as the step width for SR
#ratelistAR2 = map(poprate,[rasterAR]*B,x,y) # calculation of pop. rate for a timebin as large as the step width for AR
#ratelistSI2 = map(poprate,[rasterSI]*B,x,y)
#ratelistAI2 = map(poprate,[rasterAI]*B,x,y)
## timebin six times as large as the step width
#x = range(0,Tmax-5,6)
#y = range(6,Tmax,6)
#B = len(x)
#ratelistSR6 = map(poprate,[rasterSR]*B,x,y) # calculation of pop. rate for a timebin as large as the step width for SR
#ratelistAR6 = map(poprate,[rasterAR]*B,x,y) # calculation of pop. rate for a timebin as large as the step width for AR
#ratelistSI6 = map(poprate,[rasterSI]*B,x,y)
#ratelistAI6 = map(poprate,[rasterAI]*B,x,y)
## plot population rates
#map(plt.plot, [ratelistSR1,ratelistAR1,ratelistSI1,ratelistAI1], ['o']*4)
#plt.ylabel("instantaneous population rate")
#plt.xlabel("timestep")
#plt.ylim((-0.1,1.1))
#plt.show()
#map(plt.plot, [ratelistSR2,ratelistAR2,ratelistSI2,ratelistAI2], ['o']*4)
#plt.ylabel("instantaneous population rate")
#plt.xlabel("timestep")
#plt.ylim((-0.1,1.1))
#plt.show()
#map(plt.plot, [ratelistSR6,ratelistAR6,ratelistSI6,ratelistAI6], ['o']*4)
#plt.ylabel("instantaneous population rate")
#plt.xlabel("timestep")
#plt.ylim((-0.1,1.1))
#plt.show()
## Mixed and AI state should be compared!
## timebin as large as the step width
#ratelistSR1 = map(poprate,[rasterSR]*Tmax,range(0,Tmax-1),range(1,Tmax)) # calculation of pop. rate for a timebin as large as the step width for SR
#ratelistAR1 = map(poprate,[rasterAR]*Tmax,range(0,Tmax-1),range(1,Tmax)) # calculation of pop. rate for a timebin as large as the step width for AR
#ratelistSI1 = map(poprate,[rasterSI]*Tmax,range(0,Tmax-1),range(1,Tmax))
#ratelistAI1 = map(poprate,[rasterAI]*Tmax,range(0,Tmax-1),range(1,Tmax))
## timebin twice as large as the step width
#x = range(0,Tmax-1,2)
#y = range(2,Tmax,2)
#B = len(x)
#ratelistSR2 = map(poprate,[rasterSR]*B,x,y) # calculation of pop. rate for a timebin as large as the step width for SR
#ratelistAR2 = map(poprate,[rasterAR]*B,x,y) # calculation of pop. rate for a timebin as large as the step width for AR
#ratelistSI2 = map(poprate,[rasterSI]*B,x,y)
#ratelistAI2 = map(poprate,[rasterAI]*B,x,y)
## timebin six times as large as the step width
#x = range(0,Tmax-5,6)
#y = range(6,Tmax,6)
#B = len(x)
#ratelistSR6 = map(poprate,[rasterSR]*B,x,y) # calculation of pop. rate for a timebin as large as the step width for SR
#ratelistAR6 = map(poprate,[rasterAR]*B,x,y) # calculation of pop. rate for a timebin as large as the step width for AR
#ratelistSI6 = map(poprate,[rasterSI]*B,x,y)
#ratelistAI6 = map(poprate,[rasterAI]*B,x,y)
# plot population rates
#map(plt.plot, [ratelistSR1,ratelistAR1,ratelistSI1,ratelistAI1], ['o']*4)
#plt.ylabel("instantaneous population rate")
#plt.xlabel("timestep")
#plt.ylim((-0.1,1.1))
#plt.show()
#map(plt.plot, [ratelistSR2,ratelistAR2,ratelistSI2,ratelistAI2], ['o']*4)
#plt.ylabel("instantaneous population rate")
#plt.xlabel("timestep")
#plt.ylim((-0.1,1.1))
#plt.show()
#map(plt.plot, [ratelistSR6,ratelistAR6,ratelistSI6,ratelistAI6], ['o']*4)
#plt.ylabel("instantaneous population rate")
#plt.xlabel("timestep")
#plt.ylim((-0.1,1.1))
#plt.show()
#plt.rcParams.update({'font.size':10})
##--------------------------------------------with subplots
#fig = plt.figure(1000)
#a = fig.add_subplot(2,2,1)
#plt.plot(ratelistSR1, 'o')
#plt.title("SR")
#plt.ylabel("instantaneous population rate")
##plt.xlabel("timestep")
#plt.ylim((-0.1,1.1))
#a.autoscale_view()
#a = fig.add_subplot(2,2,2)
#plt.plot(ratelistAR1, 'o')
#plt.title("AR")
##plt.ylabel("instantaneous population rate")
##plt.xlabel("timestep")
#plt.ylim((-0.1,1.1))
#a.autoscale_view()
#a = fig.add_subplot(2,2,3)
#plt.plot(ratelistSI1, 'o')
#plt.title("SI")
#plt.ylabel("instantaneous population rate")
#plt.xlabel("timestep")
#plt.ylim((-0.1,1.1))
#a.autoscale_view()
#a = fig.add_subplot(2,2,4)
#plt.plot(ratelistAI1, 'o')
#plt.title("AI")
##plt.ylabel("instantaneous population rate")
#plt.xlabel("timestep")
#plt.ylim((-0.1,1.1))
#plt.savefig('Simulations1/step1')
##plt.show()
##--------------------------------------------with subplots
#fig = plt.figure(1001)
#a = fig.add_subplot(2,2,1)
#plt.plot(ratelistSR2, 'o')
#plt.title("SR")
#plt.ylabel("instantaneous population rate")
##plt.xlabel("timestep")
#plt.ylim((-0.1,1.1))
#a.autoscale_view()
#a = fig.add_subplot(2,2,2)
#plt.plot(ratelistAR2, 'o')
#plt.title("AR")
##plt.ylabel("instantaneous population rate")
##plt.xlabel("timestep")
#plt.ylim((-0.1,1.1))
#a.autoscale_view()
#a = fig.add_subplot(2,2,3)
#plt.plot(ratelistSI2, 'o')
#plt.title("SI")
#plt.ylabel("instantaneous population rate")
#plt.xlabel("timestep")
#plt.ylim((-0.1,1.1))
#a.autoscale_view()
#a = fig.add_subplot(2,2,4)
#plt.plot(ratelistAI2, 'o')
#plt.title("AI")
##plt.ylabel("instantaneous population rate")
#plt.xlabel("timestep")
#plt.ylim((-0.1,1.1))
#plt.savefig('Simulations1/step2')
##plt.show()
##--------------------------------------------with subplots
#fig = plt.figure(1002)
#a = fig.add_subplot(2,2,1)
#plt.plot(ratelistSR6, 'o')
#plt.title("SR")
#plt.ylabel("instantaneous population rate")
##plt.xlabel("timestep")
#plt.ylim((-0.1,1.1))
#a.autoscale_view()
#a = fig.add_subplot(2,2,2)
#plt.plot(ratelistAR6, 'o')
#plt.title("AR")
##plt.ylabel("instantaneous population rate")
##plt.xlabel("timestep")
#plt.ylim((-0.1,1.1))
#a.autoscale_view()
#a = fig.add_subplot(2,2,3)
#plt.plot(ratelistSI6, 'o')
#plt.title("SI")
#plt.ylabel("instantaneous population rate")
#plt.xlabel("timestep")
#plt.ylim((-0.1,1.1))
#a.autoscale_view()
#a = fig.add_subplot(2,2,4)
#plt.plot(ratelistAI6, 'o')
#plt.title("AI")
##plt.ylabel("instantaneous population rate")
#plt.xlabel("timestep")
#plt.ylim((-0.1,1.1))
#plt.savefig('Simulations1/step6')
##plt.show()
# Renart_measure
rSR = Renart_measure(rasterSR)
smaller_step_rSR = Renart_measure(smaller_step_rasterSR)
smaller_step_noisy_rSR = Renart_measure(smaller_step_noisy_rasterSR)
smaller_step_more_noisy_rSR = Renart_measure(smaller_step_more_noisy_rasterSR)
rAR = Renart_measure(rasterAR)
rSI = Renart_measure(rasterSI)
rAI = Renart_measure(rasterAI)
rM5 = Renart_measure(Mixed5)
rM10 = Renart_measure(Mixed10)
rM20 = Renart_measure(Mixed20)
rP = Renart_measure(rasterPo)
# my_measure
mSR = my_measure(rasterSR)
smaller_step_mSR = my_measure(smaller_step_rasterSR)
smaller_step_noisy_mSR = my_measure(smaller_step_noisy_rasterSR)
smaller_step_more_noisy_mSR = my_measure(smaller_step_more_noisy_rasterSR)
mAR = my_measure(rasterAR)
mSI = my_measure(rasterSI)
mAI = my_measure(rasterAI)
mM5 = my_measure(Mixed5)
mM10 = my_measure(Mixed10)
mM20 = my_measure(Mixed20)
mP = my_measure(rasterPo)
# poisson_measure
pSR = poisson_measure(rasterSR)
smaller_step_pSR = poisson_measure(smaller_step_rasterSR)
smaller_step_noisy_pSR = poisson_measure(smaller_step_noisy_rasterSR)
smaller_step_more_noisy_pSR = poisson_measure(smaller_step_more_noisy_rasterSR)
pAR = poisson_measure(rasterAR)
pSI = poisson_measure(rasterSI)
pAI = poisson_measure(rasterAI)
pM5 = poisson_measure(Mixed5)
pM10 = poisson_measure(Mixed10)
pM20 = poisson_measure(Mixed20)
pP = poisson_measure(rasterPo)
## print and compare Renart_measure and my_measure
print("\t \t \t Renart \t my_measure \t poisson_measure")
print("AR \t \t \t %f \t %f \t %f" %(rAR, mAR, pAR))
print("SR \t \t \t %f \t %f \t %f" %(rSR, mSR, pSR))
print("noisy, smaller step SR %f \t %f \t %f" %(smaller_step_noisy_rSR,smaller_step_noisy_mSR,smaller_step_noisy_pSR))
print("more noisy, smaller step SR %f \t %f \t %f" %(smaller_step_more_noisy_rSR,smaller_step_more_noisy_mSR,smaller_step_more_noisy_pSR))
print("AI \t \t \t %f \t %f \t %f" %(rAI,mAI,pAI))
print("SI \t \t \t %f \t %f \t %f" %(rSI,mSI,pSI))
print("Mixed 5 \t \t %f \t %f \t %f" %(rM5,mM5,pM5))
print("Mixed 10 \t \t %f \t %f \t %f" %(rM10,mM10,pM10))
print("Mixed 20 \t \t %f \t %f \t %f" %(rM20,mM20,pM20))
print("Poisson \t \t %f \t %f \t %f" %(rP,mP,pP))
return 0
| true |
679f90dda039f6c0800c6f3b40b4e5a21d67d14f | Python | nikghosh/spaceInvadersRL | /record_humanplay.py | UTF-8 | 1,574 | 2.828125 | 3 | [] | no_license | import gym
import sys
from gym.utils import play as p
import numpy as np
from pygit2 import Repository
import pandas as pd
import datetime
import pickle
# Things to fix / look at
# Notes, pickling for now, is this the best way to store the info?
# pandas dataframe creation might be n^2 the way im doing it rn , look at later
# Adjust game characteristics here
# frames per second, 30 is the default
fps_rate = 10
# game name, prolly nvr gonna change this
game_name = 'SpaceInvaders-v0'
# gets branch name.
head = Repository('.').head.shorthand
# Folder to dump in
filePath = './human_play/'
# Class to play the game + serialize the dataframe w play stats.
class PlayGame(object):
def __init__(self):
self.game_data = pd.DataFrame()
self.score = 0
def callbackFunction(self,obs_t, obs_tp1, action, rew, done, info):
# GS stands for game state.
column_names = ["PriorGS", "PostGS", "Action", "Reward", "Done?", "Info"]
self.score += rew
self.game_data = self.game_data.append(pd.DataFrame([[obs_t,\
obs_tp1,action,rew,done,info]], columns = column_names), ignore_index = True)
return 1
def run(self):
env = gym.make(game_name)
p.play(env, zoom = 2, fps = fps_rate, callback = self.callbackFunction)
now = datetime.datetime.now()
filename = filePath + head + "_Score_" + str(int(self.score)) + ".data"
f = open(filename, "wb")
pickle.dump(self.game_data, f)
f.close()
if __name__ == '__main__':
g = PlayGame()
g.run()
| true |
f9e90e06958a8ecfa2061353f57dbfaba8acc407 | Python | patrickmoffitt/laser-light-meter | /app/python/prediction.py | UTF-8 | 5,583 | 2.734375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Detect duty cycle values in sample data using a model previously trained on the same laser. """
from os import path, getcwd, listdir
from platform import node
from json import JSONEncoder
import time
import sys
import argparse
from datetime import datetime
from math import floor, pow
import numpy as np
from sklearn.externals import joblib
from scipy import stats
import re
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
parser = argparse.ArgumentParser()
parser.add_argument('model_id', help='Model ID number for the model.')
parser.add_argument('sample_id', help='Model ID number for the sample.')
parser.add_argument('operator_id', help='Operator ID number for the person running the prediction.')
parser.add_argument('-d', '--directory', default=getcwd(),
help="Base directory for the models. Defaults to current directory.")
parser.add_argument('--host', default=node(),
help="The local hostname. Defaults to the local hostname.")
args = parser.parse_args()
""" Retrieve the stored model and sample data. """
model_file = path.join(args.directory, args.model_id, 'knn_model.pkl.xz')
sample_file = path.join(args.directory, args.sample_id, 'poly2d.pkl.xz')
for file in [model_file, sample_file]:
if not path.isfile(file):
print('Error:', file, 'is not a valid file.', file=sys.stderr, flush=True)
exit(1)
try:
knn = joblib.load(model_file)
except KeyError as e:
print('Error:', model_file, 'is not a valid model.', file=sys.stderr, flush=True)
exit(1)
try:
samples = joblib.load(sample_file)
X = np.asarray(samples.data)
y = np.asarray(samples.target)
except KeyError as e:
print('Error:', sample_file, 'is not a valid sample.', file=sys.stderr, flush=True)
exit(1)
predict = knn.predict(X) # Predict the class labels for the provided data.
predict_proba = knn.predict_proba(X) # Return probability estimates for the test data.
score = knn.score(X, y) # Returns the mean accuracy on the given test data and labels.
predict_proba_file = ''.join([
args.directory, path.sep,
args.model_id, path.sep,
'predict_proba_',
args.sample_id,
'_data_by_',
args.model_id,
'_model.pkl.xz'])
joblib.dump(predict_proba, predict_proba_file)
""" Chart probability distribution. """
title = ' '.join([
datetime.fromtimestamp(int(args.sample_id)).strftime('%Y-%m-%d %H:%M %p'),
'data by',
datetime.fromtimestamp(int(args.model_id)).strftime('%Y-%m-%d %H:%M %p'),
'model.'])
def get_range(directory):
""" Determine the range for the samples by inspecting the samples directory. """
regex = '[\d]{2}_duty'
sub_dirs = sorted([f for f in listdir(directory) if path.isdir(path.join(directory, f)) and re.match(regex, f)])
min_range = sub_dirs[0].split('_')[0]
max_range = sub_dirs[len(sub_dirs) - 1].split('_')[0]
return range(int(min_range), int(max_range) + 1)
series = list(get_range(path.join(args.directory, args.sample_id)))
values = np.sum(predict_proba, axis=0)
plt.plot(series, values, label='Probability')
plt.title('Probability Distribution')
z = np.polyfit(series, values, 1)
p = np.poly1d(z)
coef = z.tolist()
plt.plot(series, p(series), label='\n'.join(map(repr, coef)))
plt.ylabel('Sum')
plt.xlabel('\n'.join(['Category', title]))
plt.axis([20, 80, 20, 80])
plt.legend(loc='upper right')
prob_dist_file = ''.join([
args.directory, path.sep,
args.model_id, path.sep,
'prob_dist_',
args.sample_id,
'_data_by_',
args.model_id,
'_model.svg'])
plt.tight_layout()
plt.savefig(prob_dist_file, papertype='letter', orientation='landscape')
""" Chart mean variance histogram. """
hist, axh = plt.subplots()
hist.subplots_adjust(bottom=0.2)
a = predict_proba.sum(axis=0)
var = np.var(a, axis=0)
mu = a.mean(axis=0) # mean of distribution
sigma = a.std(axis=0) # standard deviation of distribution
sem = stats.sem(a, axis=None, ddof=0)
# the histogram of the data
n, bins, patches = axh.hist(a, bins='auto', normed=1)
no_bins = len(bins)
# add a 'best fit' line
y = mlab.normpdf(bins, mu, sigma)
axh.plot(bins, y, '--', color='orange', label='Sigma')
# add sem line
r = mlab.normpdf(bins, mu, sem)
axh.plot(bins, r, '--', color='red', label='SEM')
axh.set_xlabel('\n'.join(['Variation about the Mean', title]))
axh.set_ylabel('Probability Density')
axh.set_title(r'Histogram: $\mu=$%0.2f, $\sigma=$%0.2f, bins=%2u, sem=%0.2f, var=%0.2f'
% (mu, sigma, no_bins, sem, var))
plt.legend(loc='upper right')
hist_file = ''.join([
args.directory, path.sep,
args.model_id, path.sep,
'mean_variance_',
args.sample_id,
'_data_by_',
args.model_id,
'_model.svg'])
plt.savefig(hist_file, papertype='letter', orientation='landscape')
sum_sq = 0
for guess, target in zip(predict, y):
sum_sq += pow(guess - target, 2)
std_err_estimate = sum_sq / len(X)
output = JSONEncoder().encode({
'sample-model-id': args.sample_id,
'knn-model-id': args.model_id,
'operator-id': args.operator_id,
'host-name': args.host.split('.')[0],
'date': floor(time.time()),
'error-proba-mean': mu,
'error-proba-std-dev': sigma,
'error-proba-std-err-mean': sem,
'error-proba-variance': var,
'error-proba-bins': no_bins,
'predict-proba': predict_proba_file,
'prediction-score': score,
'std-err-estimate': std_err_estimate,
'proba-dist-chart': prob_dist_file,
'mean-variance-chart': hist_file})
print()
print(output, flush=True)
| true |
7e2fe8e98797d2de13f78b3af3ecbbc6af2f24fd | Python | homeah/myPython | /026.py | UTF-8 | 382 | 4.125 | 4 | [] | no_license | '''
【程序26】
题目:利用递归方法求5!。
1.程序分析:递归公式:fn=fn_1*4!
2.程序源代码:
'''
'''
def recursion(n):
if n == 1:
return n
else:
return n*recursion(n-1)
print('5!的结果是%d'%recursion(5))
'''
def recursion(n):
return n if n==1 else n*recursion(n-1)
print('5!的结果是%d'%recursion(5))
| true |
97193d64cfa7e11cd7c6c620aad055a1f2f8e7fc | Python | Xuchiyu/selenium_ui_auto | /test_case/test_home.py | UTF-8 | 3,176 | 2.90625 | 3 | [] | no_license | # coding=utf-8
# @Time : 2019/12/22
# @Author: 星空物语
# @File : config.py
# @Description: 百度首页测试用例
import sys
reload(sys)
sys.setdefaultencoding('utf8')
from page_object.home_page import HomePage
from page_object.news_page import NewsPage
from page_object.hao123_page import Hao123Page
from page_object.search_page import SearchPage
import pytest
import config.config as cf
import logging
log = logging.getLogger('szh.TestHome')
class TestHome():
"""
pytest:
测试文件以test_开头
测试类以Test开头,并且不能带有__init__方法
测试函数以test_开头
断言使用assert
"""
driver = cf.get_value('driver') # 从全局变量取driver
home_page = HomePage(driver)
news_page = NewsPage(driver)
hao123_page = Hao123Page(driver)
search_page = SearchPage(driver)
def test_open_homepage(self):
"""首页-打开百度首页"""
try:
self.home_page.open_homepage()
assert self.home_page.wait_element(self.home_page.l_more_product) # 有‘更多产品’element
log.info(u'断言有‘更多产品’元素 成功')
self.home_page.screenshot(u'打开百度首页')
except Exception, e:
self.home_page.screenshot(u'打开百度首页失败')
raise e
def test_input_keyword(self):
"""首页-输入搜索关键字,自动跳转"""
try:
self.home_page.open_homepage()
self.home_page.input_keyword(u'星空物语') # 输入关键字
self.search_page.wait_element(self.search_page.l_baike) # 等待含星空物语_百度百科的搜索结果
assert self.home_page.wait_text(u'星空物语_百度百科') # 输入关键字自动跳搜索结果页,第一项是百科
log.info(u'断言有‘星空物语_百度百科’文字 成功')
self.home_page.screenshot(u'输入关键字跳转')
except Exception, e:
self.home_page.screenshot(u'输入关键字跳转失败')
raise e
def test_click_news(self):
"""首页-打开新闻"""
try:
self.home_page.open_homepage()
self.home_page.click_news() # 点击新闻
assert self.home_page.wait_element(self.news_page.d_carousel) # 轮播图出现
log.info(u'断言有‘轮播图’元素 成功')
self.home_page.screenshot(u'打开新闻')
except Exception, e:
self.home_page.screenshot(u'打开新闻失败')
raise e
def test_click_hao123(self):
"""首页-打开hao123"""
try:
self.home_page.open_homepage()
self.home_page.click_hao123() # 点击hao123
assert self.home_page.wait_element(self.hao123_page.l_more_product) # 腾讯链接出现
log.info(u'断言有‘腾讯链接’ 成功')
except Exception, e:
self.home_page.screenshot(u'打开hao123失败')
raise e
if __name__ == '__main__':
# pytest.main(['-v', '-s', 'test_home.py::TestHome::test_input_keyword'])
pytest.main(['-v', '-s']) | true |
d02c0a99c58b4f2dddf53e493fca488d63135308 | Python | kkaris/neo4jnx | /neo4jnx/tsv.py | UTF-8 | 1,488 | 2.96875 | 3 | [] | no_license | import csv
import gzip
import json
def get_data_value(data, key):
val = data.get(key)
if not val:
return ""
elif isinstance(val, (list, dict)):
return json.dumps(val)
elif isinstance(val, str):
return val.replace('\n', ' ')
else:
return val
def canonicalize(s):
return s.replace('\n', ' ')
def graph_to_tsv(g, nodes_path, edges_path):
metadata = sorted(set(key for node, data in g.nodes(data=True)
for key in data))
header = "name:ID", ':LABEL', *metadata
node_rows = (
(canonicalize(node), 'Node',
*[get_data_value(data, key) for key in metadata])
for node, data in g.nodes(data=True)
)
with gzip.open(nodes_path, mode="wt") as fh:
node_writer = csv.writer(fh, delimiter="\t") # type: ignore
node_writer.writerow(header)
node_writer.writerows(node_rows)
metadata = sorted(set(key for u, v, data in g.edges(data=True)
for key in data))
edge_rows = (
(
canonicalize(u), canonicalize(v), 'Relation',
*[get_data_value(data, key) for key in metadata],
)
for u, v, data in g.edges(data=True)
)
with gzip.open(edges_path, "wt") as fh:
edge_writer = csv.writer(fh, delimiter="\t") # type: ignore
header = ":START_ID", ":END_ID", ":TYPE", *metadata
edge_writer.writerow(header)
edge_writer.writerows(edge_rows)
| true |
2550c440c02a4131e39a1084643f718bd086a3ac | Python | tocxu/program | /python/function_return.py | UTF-8 | 253 | 3.625 | 4 | [] | no_license | def maximum(x,y):
if x>y:
return x
elif x==y:
return 'The numbers are equal'
else:
return y
print maximum(2,3)
print '\n'
#x=int(raw_input('x= ' ))
#y=int(raw_input('y= '))
x=raw_input('x= ')
y=raw_input('y= ')
print maximum(x,y)
print 'Done'
| true |
bc2fd0b4fb95813c16b4489b31a7b4cf8a09d91b | Python | pauchan/akagi | /akagi/data_sources/s3_data_source.py | UTF-8 | 1,568 | 2.734375 | 3 | [
"MIT"
] | permissive | from akagi.data_source import DataSource
from akagi.data_file import data_files_for_s3_prefix, data_files_for_s3_keys
class S3DataSource(DataSource):
'''S3DataSource replesents a set of files on Amazon S3 bucket.
'''
@classmethod
def for_prefix(cls, bucket_name, prefix, file_format='binary', no_cache=False):
return S3DataSource(bucket_name, prefix=prefix, keys=None, file_format=file_format, no_cache=no_cache)
@classmethod
def for_keys(cls, bucket_name, keys, file_format='binary', no_cache=False):
return S3DataSource(bucket_name, prefix=None, keys=keys, file_format=file_format, no_cache=no_cache)
@classmethod
def for_key(cls, bucket_name, key, file_format='binary', no_cache=False):
return S3DataSource(bucket_name, prefix=None, keys=[key], file_format=file_format, no_cache=no_cache)
def __init__(self, bucket_name, prefix=None, keys=None, file_format='binary', no_cache=False):
self._file_format = file_format
self._bucket_name = bucket_name
self._keys = keys
self._prefix = prefix
self._no_cache = no_cache
self._data_files = None
@property
def data_files(self):
if self._data_files is None:
if self._prefix is not None:
self._data_files = data_files_for_s3_prefix(self._bucket_name, self._prefix, self._file_format)
elif self._keys is not None:
self._data_files = data_files_for_s3_keys(self._bucket_name, self._keys, self._file_format)
return self._data_files
| true |
c23bca077298669c297047d507a90ab3e876e582 | Python | jinghui31/Document | /Python/windowsform.py | UTF-8 | 1,877 | 2.671875 | 3 | [] | no_license | from tkinter import *
import barcode
from barcode.writer import ImageWriter
import qrcode
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
# 程式一執行產生輸入帳號密碼介面
win=Tk()
#全域帳號、密碼、THREAD數
Barcodestring = None
# cancel按鈕的事件
def FormClose():
win.destroy()
exit()
# ok按鈕的事件
def FormOK(edit_barcode):
global Barcodestring
Barcodestring = edit_user.get()
name=edit_save.get().strip()+'.png'
#qr.add_data(Barcodestring)
#qr.make(fit=True)
#img = qr.make_image(fill_color="black", back_color="white")
#img.save(name)
EAN = barcode.get_barcode_class('code39')
ean = EAN(Barcodestring, writer=ImageWriter(),add_checksum=False)
f = open(name, 'wb')
ean.write(f)
f.close()
photo=PhotoImage(file=name)
edit_barcode.configure(image=photo)
edit_barcode.image=photo
#Barcode介面設定
win.title("Barcode 生成器")
win.geometry("500x500")
#輸入要轉換的Barcode
label_user=Label(win, text="請輸入轉換碼(限英文)")
edit_user=Entry(win, text="")
label_user.grid(column=0, row=0)
edit_user.grid(column=1, row=0, columnspan=15)
#輸入要儲存的檔名
label_save=Label(win, text="請輸入檔名(可中文)")
edit_save=Entry(win, text="")
label_save.grid(column=0, row=1)
edit_save.grid(column=1, row=1, columnspan=15)
#Barcode 照片
label_barcode=Label(win, text="barcode :")
label_barcode.grid(column=0, row=2)
edit_barcode=Label(win, text='')
edit_barcode.grid(column=0, row=3,columnspan=5)
#BUTTON-連接事件
button_cancel = Button(win, text="結束", width="15", command=FormClose)
button_ok = Button(win, text="轉換",width="15", command=lambda: FormOK(edit_barcode))
button_cancel.grid(column=1, row=4)
button_ok.grid(column=0, row=4)
win.mainloop()
| true |
99809cc271c7b9d5807aece85fa667ad205409b0 | Python | mmylll/FDSS_Algorithm | /code/reconstructed_topo.py | UTF-8 | 1,594 | 2.984375 | 3 | [] | no_license | class Node:
def __init__(self):
self.children = []
self.in_degree = 0
self.visited = False
self.count = 0
N = 3
M = 3
expressions = [
'2<1',
'0<2',
'1<0'
]
nodes = [Node()] * M
fathers = [i for i in range(N)]
reach_node = 0
has_circle = False
flag = False
def find(num):
if fathers[num] == num:
return num
else:
fathers[num] = find(fathers[num])
return fathers[num]
def union(num1, num2):
father1 = find(num1)
father2 = find(num2)
if father1 != father2:
fathers[num1] = father2
for expression in expressions:
if '<' in expression:
pivot = expression.index('<')
small_num, big_num = int(expression[:pivot]), int(expression[pivot+1:])
nodes[small_num].chilren.append(nodes[big_num])
nodes[small_num].in_degree += 1
elif '>' in expression:
pivot = expression.index('>')
big_num, small_num = int(expression[:pivot]), int(expression[pivot+1:])
nodes[small_num].chilren.append(nodes[big_num])
nodes[small_num].in_degree += 1
elif '=' in expression:
pivot = expression.index('=')
num1, num2 = int(expression[:pivot]), int(expression[pivot+1:])
union(num1, num2)
for i in range(N):
fa = find(i)
nodes[fa].count += 1
nodes[i] = nodes[fa]
root = None
for node in nodes:
if node.in_degree == 0:
root = node
break
if not root:
print('conflict')
def dfs(node):
node.visited = True
global reach_node
reach_node += node.count
if reach_node == N:
| true |
30b56c91817eed0d5db34c3bb1326a604846e24b | Python | cjmccann/comp23-cmccann | /battle/Background.py | UTF-8 | 979 | 3.15625 | 3 | [] | no_license | import pygame, os, sys
from pygame.locals import *
class Background(pygame.sprite.Sprite):
def __init__(self, screen):
pygame.sprite.Sprite.__init__(self)
self.screen = screen
self.scrolling = True
try:
self.image = pygame.image.load('assets/ram_aras.png').convert_alpha()
self.rect = self.image.get_rect()
self.image_w, self.image_h = self.image.get_size()
self.screen_w = self.screen.get_size()[0]
self.screen_h = self.screen.get_size()[1]
self.x = 0
self.y = -1 * self.image_h + self.screen_h # starts at the bottom of img
self.dy = 2
except pygame.error, message:
print "Cannot load background image"
raise SystemExit, message
def update(self):
#if ((self.y > self.image_h - self.screen_h) and self.scrolling == True:
# self.scrolling = False
# else:
self.y += self.dy
def draw(self):
if self.scrolling == True:
draw_pos = self.image.get_rect().move(self.x, self.y)
self.screen.blit(self.image, draw_pos)
| true |
b0e1b6bbfa2a5e702b3df16cefc07f32179f0028 | Python | dteague/VVPlotter | /histograms/pyUproot.py | UTF-8 | 6,760 | 2.609375 | 3 | [] | no_license | import numpy as np
from copy import deepcopy
from scipy.stats import beta
class GenericHist:
def __init__(self, hist=[None, None], err2=[0.], under=0, over=0):
self.hist = hist[0]
self.bins = hist[1]
if self.bins is not None and err2 == [0.]:
err2 = np.zeros(len(self.bins) + 1)
self.histErr2 = np.array(err2[1:-1])
self.underflow = np.array([under, err2[0]])
self.overflow = np.array([over, err2[-1]])
@classmethod
def fromUproot(cls, hist):
if np.array(hist._fSumw2).size == 0:
return cls()
return cls(hist=hist.numpy(), err2=hist._fSumw2, under=hist.underflows,
over=hist.overflows)
def copy_into(self, hist):
for var in ["hist", "bins", "histErr2", "underflow", "overflow"]:
setattr(self, var, getattr(hist, var))
def copy(self):
return deepcopy(self)
def __add__(self, other):
if self.empty():
return deepcopy(other)
if not (self.bins == other.bins).all():
raise Exception("GenericHist: Different bin size")
returnHist = GenericHist()
returnHist.bins = np.array(self.bins)
returnHist.hist = np.array(self.hist + other.hist)
returnHist.histErr2 = np.array(self.histErr2 + other.histErr2)
returnHist.underflow = self.underflow + other.underflow
returnHist.overflow = self.overflow + other.overflow
returnHist.name = self.name
return returnHist
def scale(self, scale):
self.hist *= scale
self.histErr2 *= scale**2
self.underflow *= scale
self.overflow *= scale
self.underflow[1] *= scale
self.overflow[1] *= scale
def empty(self):
return self.bins is None
def setupTGraph(self, graph):
self.hist = np.array(graph.GetY())
self.histErr2 = list()
self.bins = [graph.GetX()[0] - graph.GetErrorX(0)]
self.underflow = np.array([0, 0])
self.overflow = np.array([0, 0])
for i in range(graph.GetN()):
self.histErr2.append(graph.GetErrorY(i)**2)
self.bins.append(2 * graph.GetErrorX(i) + self.bins[-1])
self.histErr2 = np.array(self.histErr2)
self.bins = np.array(self.bins)
def addOverflow(self):
self.hist[-1] += self.overflow[0]
self.histErr2[-1] += self.overflow[1]
self.overflow = np.array([0., 0.])
def addUnderflow(self):
self.hist[0] += self.underflow[0]
self.histErr2[0] += self.underflow[1]
self.underflow = np.array([0., 0.])
def changeAxis(self, newRange):
lowIdx = 0
highIdx = self.bins.size
for i, val in enumerate(self.bins):
if val <= newRange[0]:
lowIdx = i
if val >= newRange[1]:
highIdx = i
break
self.changeAxisIndex(lowIdx, highIdx)
def changeAxisIndex(self, lowIdx, highIdx):
self.bins = self.bins[lowIdx:highIdx+1]
self.overflow[0] += sum(self.hist[highIdx:])
self.overflow[1] += sum(self.histErr2[highIdx:])
self.underflow[0] += sum(self.hist[:lowIdx])
self.underflow[1] += sum(self.histErr2[:lowIdx])
self.hist = self.hist[lowIdx:highIdx]
self.histErr2 = self.histErr2[lowIdx:highIdx]
def rebin(self, rebin):
if not isinstance(rebin, int):
self.special_rebin(rebin)
return (-1, -1)
origRebin = rebin
size = len(self.hist)
subSize = size//rebin
newSize = subSize * rebin
if newSize == 0:
print("New binning is too fine:")
print("Rebin: {}, Old # bins: {}".format(rebin, size))
raise Exception
elif float(newSize)/size < 0.95:
while float(newSize)/size < 0.975:
rebin -= 1
subSize = size//rebin
newSize = subSize * rebin
self.changeAxisIndex(0, newSize)
self.hist = np.sum(self.hist.reshape(rebin, subSize), axis=1)
self.histErr2 = np.sum(self.histErr2.reshape(rebin, subSize), axis=1)
self.bins = self.bins[::subSize]
return (origRebin, rebin)
def special_rebin(self, rebin):
old_width = self.bins[1] - self.bins[0]
i = 0
new_bins = [self.bins[0]]
new_hist = list()
new_histErr2 = list()
for num, width in rebin:
if width > 0:
bin_width = int(width/old_width+0.5)
else:
bin_width = int((len(self.bins)-i-1)/num) + 1
while i + bin_width < len(self.bins) and num > 0:
num -= 1
new_bins.append(self.bins[i+bin_width])
new_hist.append(sum(self.hist[i:i+bin_width]))
new_histErr2.append(sum(self.histErr2[i:i+bin_width]))
i += bin_width
new_bins.append(self.bins[-1])
new_hist.append(sum(self.hist[i:]))
new_histErr2.append(sum(self.histErr2[i:]))
self.bins = np.array(new_bins)
self.hist = np.array(new_hist)
self.histErr2 = np.array(new_histErr2)
def integral(self):
return np.sum(self.hist)
def get_int_err(self, sqrt_err=False):
if sqrt_err:
return np.array([np.sum(self.hist), np.sqrt(np.sum(self.histErr2))])
else:
return np.array([np.sum(self.hist), np.sum(self.histErr2)])
def getMyTH1(self):
full_hist = np.concatenate(([self.underflow[0]], self.hist, [self.overflow[0]]))
full_hist_err2 = np.concatenate(([self.underflow[1]], self.histErr2, [self.overflow[1]]))
return (self.bins, full_hist, full_hist_err2)
def divide(self, denom):
size = len(self.hist)
p_raw = np.divide(self.hist**2, self.histErr2, out=np.zeros(size),
where=self.histErr2!=0)
t_raw = np.divide(denom.hist**2, denom.histErr2, out=np.zeros(size),
where=denom.histErr2!=0)
ratio = np.divide(self.histErr2*denom.hist, self.hist*denom.histErr2,
out=np.zeros(size), where=self.hist*denom.histErr2!=0)
alf = (1-0.682689492137)/2
lo = np.array([beta.ppf(alf, p, t+1) for p, t in zip(p_raw, t_raw)])
hi = np.array([beta.ppf(1 - alf, p+1, t) for p, t in zip(p_raw, t_raw)])
lo[np.isnan(lo)] = 0
hi[np.isnan(hi)] = 0
self.hist = np.divide(self.hist, denom.hist, out=np.zeros(size),
where=denom.hist!=0)
errLo = self.hist - ratio*lo/(1-lo)
errHi = ratio*hi/(1-hi) - self.hist
self.histErr2 = (errLo**2 + errHi**2)/2
return self
| true |
495f23d94141332bed3e3a0a504e53c8f1784ab1 | Python | LeggyOfficial/CodeBreakers2019 | /grill/grillDecoder.py | UTF-8 | 1,743 | 2.75 | 3 | [] | no_license | #!/usr/bin/env python3
from itertools import cycle
from math import sqrt, floor
from textwrap import wrap
import operator
import copy
key='FLEISNRGA'
inputText = "DNFOAV ENLAEI RSITCR HEISCS ATNIBH EREODE PESRSG HESRBO IELARA DONAPR LEDSDT CIHWIE MEDARI ATBNYT GNTWAR ARMHXE HEGGYX ERDRUX"
def printMatrix(matrix):
for line in matrix:
print(line)
def rotateRight(matrix):
return [list(reversed(col)) for col in zip(*matrix)]
def rotateLeft(matrix):
return list(reversed([list((col)) for col in zip(*matrix)]))
keySort = "".join(sorted(key))
keyN =[]
for i in key:
keyN.append(keySort.find(i)+1)
N = int(sqrt(len(keyN)))
inputText = ''.join([i for i in inputText if i.isalpha()]).upper()
matrix = [[i+j*N+1 for i in range(N)] for j in range(N)]
keyIt=iter(keyN)
#this will need some huge refactor..........
windows = floor(len(keyN)/4)
matrixes = []
for i in range(4):
toBeMarked = [];
for j in range(windows):
toBeMarked.append(next(keyIt))
if i == 3 and windows*4<len(keyN):
toBeMarked.append(next(keyIt))
matrixCp = [[0 if k in toBeMarked else k for k in l] for l in matrix]
matrixes.append(matrixCp)
half1 = matrixes[0]+rotateLeft(matrixes[3])
half2 = rotateRight(matrixes[1]) +rotateRight(rotateRight(matrixes[2]))
full = [half1, half2]
grill = list(map(lambda x: x[0]+x[1], zip(*full)))
inputText = wrap(inputText,4*N*N)
outputText =""
thisGrill=copy.deepcopy(grill)
for text in inputText:
code=wrap(text,2*N)
for i in range(4):
for j in range(2*N):
for k in range(2*N):
if thisGrill[j][k] == 0:
outputText += code[j][k]
thisGrill = rotateRight(thisGrill)
print(outputText)
| true |
21938c8045e7634ee3ff7165198a5aa10ba6efa0 | Python | serkanh/uberlearner | /uberlearner/filestorage/models.py | UTF-8 | 2,142 | 2.5625 | 3 | [
"MIT"
] | permissive | from django.core.files.storage import get_storage_class
from easy_thumbnails.files import get_thumbnailer
import os
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from easy_thumbnails.fields import ThumbnailerImageField
from storages.backends.s3boto import S3BotoStorage
default_storage_class = get_storage_class()
def uberphoto_image_path_generator(instance=None, filename=None):
"""
This method generates the filepath for each photo when it is about to be stored. Currently the path takes
the format:
<username>/images/<imagename>.
This also means that the thumbnails will automatically get stored at:
<username>/images/thumbnails/<imagename>_<thumbnails_params>.jpg
"""
if not filename:
#the file already exists in the database
filename = instance.photo.name
path = os.path.join(instance.user.username, 'images', filename)
return path
class UberPhoto(models.Model):
"""
Represents all the images that the users have uploaded. Each image has to have an user field that indicates
the owner of the image.
"""
user = models.ForeignKey(User, related_name='user_images')
image = ThumbnailerImageField(
upload_to=uberphoto_image_path_generator,
storage=default_storage_class(
location='development/filestorage' if settings.DEBUG else 'filestorage',
querystring_auth=False
),
thumbnail_storage=default_storage_class(
location='development/filestorage' if settings.DEBUG else 'filestorage',
reduced_redundancy=True, #saves money on S3!
querystring_auth=False
)
)
def get_url_dict(self):
"""
Returns a dictionary of the form:
{
'thumbnail': <thumbnail_url>,
'original': <original_full_sized_image_url>
}
"""
thumbnail = get_thumbnailer(self.image)['thumbnail']
return {
'thumbnail': thumbnail.url,
'original': self.image.url
}
def __unicode__(self):
return self.image.url
| true |