Posts

Showing posts from September 19, 2018

How to set primary key auto increment in SqlAlchemy orm

Image
Clash Royale CLAN TAG #URR8PPP How to set primary key auto increment in SqlAlchemy orm I tired to use the SqlAlchemy orm to build the api to insert the values into database from uploaded excel files. when I tested on the codes it kept showing the error: TypeError: __init__() missing 1 required positional argument: 'id' I've updated the id key to primary key, auto increment, unique and unsigned in my local MySql data base. I believe the system cannot insert the primary key automatically because it works if I assign the value to id manually transaction_obj = Transaction(id=1, name="David", date="2018-03-03", product="fruit", quantity=20, amount=12.55) Here is model.py from sqlalchemy import Table, MetaData, Column, Integer, String, DATE, DECIMAL,ForeignKey, DateTime from sqlalchemy.orm import mapper metadata = MetaData() customers = Table('customers', metadata, Column('id', Integer, primary_key=True), Column('name',

Make selection using cypress in Angular if you're using material forms

Image
Clash Royale CLAN TAG #URR8PPP Make selection using cypress in Angular if you're using material forms I have a form that looks something like this: <form class="col s12" materialize [formGroup]="newUserForm"> ... <div class="row"> <div class="input-field col m4 s12"> <select formControlName="genderBound" materialize="material_select" id="gender" name="test"> <option value="" disabled selected name="chooseGender">Choose gender</option> <option *ngFor="let gender of genders">gender</option> </select> <label for="gender">Gender</label> </div> ... When I try to use cypress to select the dropdown menu, it tells me that it's not visible. When I follow the explanatory URL that cypress provides, it suggest that I use force: true inside my click. This allowed my test to pass, but never

++ in my function does not add right number

Image
Clash Royale CLAN TAG #URR8PPP ++ in my function does not add right number In this code i want to make the 3 div's count up by one when you scroll up and count down when you scroll down. For some reason the first time you scroll it doesnt do it for all the div's, and they don't add up properly. Can someone help? var Value = 1; function show() if (Value === null) Value = 1; document.getElementById("ValueCenter").innerHTML = Value; document.getElementById("ValueCenter").addEventListener('wheel', function (e) if (e.deltaY < 0) add(); if (e.deltaY > 0) decrease(); ); function showRest() document.getElementById("ValueUpper").innerHTML = Value - 1; document.getElementById("ValueDown").innerHTML = Value + 1; function add() document.getElementById("ValueCenter").innerHTML = Value++; document.getElementById("ValueUpper").innerHTML = Value++; document.getElementById("ValueDown").i

Spring Cloud Config - Multiple Composite Repositories?

Image
Clash Royale CLAN TAG #URR8PPP Spring Cloud Config - Multiple Composite Repositories? Is it possible configure Spring Cloud Config with multiple composite repositories? Our setup uses multiple team-based repositories: spring: cloud: config: server: git: repos: teamA: cloneOnStart: true pattern: teama-* searchPaths: 'profile' uri: file:///etc/config/teama teamB: cloneOnStart: true pattern: teamb-* searchPaths: 'profile' uri: file:///etc/config/teamb We want each team to now pull from 2 different git repositories. I think multiple Composite repositories (https://cloud.spring.io/spring-cloud-config/single/spring-cloud-config.html#composite-environment-repositories) is what we want, but I can't figure out how to combine them, or if it is even possible. Clarification: I want each team to put configuration data from two repos instead of just the 1. In pseudo code: spring: cloud: config: server: git: repos: teamA: repo1: key1: repo1 key2: repo

Selenium get_property is None?

Image
Clash Royale CLAN TAG #URR8PPP Selenium get_property is None? I can't seem to get any properties from any elements on any webpages and I don't know what I'm doing wrong. I've written this very basic test case to show what I mean: from selenium import webdriver URL = "https://stackoverflow.com/tour" Driver = webdriver.Firefox() Driver.get(URL) TheContent = Driver.find_element_by_id("content") print(TheContent.get_property("background-color")) This seems like the simplest of simple tests to me, but it still returns different results than expected. I know by using the Dev Tools that the StackOverflow tour page has a div with the id content and that its background color is #FFF (white). content Yet running the above script still prints out "None." I'm pretty sure it is printing out "None" because it is grabbing the wrong element, but I have no idea why. There is only one element with the id content ? content Can a

android: how to let js code to change the webview's size

Image
Clash Royale CLAN TAG #URR8PPP android: how to let js code to change the webview's size I'm developing an android application with API 19(android4.4).I have a linearLayout view nested another linearLayout view. Now I want change this linearLayout's height by js code, but it doesn't work. active_main.xml <LinearLayout xmlns="...." ... android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:id="@id/sContainer" tools:context=".MainActivity"> </LinearLayout> java test code: ... private LinearLayout webViewContainer; ... private void initView() LinearLayout container=(LinearLayout)findViewById(R.id.sContainer); //add a child linearLayout webViewContainer=new LinearLayout(this); LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,200); webViewContainer.setLayoutParams(layoutParams)

