def saldo(self, id): saldo_file = SALDO_FILE.format(id) if not os.path.exists(saldo_file): return Example.ResultadoOperacion(ctes.COD_CUENTA_INEXISTENTE, 0) sf = open(saldo_file, 'r') saldo = sf.readline() return Example.ResultadoOperacion(ctes.COD_SUCCESS, int(saldo))
def crear(self, id): saldo_file = SALDO_FILE.format(id) mov_file = MOVIM_FILE.format(id) if os.path.exists(saldo_file): return Example.ResultadoOperacion(ctes.COD_CUENTA_EXISTENTE, 0) sf = open(saldo_file, 'a') open(mov_file, 'a').close() sf.write("0") sf.close return Example.ResultadoOperacion(ctes.COD_SUCCESS, 0)
def setup(self): self.graph = create_app(testing=True) self.client = self.graph.flask.test_client() recreate_all(self.graph) self.name1 = "name1" self.example1 = Example( id=new_object_id(), name=self.name1, )
def main(): ww.get_trending() print('trending topics generated') ww.get_tweets() print('tweets based on trending topics are generated') eg.run() print('Apache beam pipeline working and counting tweets words') trends.upload_trending() tweets.upload_tweets() tweetcount.upload_wordcount() tp.upload_tweets_and_topics()
def readDataFile(self, dataFile, schemeAttributes): #The number associated with each example exampleNum = 1 try: #Read the sample file in its entirety with open(dataFile, "r") as sampleReader: headerLine = sampleReader.readline() #If the header line's variables are out of order or missing, exit the program if (self.verifyHeaderLine(headerLine) == False): print("One or more of the header variables in the data file are out of order or missing.") sampleReader.close() exit(1) #Read the first example line in the DataFile fileLine = sampleReader.readline() #Read every Example from the DataFile while (fileLine != None and fileLine != ""): fileLine = fileLine.strip() fileLine = fileLine.replace("\t\t", " ") fileLine = fileLine.replace("\t", " ") fileLine = fileLine.replace(" +", " ") #Create a new Example using the file line dataExample = Example(exampleNum, fileLine, schemeAttributes) #If the example read was invalid, stop reading the file and exit the program if (dataExample.getAttributeValues() == None): sampleReader.close() exit(1) #Else, add the example to the example set else: self.exampleSet.append(dataExample) #Increment the count of the number of examples exampleNum += 1 #Read the next example in the file fileLine = sampleReader.readline() #If the file couldn't be found, inform the user except FileNotFoundError: print("The data file " + dataFile + " could not be found") #If an error occurred while reading the file, inform the user except IOError: print("An error occurred while reading the data file " + dataFile)
def main(): import Example import os cwd = os.getcwd() print "Before fix:\n" Example.Xmastree() #Because regex is used, some special cases exist. We're looking for an exact match #so check https://docs.python.org/3/library/re.html#regular-expression-syntax for syntax Fix(" for i in range\(100\):", " for i in range(50):", "{}/Example.py".format(cwd)) print("\n After fix:\n") reload(Example) Example.Xmastree()
def consultaMovimientos(self, id): a = [] saldo_file = SALDO_FILE.format(id) mov_file = MOVIM_FILE.format(id) if not os.path.exists(saldo_file): return Example.Historial(ctes.COD_CUENTA_INEXISTENTE, a) mf = open(mov_file, 'r') for line in mf: b = line.split(',') a.insert(0, Example.Operacion(b[0], long(b[1]))) mf.close() return Example.Historial(ctes.COD_SUCCESS, a[0:10])
def depositar(self, id, cantidad): saldo_file = SALDO_FILE.format(id) mov_file = MOVIM_FILE.format(id) if not os.path.exists(saldo_file): return Example.ResultadoOperacion(ctes.COD_CUENTA_INEXISTENTE, 0) sf = open(saldo_file, 'r+') saldo = int(sf.readline()) + cantidad sf.close() sf = open(saldo_file, 'w') sf.write(str(saldo)) sf.close() mf = open(mov_file, 'a') mf.write(OP_TEMPLATE.format(ctes.OP_DEPOSITO, cantidad)) mf.close() return Example.ResultadoOperacion(ctes.COD_SUCCESS, saldo)
def read_data(max=None): result = [] letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] max_images_per_letter = float("+inf") if max != None: max_images_per_letter = max / len(letters) for i, letter in enumerate(letters): num_images_read_for_letter = 0 for image_path in glob.glob("../data/" + letter + "/*.png"): img = misc.imread(name=image_path).flatten().tolist() vector_div_inplace(img, 128) result.append(Example(img, i, 10)) num_images_read_for_letter += 1 if num_images_read_for_letter >= max_images_per_letter: break random.shuffle(result) break_index = int(len(result) * test_ratio) test_data = result[0:break_index] train_data = result[break_index + 1:] return train_data, test_data
def create_example(): from {{cookiecutter.app_name}}.models import Example click.echo("create example entry") entry = Example( name='test-entry' ) db.session.add(entry) db.session.commit() click.echo("created test example entry")
def admin_user(db): entry = Example( name='example-test', ) db.session.add(entry) db.session.commit() return entry
def extraer(self, id, cantidad): saldo_file = SALDO_FILE.format(id) mov_file = MOVIM_FILE.format(id) if not os.path.exists(saldo_file): return Example.ResultadoOperacion(ctes.COD_CUENTA_INEXISTENTE, 0) sf = open(saldo_file, 'r+') saldo = int(sf.readline()) sf.close() if saldo < cantidad: return Example.ResultadoOperacion(ctes.COD_SALDO_INSUF, saldo) saldo = saldo - cantidad sf = open(saldo_file, 'w') sf.write(str(saldo)) sf.close() mf = open(mov_file, 'a') mf.write(OP_TEMPLATE.format(ctes.OP_EXTRACCION, cantidad)) mf.close() return Example.ResultadoOperacion(ctes.COD_SUCCESS, saldo)
def test_create_duplicate(self): """ Examples enforce uniqueness on type/external id. """ example1 = Example( name=self.name, ) example2 = Example( name=self.name, ) with transaction(): self.example_store.create(example1) assert_that( calling(self.example_store.create).with_args(example2), raises(DuplicateModelError), )
def run(self): for job in iter(self.queue.get, self.QUIT): self.progress_topic.notify(Example.ClipData(job.get_url(), '',Example.status.InProgress)) value = job.execute() if value =='' self.progress_topic.notify(Example.ClipData(job.get_url(), '',Example.status.Error)) else: self.progress_topic.notify(Example.ClipData(job.get_url(), '',Example.status.Done)) self.queue.task_done() self.queue.task_done() self.queue.put(self.CANCEL) for job in iter(self.queue.get, self.CANCEL): job.cancel() self.queue.task_done() self.queue.task_done()
def test_value_change(): start_val = 5 new_val = 20 example = Example(start_val) example.update_value(new_val) assert example.get_value() == new_val and example.get_previous_value() == start_val
def readData(fileName): dataFileHandle = open(fileName, 'r') exampleLines = dataFileHandle.readlines() examples = [] for example in exampleLines: example = example.strip() example = preprocess(example) toks = example.split(' ', 1) classTag = toks[0] text = toks[1] ex = Example(classTag, text) examples.append(ex) return examples
def test_create(self): """ Examples can be persisted. """ new_example = Example( name=self.name, ) with transaction(): self.example_store.create(new_example) retrieved_example = self.example_store.retrieve(new_example.id) assert_that(retrieved_example, is_(equal_to(new_example)))
async def create_mock(cls, user_input: Dict[str, Any] = None, expected_db_data: Dict[str, Any] = None) -> Example: """ Creates a new mocked Example and returns it using the user's input (what the user typed in when creating the instance, and the expected DB data (what the database is expected to return if the instance/record creation was successful) """ _user_input = {**cls.user_input_template, **(user_input or {})} _expected_db_data = {**cls.expected_db_data_template, **(expected_db_data or {})} example_instance = Example(**_user_input) for attr_name, attr_value in _expected_db_data.items(): setattr(example_instance, attr_name, attr_value) return example_instance
def learnConstraints(filename, sheet, data_ranges): constraints = [] variables = [] for data_range in data_ranges: ex = Example.Example(filename, sheet, data_range) dataTensor, variables = ex.get_dimensions_and_data() dataTensor = dataTensor.transpose((1, 2, 0)) variables = [variables[1], variables[2], variables[0]] lenVar = [] for i in range(len(variables)): lenVar.append(len(variables[i])) orderingNotImp = [0] constraints.append( getConstraintsForAll(dataTensor, variables, orderingNotImp)) # print(constraints) return constraints, [variables[2], variables[0], variables[1]]
def test_retrieve_by_name(self): """ Examples can be retrieved by name. """ new_example = Example( name=self.name, ) with transaction(): self.example_store.create(new_example) retrieved_example = self.example_store.retrieve_by_name( self.name ) assert_that(retrieved_example, is_(equal_to(new_example)))
def main(): try: args = Args() dbg = args.debug # Do your work here - preferably in a class or function, # passing in your args. E.g. exe = Example(args.first) exe.update_value(args.second) print( "First : {}\nSecond: {}".format(exe.get_value(), exe.get_previous_value()) ) except Exception as e: log.error("=============================================") if dbg: log.error("\n\n" + traceback.format_exc()) log.error("=============================================") log.error("\n\n" + str(e) + "\n") log.error("=============================================") sys.exit(1)
def add(self, cb, url): self.queue.put(Job(cb, url)) self.progress_topic.notify(Example.ClipData(job.get_url(), '', Example.status.InProgress))
class TestExampleRoutes: def setup(self): self.graph = create_app(testing=True) self.client = self.graph.flask.test_client() recreate_all(self.graph) self.name1 = "name1" self.example1 = Example( id=new_object_id(), name=self.name1, ) def teardown(self): self.graph.postgres.dispose() def test_search(self): with SessionContext(self.graph), transaction(): self.example1.create() uri = "/api/v1/example" response = self.client.get(uri) assert_that(response.status_code, is_(equal_to(200))) data = loads(response.data) assert_that(data, has_entries( items=contains( has_entries( id=str(self.example1.id), name=self.example1.name, ), ), )) def test_create(self): uri = "/api/v1/example" with patch.object(self.graph.example_store, "new_object_id") as mocked: mocked.return_value = self.example1.id response = self.client.post(uri, data=dumps({ "name": self.example1.name, })) assert_that(response.status_code, is_(equal_to(201))) data = loads(response.data) assert_that(data, has_entries( id=str(self.example1.id), name=self.example1.name, )) def test_replace_with_new(self): uri = f"/api/v1/example/{self.example1.id}" response = self.client.put(uri, data=dumps({ "name": self.example1.name, })) assert_that(response.status_code, is_(equal_to(200))) data = loads(response.data) assert_that(data, has_entries( id=str(self.example1.id), name=self.example1.name, )) def test_retrieve(self): with SessionContext(self.graph), transaction(): self.example1.create() uri = f"/api/v1/example/{self.example1.id}" response = self.client.get(uri) data = loads(response.data) assert_that(data, has_entries( id=str(self.example1.id), name=self.example1.name, )) def test_delete(self): with SessionContext(self.graph), transaction(): self.example1.create() uri = f"/api/v1/example/{self.example1.id}" response = self.client.delete(uri) assert_that(response.status_code, is_(equal_to(204)))
async def create_new_examples(): async with transactional_session() as session: for i in range(1, 5): session.add(Example(name=f"Example #{i}")) session.commit()
# 这是一个示例 Python 脚本。 # 按 Shift+F10 执行或将其替换为您的代码。 # 按 双击 Shift 在所有地方搜索类、文件、工具窗口、操作和设置。 # def print_hi(name): # # 在下面的代码行中使用断点来调试脚本。 # print(f'Hi, {name}') # 按 Ctrl+F8 切换断点。 # # # # 按间距中的绿色按钮以运行脚本。 # if __name__ == '__main__': # print_hi('PyCharm') # 访问 https://www.jetbrains.com/help/pycharm/ 获取 PyCharm 帮助 import sys from PyQt5.QtWidgets import QApplication, QMainWindow import Example if __name__ == '__main__': app = QApplication(sys.argv) MainWindow = QMainWindow() ui = Example.Ui_Form() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
import Example a = Example.MyClass() a.bar = "Puppies" Example.consume(a) b = Example.eject() ## Should output "Puppies" print b.bar
def test_integration(): task = Example() success = luigi.build([task], scheduler_host='localhost') assert success
def test_example(): e = Example() assert e.get_value() == 10
def cancel(self): self.cb.ice_exception(Example.RequestCancelException())
import Example ex = Example("Cocoa Beach","Cocoa Beach") print "Instantiated class:", ex.getName() print "Static method: ", Example.printInfo()
#https://docs.python.org/3/py-modindex.html "Modules" #A file containing a set of functions you want to include in your application. #packages are collection of modules """We can define our most used functions in a module and import it, instead of copying their definitions into different programs.""" import Example #we want to create example.py module in local machine Example.add(4, 5) 'Or' from Example import add add(22, 2) import math #import statement access the definitions of it print("The value of pi is", math.pi) int(math.sqrt(9)) #renaming import math as m m.pi #We can import specific names from a module without importing the module as a whole. from math import pi math.pi #import all by *