Will tf.global_variables_initializer() also initialize the iterator for tf.data.Dataset?

Image
Clash Royale CLAN TAG #URR8PPP Will tf.global_variables_initializer() also initialize the iterator for tf.data.Dataset? I was wondering whether tf.global_variables_initializer() also initializes the iterator for tf.data.Dataset , or I need to initialize the iterator separately as: tf.global_variables_initializer() iterator tf.data.Dataset iterator iterator = dataset.make_initializable_iterator() sess.run(iterator.initializer) iterator = dataset.make_initializable_iterator() sess.run(iterator.initializer) 1 Answer 1 You have to initialize the iterator separately. There is None variable feed to tf.global_variables_initializer() tf.global_variables_initializer() official example: max_value = tf.placeholder(tf.int64, shape=) dataset = tf.data.Dataset.range(max_value) iterator = dataset.make_initializable_iterator() next_element = iterator.get_next() # Initialize an iterator over a dataset with 10 elements. sess.run(iterator.initializer, feed_dict=max_value: 10) for i in range(

Cython: Why do NumPy arrays need to be type-cast to object?

Image
Clash Royale CLAN TAG #URR8PPP Cython: Why do NumPy arrays need to be type-cast to object? I have seen something like this a few times in the Pandas source: def nancorr(ndarray[float64_t, ndim=2] mat, bint cov=0, minp=None): # ... N, K = (<object> mat).shape This implies that a NumPy ndarray called mat is type-casted to a Python object. * ndarray mat Upon further inspection, it seems like this is used because a compile error arises if it isn't. My question is: why is this type-cast required in the first place ? Here are a few examples. This answer suggest simply that tuple packing doesn't work in Cython like it does in Python---but it doesn't seem to be a tuple unpacking issue. (It is a fine answer regardless, and I don't mean to pick on it.) Take the following script, shape.pyx . It will fail at compile time with "Cannot convert 'npy_intp *' to Python object." shape.pyx from cython cimport Py_ssize_t import numpy as np from numpy cimpo

VSCode: moving files out of appdata directory

Image
Clash Royale CLAN TAG #URR8PPP VSCode: moving files out of appdata directory I'm on a company laptop and appdata has restricted storage space. An initial google showed there isn't really any settings to move directories. I was thinking of simply copying relevant directories i.e. AppDataRoamingCode to somewhere else, then creating a hard symbolic link (junction) with the same name and then point it to the same location i.e. in command line: mklink /J C:UsersmeAppDataRoamingCode C:myFolderCode I played around with moving the whole appdata folder (right click on roaming/local/locallow then click on properties then location tab then change directory). I managed to only move half the files over. it seemed to work until i restarted and it caused chaos. I don't want the same thing to happen again with vscode. (that said I haven't tried using a symbolic link for appdata what is everyone's advice? can i create a symbolic link and have everything work fine? or will i ca

Computing sum of consecutive values in a vector that are greater than a constant number?

Image
Clash Royale CLAN TAG #URR8PPP Computing sum of consecutive values in a vector that are greater than a constant number? I couldn't summarize my question in the title very well. I'm writing a code and in one part of the code I need to compute the following: Let's say we have a vector (e.g. a numpy array): a = [3.2, 4, 7, 2, 8, 9, 7, 1.7, 2, 8, 9, 1, 3] We want to turn any number greater than 5 to 5: a = [3.2, 4, 5, 2, 5, 5, 5, 1.7, 2, 5, 5, 1, 3] Then we compute the sum of consecutive 5s and the number that follows them and replace all these elements with the resulting sum: a = [3.2, 4, 5+ 2, 5+ 5+ 5+ 1.7, 2, 5+ 5+ 1, 3] so the resulting array would be: a = [3.2, 4, 7, 16.7, 2, 11, 3] I can do this using a for loop like this: indx = np.where(a>5)[0] a[indx] = 5 counter = 0 c = while (counter < len(a)): elem = a[counter] if elem ~= 5: c.append(elem) else: temp = 0 while(elem==5): temp += elem counter +=1 elem = a[counter] temp += elem c.append(tem

How to catch exception for each record while reading CSV using Spark/Scala

Image
Clash Royale CLAN TAG #URR8PPP How to catch exception for each record while reading CSV using Spark/Scala I have a CSV (no headers) that looks like this: file_id, file_contents 1001, textString1 1002, textString2 1003, textString3 I am reading the file using Spark/Scala app like this: val df = spark.read .text(list: _*) .map r => val str = r.getAs[String]("value") val fileId == str.substring(0, str.indexOf(",")) val fileContents = val content = str.substring(0, str.indexOf(",")) if (content .startsWith(""")) content .substring(1, content .length - 1) else content (fileId, fileContents) .toDF("fileId", "fileContents") When i transform this dataframe, i am capturing exceptions and processing as usual. But the problem iam having is that, if there is atleast on bad record in the CSV, like the contents are malformed etc. the application is failing for the whole file. I want to change this feature and make sure

Schedule a message in Slack

Image
Clash Royale CLAN TAG #URR8PPP Schedule a message in Slack I need to send a message in slack at a time set in advance. Is there a way to do it through the Slack API or do I need to have a script running and checking if it's time to send the message and then send it? 2 Answers 2 If you just want to send a short message to a user at a given time you can use the build-in reminder. The reminder.add method allows you to specify a date, time, message text and the user to receive the message. The reminder message will appear in the "Slackbot" channel of the addressed user. Here is an example on how it would look like: I want to post messages to a channel, they are not repeating, basically saying that a scheduled event is starting and/or ending now without any other triggers besides the time. Would be nice to have some formatting on them as well. Is the reminder still good for that? – LLL Jan 31 '17 at 11:24 yes, the reminder works for non repeating messag

CommunicationException in client-service integration test

Image
Clash Royale CLAN TAG #URR8PPP CommunicationException in client-service integration test I'm making an integration tests for my WCF service, in which my test client is making requests to self hosted service. My WCF service setup: var binding = new BasicHttpBinding Security = Mode = BasicHttpSecurityMode.Transport; var endpointAddress = new EndpointAddress("https://localhost:44398/MyService.svc"); var host = new ServiceHost(typeof(MyService), endpointAddress.Uri); host.AddServiceEndpoint(typeof(WcfServices.Contracts.IMyService), binding, endpointAddress.Uri); host.Open(); And my client call: var client = new MyServiceClient(binding, endpointAddress); // Act Contract.MyResult result; try result = actMethod.Invoke(sut); finally client.Close(); if (host.State == CommunicationState.Opened) host.Close(); else host.Abort(); Before executing tests, I run this PowerShell script: $whoami = WHOAMI netsh http add urlacl url=https://+:44398/MyService.svc/ user=$whoami Ever

Why can't I trigger input file through prop?

Image
Clash Royale CLAN TAG #URR8PPP Why can't I trigger input file through prop? I'm trying to open a selection of files, but through passing prop to component (I need this for convenience). Is there a way to do this? https://codepen.io/iliyazelenko/pen/RBejRV?editors=1010 Variant in code below does not suit me: <input type="file" ref="input" hidden> <button @click="() => $refs.input.click() ">Choose file</button> Why does it click but does not open file selection? this.$refs.input.addEventListener('click', e => console.log('clicked: ', e.target) ) Would you like to show us how you code? – Xiaofeng Zheng Aug 8 at 2:01 codepen.io/iliyazelenko/pen/RBejRV?editors=1010 – Илья Зеленько Aug 8 at 2:03 See stackoverflow.com/a/21583865/38065 – Bert Aug 8 at 2:15 @Bert Many thanks! – Илья Зеленько Aug 8 at 15:57 1 Answer 1 It will not work if it's not triggered from inside the cl

VBA/excel extract multiple strings between symbols in cell

Image
Clash Royale CLAN TAG #URR8PPP VBA/excel extract multiple strings between symbols in cell I have a spreadsheet with multiple cells with a bunch of text in them. Within the text are a few words/sentences between @ symbols. There are multiple of these strings in each cell. So for example: Lorem ipsum dolor sit amet, @consectetur adipiscing elit@ . Curabitur sapien nibh, faucibus ut odio ut, vehicula elementum nunc. @Fusce consequat risus vel dui tincidunt@ condimentum. I need a solution to extract the @...@ strings, let's say into the adjacent column. Edit to respond to comments: No solution could be attempt fully yet before making this post as I didn't know how to start - the main challenge seems to be around multiple @...@ strings in the text. Other solutions I researched did not seem to work with multiple delimiters: excel vba- extract text between 2 characters Any solutions are appreciated. Thanks You could go Data > Text To Columns and split it into separa

optimize laravel eloquent built-in functions

Image
Clash Royale CLAN TAG #URR8PPP optimize laravel eloquent built-in functions I am optimizing a existing laravel project which has following code segment. this method is calling from another foreach. but this method gets almost 3 seconds to process a single round.is there anything that i can do to optimize following code. public function getFavouriteForRace($raceId) $race = $this->raceRepository->find($raceId); $selections = $this->selectionRepository->getSelectionsForRace($raceId); //set product $products = new EloquentResourceCollection($race->products, 'ResourcesProductResource'); $selections = $selections->map(function ($v) use ($products) $v->setProducts($products); return $v; ); $selections = $selections ->filter(function ($v) return $v->selectionStatus == SelectionStatusRepositoryInterface::SELECTION_STATUS; ) ->sortBy(function ($v) use ($race) return $v->getBetTypePrice(BetTypeRepositoryInterface::TYPE_WIN, (bool)$race->