input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Issue with scanf() in C <p>I am learning by myself how to code using the C languange. In order to study this latter a bit more in depth, I'm doing some basic exercises and, due to this, today I have faced a little issue using the <code>scanf()</code> instruction. Infact, the following code:</p>
<pre><code>int main() {... | <p>It takes <code>line feed</code> as input to the second character. You can take the <code>inputTwo</code> again to prevent it:</p>
<pre><code>int main() {
char inputOne;
char inputTwo;
printf("Insert a char: ");
scanf("%c", &inputOne);
// &inputOne is the pointer to inputOne.
printf("Insert an... |
Subnetting, how do you find the Ip range , and subnetMask ? <p>If you have Subnet A with a network address of 172.25.100.0 and you need 1100 hosts . You also have Subnet B with a network address of 192.168.105.0 and you need 70 , find the subnet masks, and IP rage for both networks. </p>
<p>I donât know how do this ... | <p>I'll add an explanation which isn't in bits. For Subnet A you need 1100 hosts, a /24 provides 255 addresses. A /23 provides 512 addresses. A /22 provides 1024 addresses. So we will need a /21 which provides 2048 addresses (2046 usable).</p>
<p>For Subnet B we need 70 hosts. Again, a /24 provides 255 addresses, a /2... |
How many ways we can access user's location iOS? <p>I know we can access user's location using geolocation in iOS. I want to know what other ways we can access user's location off course with his permission. I also heard we can access user's location using network/Internet etc.</p>
| <p>All geolocation of the device is done via the CoreLocation framework. The specifics of what method(s) used to determine the location is not provided through the framework. The position can be determined via WiFi proximity to a known AP, cellular proximity to a tower mapped by the carrier, or most accurately via th... |
Java TCP - server & client working, but can't get answer <p>I'm trying to make a small TCP server/client thingy. I have a client and a server, and after getting some basic Exceptions solved, nothing works.
The client is supposed to send (user) data to the server (at port 6789, localhost), who is then supposed to write ... | <p>The answer is:
I'm stupid.</p>
<p>I accidentally let both the client and the server run on the same thread. I now made <code>TCPClient</code> a <code>Runnable</code> and everything works as planned.</p>
<p>NOTE:
the <code>TCPClient.main(null)</code> does not start a new program/thread, just the same thread, anothe... |
How to bind opaque types with Ctypes <p>I'm writing an OCaml binding for Quartz Event Services[1].</p>
<p>There are cases where I need to bind opaque types like in this code:</p>
<pre><code>typedef CGEventRef _Nullable (*CGEventTapCallBack)(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *userInfo);
... | <p>For now I'm treating pointers on opaque types as void pointers.</p>
<pre><code>type machport_ref = unit ptr
let machport_ref = ptr void
type event_ref = unit ptr
let event_ref = ptr void
</code></pre>
|
Akka actor is processing the second message before processing the first message <p>I am learning and understanding Akka actor model with some basic examples.</p>
<p>I created two instances for a same Actor (i.e) "helloworld1" and "helloworld2" and sending messages to that Actor. The first message is sent by instance "... | <p>Akka does not guarantee that messages are delivered in the order they are sent globally. It guarantees the following:</p>
<ul>
<li>at-most-once delivery (i.e. no guaranteed delivery, messages may be dropped)</li>
<li>message ordering per senderâreceiver pair</li>
</ul>
<p>So you see, the ordering is only guarant... |
Searchbar doesn't work properly in iOS <p>Currently I am making a search functionality in my project but it isn't working properly. Currently when I typ something in the UISearchbar it does change from search results but its not showing the correct search results. Is this because of the white space between the words in... | <p>The problem is that you are saying:</p>
<pre><code>let lower = searchBar.text!.lowercased()
</code></pre>
<p>But the <code>exercises</code> elements are all titlecased:</p>
<pre><code>let exercise1 = exercise(exerciseName: "Incline Bench Press")
let exercise2 = exercise(exerciseName: "Decline Bench Press")
let ex... |
ARRAY(0x7ff4bbb0c7b8) error: perl hash of arrays <p>Although my code runs without throwing a fatal error, the output is clearly erroneous. I first create a hash of arrays. Then I search sequences in a file against the keys in the hash. If the sequence exists as a key in the hash, I print the key and the associated valu... | <p>In this line:</p>
<pre><code>print $out ">$sequence\n$hash{$sequence}\n";
</code></pre>
<p>...<code>$hash{$sequence}</code> is a reference to an array. You have to dereference the referenced array before printing it. Here's an example of printing <code>$sequence</code>, then printing the elements of the <code>$... |
How to load a UIViewController inside an UIScrollView <p>This is my setup. I have an <code>UIScrollView</code> on top of my main view controller in which I load multiple view controllers. I also have an Add button which will present a new view controller using a Push segue. </p>
<p>I want this view controller to also... | <p>You cannot push any view controller on the same view controller, you need to add container view to your scroll view. And then if you want you may scroll the scroll on tap of the add button, so that it will seem like new controller is being added to it. It can be done like this,</p>
<pre><code>scrollView.contentSize... |
Is it safe and pythonic to consume the iterator in the body of a for loop? <p>Is it safe in Python to do something like this (say, in a parser)?</p>
<pre><code>iterator = iter(some_iterable)
for x in iterator:
# do stuff with x
if some_condition(x):
y = next(iterator)
# do stuff with y
</code><... | <p>Basically it's always better to keep track of your exceptions and handle them properly. But regarding the difference between the <code>while</code> and <code>for</code> loops in this case when you are calling a <code>next()</code> function within a <code>while</code> loop it's always possible to raise an StopIterati... |
Angular 2 router - aux route on the root url <p>I want to load aux route on the / URL but it does not work. For example, I want to load in my homepage the LoginComponent.</p>
<pre><code>const routes : Routes = [
{
path: '',
pathMatch: 'full',
component: HomeComponent
},
{
path: 'login',
outle... | <p>You need to define redirect route:</p>
<pre><code>const routes : Routes = [
{
path: '',
redirectTo: 'home',
pathMatch: 'full'
},
{
path: 'home',
component: HomeComponent
},
{
path: 'login',
outlet: 'auth',
component: LoginComponent
}
];
<a [routerLink]="[{ outlets: { ... |
Adding an element to a singly linked list in Java <p>I'm implementing a singly linked list in Java. What I don't like about this code is that I need to check <code>if (head.next == null)</code> every time I add an element. But the condition is met only once, when adding the first element.</p>
<p>Is there a way to impl... | <p>There are many cases where "good OO design" allows you to go without <strong>if/else</strong> checks; most often by using some form of polymorphism. </p>
<p>Meaning: instead of asking some object about some property, to then make a decision on that in your client code, you somehow make sure that your client code ca... |
I just started learning sql and I cant find the answer for the below as given in assignment, working on the same since 2 days. lol <pre><code>EMP - TABLE NAME
1.FNAME LNAME DEPTNO
2.MIKE JOHN 1
3.MIKE JORDAN 2
4.NICKY MINAJ 3
5.JAMES PATEL 4
6.MARTIN LUTHER 5
7.MIKE KING 2
</code></pre>
... | <pre><code>select e.fname, e.lname
from emp e
,(select DEPTNO, fname
from emp
where fname = 'MIKE'
group by DEPTNO, fname
having count(*) >=2) e2
where e.DEPTNO = e2.DEPTNO
</code></pre>
|
C dynamic allocation malloc struc <p>I'm going through the practicals for my operating systems course and I can't get my head around this example. I've run the program and it does not work. </p>
<pre><code>#include <stdio.h>
typedef struct {
int age;
float height;}Person;
void init(Person *);
int main() {
Per... | <p>In your code,</p>
<pre><code> void init(Callum * individual)
</code></pre>
<p>is wrong. You need to write</p>
<pre><code> void init(Person * individual)
</code></pre>
<p>as <code>Person</code> is the data type. Also, the function should be enclosed in braces, same as <code>main()</code>.</p>
<p>Also, in your ... |
Make Array From Temporary Arrays <p>I have a file in where rows of random integers are divided by "::".</p>
<p>For example "1 2 3::4 5:: 6 7 8 9::10 11 12::13" </p>
<p>What I want to make is an array where the rows are combined as follows: take the second row and place at the back of the first row, then take the thi... | <pre><code>public static void main(String args[]) throws IOException
{
Scanner in = new Scanner(System.in);
PrintWriter w = new PrintWriter(System.out);
String inp = in.nextLine();
String s[] = inp.split("::");
StringBuilder ans = new StringBuilder();
for(int i = 0; i < s.length; i++){
... |
Build large scipy sparse matrix <p>One of the best ways to build a scipy sparse matrix is with the coo_matrix method ie.</p>
<pre><code>coo_matrix((data, (i, j)), [shape=(M, N)])
where:
data[:] are the entries of the matrix, in any order
i[:] are the row indices of the matrix entries
j[:] are the column indices of th... | <p>I don't quite understand. If the <code>i, j, data</code> arrays are too large to create or load into memory, then they are too large to create the sparse matrix.</p>
<p>If those three arrays are valid, the resulting sparse matrix will use them, without coping or alteration, as the corresponding attributes. A <cod... |
How to concatenate multiple values in sql <p>Hello folks I have a question regarding the concatenation of multiple values which are coming into the single column separated with comma like below.</p>
<p>For example There is a report which is fetching data but for one column there are 5 values so due to that 5 times the... | <p>MySQL's string aggregation function is <code>GROUP_CONCAT</code>.</p>
<p>You are using a join syntax that was used in the 1980's. Why? Where and when did you learn that? Use proper ANSI joins instead:</p>
<pre><code>SELECT GROUP_CONCAT(DISTINCT pac.packaged_item_gid) AS packaged_item_gids
FROM shipment sh
JOIN ord... |
python multiprocessing, cpu-s and cpu cores <p>I was trying out <code>python3</code> <code>multiprocessing</code> on a machine that has 8 cpu-s and each cpu has four cores (information is from <code>/proc/cpuinfo</code>). I wrote a little script with a useless function and I use <code>time</code> to see how long it tak... | <p>Simplified and short.. Cpu-s and cores are hardware that your computer have. On this hardware there is a operating system, the middleman between hardware and the programs running on the computer. The programs running on the computer are allotted cpu time. One of these programs is the python interpetar, which runs al... |
Virtualenv package installation without pip <p>How should i install a package inside a venv using <code>sudo apt-get install</code>? If i use <code>sudo</code> then the package will be installed globally and not only inside the venv, if i don't use <code>sudo</code> i will have no permission to install it because i am ... | <p><code>Virtualenv</code> is meant to create localized python environments. Thus, it can only control python software packages via <code>pip</code> (or <code>setuptools</code>, etc). <code>Apt</code> installs software for the entire system and is separate from <code>virtualenv</code>.</p>
<p>If you are looking to ins... |
how to recognize .delete in editingStyle in swift 3 to delete cell in tableview <p>this all my func that connected to my table view. I dont know why I cant delete row.</p>
<p>i also do in viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
self.myTableView.dataSource = self
self.m... | <p>First make sure your table has a delegate set, and that your delegate method is in the delegate class/controller.</p>
<p>Second, try to use <code>canEditRowAtIndexPath</code> method and return true.</p>
|
Change Back color of Windows Form using Another Form Application <p>I have 2 windows form applications.</p>
<p>From Main application, on button clicked, I want to change form color of target application.</p>
| <p>You must pass Form1 to the second form, then on the second form you can do something like this</p>
<pre><code>Form1.BackColor = Color.Green;
</code></pre>
<p>Did not check if that is the correct syntax as i answered this on my phone.</p>
|
Angular 2 Testing Component Gives "Error: Uncaught (in promise): Error: Template parse errors" <p>I've recently made an ng2 (using 2.0.1) app with multiple components and services. I'm in the middle of testing (Karma Jasmine) my <strong>HeaderComponent</strong> which contains my <strong>UserService</strong> (Which uses... | <p>Since you are unit testing the Header component in this case, there is no need to include other modules and components</p>
<p>TestBed can look like this: </p>
<pre><code>beforeEach(() => {
TestBed.configureTestingModule({
imports: [
AppModule
],
providers: [
... |
Response JSON Request <p>I am trying to use JSON .NET with a WebRequest, to retrieve JSON using "GET". Essentially, I am stuck on the parsing part and grabbing the item to test. The WebResponse, how would I go about retrieving the JSON file using the webResponse? The API.php is a way for me to connect to a website data... | <p>JSON is actually a string, representing serialized objects.</p>
<p><code>ToString</code> returns a string representation of an object -- probably something like <code>System.Web.HttpResponse</code>.</p>
<p>What you need is the text of the response, and that you can get via the <a href="https://msdn.microsoft.com/e... |
How to plot a one column data frame with ggplot? <p>I have a data frame like this:</p>
<pre><code> __________
| | sums |
|---+------|
| a | 122 |
|---+------|
| b | 23 |
|---+------|
| c | 321 |
|__________|
</code></pre>
<p>*Notice "a","b" and "c" are row names.</p>
<p>I would like to see a plot like this:</p... | <p>Add the rownames as a column in the data frame and then plot. Here's an example with the built-in <code>mtcars</code> data frame:</p>
<pre><code>library(tibble)
library(ggplot2)
ggplot(rownames_to_column(mtcars[1:3,], var="Model"),
aes(x=Model, y=mpg)) +
geom_bar(stat="identity") +
theme(axis.text.x=el... |
Pasting HTML or Markdown lists preserving indentation <p>I need a way to paste Markdown or Google Docs content that is in a list and have the content come out as indented text.</p>
<p>I don't care whether it's an ordered list or unordered list, and I don't care if I'm pasting it into plain text or a spreadsheet. I do... | <p>The problem is with HTML. HTML does not include any text formatting, it is plain text which has been styled with CSS. Even if you did not write the CSS for the list yourself, it is still styled with CSS using the default CSS properties for the element.</p>
<p>Styling and formatting are completely different, when yo... |
Dynamic WebGL Draw in Game Loop <p>I am fairly new to WebGL and I am working on a 3D game that dynamically generates land around the player. So, I am trying to add vertices to draw in game. Things worked fine, until I started to add this feature, making hundreds of <code>gl.drawArrays()</code> calls per frame, which ma... | <p>I know what I did. I made the vertex position array longer than my vertex color array, so it was trying to access something out of bounds. The fix is to keep the vertex color array the same length as the vertex position array.</p>
|
moment.js format date as iso 8601 without dashes? <p>How do I format a date as iso 8601 using moment.js but without the dashes and colons and setting the time to 0 e.g. if I have a date like this:</p>
<pre><code>2016-10-08T09:00:00Z
</code></pre>
<p>How do I format as :</p>
<pre><code>20161008T000000Z
</code></pre>
... | <p>You can simply parse your input into a moment object and use <a href="http://momentjs.com/docs/#/manipulating/start-of/" rel="nofollow"><code>startOf</code></a> to set time to <code>00:00:00</code>. Then you can use <a href="http://momentjs.com/docs/#/displaying/format/" rel="nofollow"><code>format</code></a> method... |
Two child classes that only differ in a static const member <p>I have a class <code>A</code> and two children <code>B</code> and <code>C</code> as follows:</p>
<pre><code>class A {
private:
int x;
template<class T>
void setX(T &y);
public:
A();
};
class B : public A {
private:
... | <p>You can write a constructor for <code>A</code> as a function template.</p>
<pre><code>class A {
//....
public:
template<typename T>
explicit A(T& y) {
setX(y);
}
};
</code></pre>
<p>And call that constructor from child classes:</p>
<pre><code>class B : public A{
//...
public... |
Different Ways of Creating Class Method in Ruby <p>Example 1:</p>
<pre><code>class Dog
def self.class_method
:another_way_to_write_class_methods
end
end
def test_you_can_use_self_instead_of_an_explicit_reference_to_dog
assert_equal :another_way_to_write_class_methods, Dog.class_method
end
</code></pre>
<p>... | <p><a href="https://github.com/bbatsov/ruby-style-guide" rel="nofollow">this ruby style guide</a> says the <code>class << self</code> syntax is "possible and convenient when you have to define many class methods."</p>
<p>They have code examples using both versions, so there's definitely not a broad community co... |
Identity Value returned as 0 using SCOPE_IDENTITY() <p>I have a contact info form in Visual Studio (using C#) that can be used to turn the contact into a customer, to do so I want to send the id from the contact that was just created to the other form and to do this I created a stored procedure that returns the id usin... | <p>You need to define the <code>@id</code> parameter as an <strong>output</strong> parameter in your C# code:</p>
<pre><code>SqlParameter idParam = cons.Parameters.Add("@id", SqlDbType.Int);
idParam.Direction = ParameterDirection.Output;
</code></pre>
<p>and after executing your query, you need to <strong>read out</s... |
How to convert string to JSON? <p>How to convert the following string into Json which contains some special characters? I want some specific notification URL and values for verification.</p>
<pre><code>colombiaadCallback("[{\"snippet\":\"\",\"adSlot\":\"208039\",\"section\":\"0\",\"position\":\"1\",\"ip\":\"223.165.29... | <p>Try use JSON.parse();</p>
<pre><code>var newJson = JSON.parse(myString);
</code></pre>
<p>In your case I set a variable with your sample code and everything is working fine:</p>
<pre><code>[Object, Object, Object, Object]
0:Object
adSlot:"208039"
cs:Array[2]0:Object
c:"http://ads.yahoo.com/cms/v1?esig=2~0e... |
Apply holiday labels to plot by week of year <p>I have some holiday dates, and a bunch of data by week of year. I'm plotting the data and want to make the X axis labels only show up when there is a holiday from my holidays table. The rest of the labels should be hidden. I think what I need is a list where the names ... | <ul>
<li>Use <code>scale_x_continuous</code> rather than <code>scale_x_discrete</code></li>
<li>Set both <code>labels</code> and <code>breaks</code>, with the corresponding text labels and the dates where you want them. In particular, for breaks use <code>week(as.Date(holiday_dates))</code> to put it on the same scale ... |
Seaborn boxplot: TypeError: unsupported operand type(s) for /: 'str' and 'int' <p>I try to make vertical seaborn boxplot like this</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'a' : ['a', 'b' , 'b', 'a'], 'b' : [5, 6, 4, 3] })
import seaborn as sns
import matplotlib.pylab as plt
%matplotlib inline
sns.boxplot... | <p>For seaborn's boxplots it is important to keep an eye on the x-axis and y-axis assignments, when switching between horizontal and vertical alignment:</p>
<pre><code>%matplotlib inline
import pandas as pd
import seaborn as sns
df = pd.DataFrame({'a' : ['a', 'b' , 'b', 'a'], 'b' : [5, 6, 4, 3] })
# horizontal boxpl... |
What's the most efficient way to find factors in a list? <h2>What I'm looking to do:</h2>
<p>I need to make a function that, given a list of positive integers (there can be duplicate integers), counts all triples (in the list) in which the third number is a multiple of the second and the second is a multiple of the fi... | <p>Right now your algorithm has O(N^3) running time, meaning that every time you double the length of the initial list the running time goes up by 8 times.</p>
<p>In the worst case, you cannot improve this. For example, if your numbers are all successive powers of 2, meaning that every number divides every number grat... |
Android POST request not working <p>I am doing this:</p>
<pre><code>@Override
protected Void doInBackground(String... strings) {
try {
String query = "username=" + strings[0] + "&duration=" + strings[1] + "&distance=" + strings[2];
URL url = new URL(ScoresActivity.URL);
HttpURLConn... | <p>hey try to use this syntax.</p>
<pre><code>@Override
protected String doInBackground(String... params) {
String urlString = params[0];
String userName = params[1];
String password = params[2];
URL url = null;
InputStream stream = null;
... |
SWIFT: Why is the visibility of most selectors not made private/fileprivate? <p>In many code examples I observe that selectors are mostly <code>internal</code>. Here is an example of what I mean:</p>
<pre><code>override func viewDidLoad()
{
button.addTarget( self, action: #selector( self.buttonWasPressed ), for: .... | <p>The method that the selector points to is called from code that is not inside the scope of the class being defined, and called from code that is not defined in that file. Therefore making the method <code>fileprivate</code> or <code>private</code> is inappropriate IMHO. </p>
<p>By marking the method with either acc... |
How To Create Reusable Window Template/Model - WPF <p>Ok, I'll try to explain what I want to accomplish:</p>
<p>I'm quite new to WPF and XAML and I would like to create some domestic use applications with <strong>custom reusable UI</strong>. To be clear, I would like that every <code>Window</code> uses the same "Appea... | <p>If you want to make custom UI in XAML you should learn to use Expression Blend. Here is a resource you can try - </p>
<ul>
<li><a href="http://www.blendrocks.com/code-blend/2015/2/11/inspirational-textbox-styles-for-windows-phone-and-store" rel="nofollow">Inspirational Textbox Styles (Source code available)</a></li... |
biggest convex hull in A not containing points in B <p>I have two sets of points, A and B. I'm looking for the subset of A whose convex hull contains at most n points from B and</p>
<ul>
<li>contains the most points from A, or</li>
<li>has the largest volume.</li>
</ul>
<p>Either would be OK. </p>
<p>Is there an eff... | <p>Not sure how to crack this one. But I'd start with a Delaunay triangulation of A and count the points inside each triangle. Now we want to maximise either area (2D right, volume was a slip?) or point count, over a convex subset.</p>
<p>Now each triangle is convex. We mark any with more than n points as "bad", howev... |
Creating a data frame with the contents of multiple txt files <p>I'm new to R programming and am having difficulties trying to create one data frame from a number of text files. I have a directory containing over 100 text files. Each of the files have a different file name but the contents are of a similar format e.g. ... | <p>I think you might want something like this:</p>
<pre><code># Put in your actual path where the text files are saved
mypath = "C:/Users/Dave/Desktop"
setwd(mypath)
# Create list of text files
txt_files_ls = list.files(path=mypath, pattern="*.txt")
# Read the files in, assuming comma separator
txt_files_df <- la... |
Java: Use recursion to check if an array is ordered <p>I am trying to learn about recursion. I want to check if an array is ordered using recursion, but there is something that is wrong with my code because when index reaches the value 2, the next step should be to reach the base case but it doesn't. Here is my code, w... | <p>You are calling <code>isArrayInSortedOrder(array, index - 1)</code>, but ignoring it's return value. Consider the following:</p>
<pre><code>public static boolean isArrayInSortedOrder (int[] array, int index) {
if (array.length == 1 || index == 1) { //base case
return true;
}
int a1 = array[inde... |
Ajax Calls not Accessing Server Side <p>I am confused why my Ajax call is not working. Currently, I just need my Ajax method from Client to access my Controller Method. <strong>The alert command is POPING</strong> on my HTML But server side is not accessed from Client. Please advise what am I missing in following:</p>
... | <p>You are calling ActionResult, you need to call JsonResult that's why is not working, see an example bellow:</p>
<pre><code> $.ajax({
url: '/Product/List',
type: "GET",
data: { "nrRecs": 4 },
async: true,
dataType: "json",
... |
Decimal numbers in R stargazer <p>I am using the R package stargazer to generate tables in Latex. It works great but I cannot figure out how to format my numbers correctly. I want all numbers to show exactly one decimal place (e. g. 1.0, 0.1, 10.5 etc.). I therefore use the option digits = 1. However, for exact numbers... | <p>You can use regex to add the decimal places back after using stargazer. Here is an example. You may need to change the regex string slightly, depending on the type of summary you are generating with stargazer, but since no minimal example is included in the question, the best I can do is give a generic example of th... |
How to input heroku credentials in Travis Ruby on Rails <p>Am working Ruby on Rails site, and I have implemented Travis CI with it and pushed to to GitHub, so as to Test my build before pushing to Heroku. </p>
<p>When Travis parsed my github source code, I get an error asking me to input my <code>Heroku Credentials</c... | <p>You don't need to manually push to heroku on <code>after_success</code>. Just having the <code>deploy</code> with your encrypted credentials is enough to automatically deploy after the build. So try removing the <code>after_success</code> commands and everything should work.</p>
<p>For more information, check <a hr... |
I get a swift "run before self" error <p>I am getting a "cannot use instance member 'appearance' within property initializer; property initializers run before 'self' is available". Please do not suggest to remove appearance from the code, that will not work. I also added a self.appearence.kcirclebackround and got and e... | <p>As the error mentions, you are not able to use your <code>appearance</code> property until it has been set in the initializer. Your properties are evaluated before the initializer runs, so your only option here is to move the desired customisation of your <code>circleBG</code> view into the initializer, for example ... |
How do I secure a public API that requires no authentication? <p>I made a web api that does that follow services:</p>
<ol>
<li>Returns the list of current job openings of the company (GET)</li>
<li>Apply on any job that is currently opened (POST).</li>
</ol>
<p>The API is then consumed by an angularJS front end. Most... | <p>You can probably add a ClientId/ClientSecret to your SPA and somehow securely send it as part of every request probably a AngularJs interceptor will help.</p>
<p>On the webAPI side accept only those requests that have a valid clientId, do that probably using a filter. </p>
<p>A similar infrastructure is explained ... |
std::get_deleter on std::shared_ptr initialized with std::bind <p>Let's say I have this code:</p>
<pre><code>class BaseObject
{
public:
virtual void OnDestroy() {}
};
template <typename T>
struct myArrayDeleter
{
void operator()(T *p, std::size_t count)
{
for(std::size_t i = 0; i < count; ... | <p>It turned out that compiler wasn't translating decltype correctly. I tried to get deleter immediately after initializing shared_ptr and it worked. However the same decltype in function was generating slightly other type. I checked it in debugger and it generated this results:</p>
<p>In constructor:</p>
<pre><code>... |
Can we merge rankings from somewhat-similar data sets to produce a global rank? <p>Another way of asking this is: can we use relative rankings from separate data sets to produce a global rank?</p>
<p>Say I have a variety of data sets with their own rankings based upon the criteria of cuteness for baby animals: 1) Kitt... | <p>You can achieve your task using a <strong>rating system</strong>, like most known <em>Elo</em>, <em>Glicko</em>, or our <em>rankade</em>. A rating system allows to build a ranking starting from pairwise comparisons, and</p>
<ul>
<li>you don't need to do all comparisons, neither have all animals be involved in the s... |
How to resize a children shape from a pshape in Processing <p>I am currently building an app using Processing.
I have a shape in which I was able to select its sub elements and manipulate its color and stroke... but I am not being able to resize every single element of the file.
Basically, what I want is to resize the... | <p>You can use the <code>PShape#scale()</code> function to scale individual <code>PShape</code> instances.</p>
<p>From <a href="https://processing.org/reference/PShape_scale_.html" rel="nofollow">the reference</a>:</p>
<blockquote>
<pre><code>PShape s;
void setup() {
s = loadShape("bot.svg");
}
void draw() {
ba... |
Replace a complex if else statement <p>I am looking for a clean and effective way of accomplishing this (See picture). I want to stack different buttons side by side depending on if they are visible or not. I started out by using if else statements but this way of doing it got fast very complicated and ineffective.</p>... | <p>You could set up a switch case:</p>
<pre><code>switch (caseDecider)
{
//ON/OFF
case 1:
//set UI elements to apropriate states here
break;
//ON/CLOSE//OFF
case 2:
//set UI elements to apropriate states here
... |
Pandas plot without specifying index <p>Given the data:</p>
<pre><code>Column1; Column2; Column3
1; 4; 6
2; 2; 6
3; 3; 8
4; 1; 1
5; 4; 2
</code></pre>
<p>I can plot it via:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('test0.csv',delimiter='; ', engine='python')
titles = list(... | <p>I am not sure what you are trying to achieve but you could reset index and set it as you would like:</p>
<pre><code>In[11]: df
Out[11]:
Column1 Column2 Column3
0 1 4 6
1 2 2 6
2 3 3 8
3 4 1 1
4 5 4 ... |
Spring Boot, RestTemplate exception during upload file from InputStream via POST <p>I am writing with my friends app, which collects JobOffer and can manually apply on them.</p>
<p>For example, I am getting CSRF token from this page <a href="http://www.stackoverflow.com/jobs/apply/110247">Click</a> cause I need CSRF t... | <p>it's obviously some problem with casting, you're trying to cast FileMessageResource to String. It's not necessarily happening explicitly. Can you add the stack trace?</p>
|
Word Reading CustomXmlParts gets stuck intermittently <p>Env: Mac Office 2016 build 15.26</p>
<p>I'm reading the Word documents' CustomXmlParts after Office.initialize is finished. I'm using the Office.context.document.customXmlParts.getByNamespaceAsync API. The getByNamespaceAsync gets stuck intermittently. As soon a... | <p>Thanks for reporting this issue. I haven't been able to reproduce it internally. Some questions:</p>
<ul>
<li>When you say that you run this code "after Office.initialize is finished", do you mean that it is inside your Office.initialize callback code (and also inside $(document).ready, so that it executes after th... |
A confusing GeneratorType implementation with while loop & let keyword <p>I am confused trying to understand why do we use <code>let</code> keyword when we implementing Fibonacci generator.</p>
<pre><code>struct FibonacciGenerator: GeneratorType {
typealias Element = Int
var values = (0, 1)
mutating func next() ->... | <p><code>let</code> should be used when defining a constant, meaning the value may not be changed afterwards, which is the case here.
If you were to modify <code>next</code> at any point, it would have to be declared as variable using the <code>var</code> keyword.</p>
|
Database changes versioning: update sqlproj project by latest database schema changes using command line <p>my problem is that I can't find the way how to update sqlproj from command line. According to <a href="https://blogs.msdn.microsoft.com/ssdt/2014/07/15/msbuild-support-for-schema-compare-is-available/" rel="nofol... | <p>There is no command-line support for automating updates to a database project from a database. That's primarily because the workflow that SSDT is intended to enable is offline database development: the expectation is that changes are made to the database project first and are then published to the database.</p>
|
Isolating pandas columns using boolean logic in python <p>I am trying to grab the rows of a data frame that satisfy one or both of the following boolean statements:</p>
<pre><code>1) df['colName'] == 0
2) df['colName'] == 1
</code></pre>
<p>I've tried these, but neither one works (throws errors):</p>
<pre><code>df =... | <p>you are missing <code>()</code></p>
<pre><code>df = df[(df['colName']==0) | (df['colName']==1)]
</code></pre>
<p>this will probably raise a copy warning but will still works.</p>
<p>if you don't want the copy warning, use an indexer such has:</p>
<pre><code>indexer = df[(df['colName']==0) | (df['colName']==1)].i... |
Best way to seed content text in rails 4 <p>I know how to create a standard seed file in rails and seed my database. However, I have a wysiwyg editor that I used to create many pages of content. The content field is a "text" type and contains a full page of HTML. I will be exporting this data out and want to create ... | <p>You can have a file containing the content and then just reading it and seeding your db:</p>
<pre><code>file_content = File.read('path to file with extension');
MyModel.create(text: file_content);
</code></pre>
<p>And of course, if you have multiple items you need to seed, just loop over them with the right file n... |
Sending Form via AJAX in plain javascript (no jQuery) <p>I have the following Form which I would like to send via an AJAX request. I am unsure how to proceed in the line 'xmlhttp.open'. I am trying to upload a video file to a third party video hosting site (using their API)and they have provided me with a URL ('uploa... | <p>First of all your <code>action</code> attribute not correct, change to some endpoint like <code>/upload</code> for example.</p>
<p>Here is simple example without server side.</p>
<p>html</p>
<pre><code><form id="upload-form" action="/upload" method="POST" enctype="multipart/form-data">
<input type="fil... |
react native dynamic list view Taylor Swift <p>I am trying to render a JSON of all my favorite Taylor Swift Albums. I thought it would be wise to use the list view instead of maping over the JSON. </p>
<p>I am having a difficult time trying to get my listview to render properly. As of now, I am getting an error "undef... | <p>In your code you're trying to render from <code>this.state.dataSource</code>, however that property of your state is not defined in the constructor. Perform this changes to your code:</p>
<pre><code>import React,{Component} from 'react';
import { Text, View,StyleSheet,Image,TextInput,ListView} from 'react-native';
... |
Javascript Map function does not preserve the original object <p>I have a scenario wherein i have</p>
<pre><code>var data = [
{
"x": 1,
"y": 0.27,
"classifier": 1
},
{
"x": 2,
"y": 0.88,
"classifier": 1
}
]
</code></pre>
<p>I want another object data2 wi... | <p>You're modifying the original element object, which isn't a full deep copy of the original data.</p>
<p>Create a copy of el in the function and then calculate the new <code>.y</code>. For example:</p>
<pre><code>var data2 = data.map(function(el) {
return {
x : el.x,
y : 1-el.y,
classifier : el.classi... |
Retrieving data from sql file in java <p>I need some guidance on how to retrieving data from a database.
The database is called Drug Combination DataBase and so far I'm just using a small text file that contains a small portion of the data, but the complete database is available as a 14mb sql-file. Can I load this in a... | <p>the way to connect a Java program to a database is through JDBC. the file needs to be read int and saved to a database like MySQL or PostgresQL in order to be accessed. check out this link for a good tutorial:
<a href="http://www.tutorialspoint.com/jdbc/" rel="nofollow">jdbc tutorial</a></p>
|
Make Pointer Getter use unique_ptr <pre><code>sf::RectangleShape* operator()()
{
return &player;
} // RectangleShape Getter
</code></pre>
<p>Do I need to free memory after this getter? If yes, how would one do this with <code>unique_ptr</code>? </p>
<p>I tried</p>
<pre><code>std::unique_ptr<sf::Rectangle... | <p>It seems like <code>player</code> is member of a class and you are trying to hand out a pointer to it for it to modified outside the class?</p>
<p>In this case, the class it belongs to owns the memory and it is down to that class to handle freeing the data when it is destroyed. A pointer to that member should absol... |
My PyQt app runs fine inside Idle but throws an error when trying to run from cmd <p>So I'm learning PyQt development and I typed this into a new file inside IDLE:</p>
<pre><code>import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
def window():
app = QApplication(sys.argv)
win = QDialog()
b1 = ... | <p>This is because when running from the command line you're using a different version of Python to the one in IDLE (with different installed packages). You can find which Python is being used by running the following from the command line:</p>
<pre><code>python -c "import sys;print(sys.executable)"
</code></pre>
<p>... |
Change Firebase API Key, Storage Bucket URL, etc Within App <p>A bit of background, I am planning to allow user to use his/her Firebase database within the application by keying in its own Firebase credentials i.e. API Key, Storage bucket url, etc.</p>
<p>Core questions is, is it possible to change Firebase database p... | <p>You can initialize a <code>FirebaseApp</code> instance with options that you specify in your code.</p>
<p>See the <a href="https://firebase.google.com/docs/reference/android/com/google/firebase/FirebaseOptions.Builder" rel="nofollow">reference docs for <code>FirebaseOptions.Builder</code></a>.</p>
<p>Also see this... |
How to generate random number with a large number of decimals in Python? <p>How it's going?</p>
<p>I need to generate a random number with a large number of decimal to use in advanced calculation.</p>
<p>I've tried to use this code:</p>
<pre><code>round(random.uniform(min_time, max_time), 1)
</code></pre>
<p>But it... | <h2>100 decimals</h2>
<p>The first problem is how to create a number with 1000 decimals at all.</p>
<p>This won't do:</p>
<pre><code>>>> 1.23456789012345678901234567890
1.2345678901234567
</code></pre>
<p>Those are floating point numbers which have limitations far from 100 decimals.</p>
<p>Luckily, in Pyt... |
Is the correct way to access ref in react? <p>Without using binding of this.say to this on button the example does not work. However I am not sure if it is right or has any side effects. </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<... | <p>Seems like this is required when using ES6 classes: <a href="https://facebook.github.io/react/docs/reusable-components.html#autobinding" rel="nofollow">See: Autobinding</a></p>
<p>Only difference is example above binds the method in constructor </p>
|
python class import issue <p>I am new to python and doing some programming for school I have written code for a roster system and I am supposed to use dictionaries. I keep getting error No module named 'players_Class'
Can someone tell me what I am doing wrong</p>
<pre><code>class Players:
def __init__(self, name,... | <p>you have unused </p>
<pre><code>import players_Class
</code></pre>
<p>statement in your code. just erase it!</p>
|
JPA @ManyToOne for hibernate <ul>
<li>old school hibernate - ManyToOne was lazy</li>
<li>JPA - ManyToOne is eager</li>
</ul>
<p>In both OneToMany is lazy thank god.</p>
<p>Is there a setting in hibernate to override this very bad setting? There is way too many people who keep adding ManyToOnes without setting them t... | <p>It is not possible for Hibernate (or any other framework) to distinguish the default of an annotation attribute from the same value that was set.</p>
<p>I mean at runtime <code>@ManyToOne</code> and <code>@ManyToOne(fetch = FetchType.EAGER)</code> are exactly the same.</p>
<p>But as you can't change the runtime be... |
Python: Ending line every N characters when writing to text file <p>I am reading the webpage at "<a href="https://google.com" rel="nofollow">https://google.com</a>" and writing as a string to a notepad file. In the notepad file, I want to break and make a newline every N characters while writing, so that I don't have ... | <p>Better yet, use the <a href="https://docs.python.org/2.7/library/textwrap.html" rel="nofollow">textwrap</a> library. Then you can use</p>
<pre><code>textwrap.fill(str(line))
</code></pre>
<p>and get breaks on whitespace and other useful additions.</p>
|
How to manipulate individual elements in a numpy array iteratively <p>Let's say I want to iterate over a numpy array and print each item. I'm going to use this later on to manipulate the (i,j) entry in my array depending on some rules.</p>
<p>I've read the numpy docs and it seems like you can access individual element... | <p>Start with:</p>
<pre><code>for i in range(row):
for j in range(column):
print space[i,j]
</code></pre>
<p>You are generating indices in your loops which index some element then!</p>
<p>The relevant <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" rel="nofollow">numpy docs on in... |
Regular Expression to replace some dots with commas in customers' comments <p>I need to write a Regular Expression to replace <code>'.'</code> with <code>','</code> in some patients' comments about drugs. They were supposed to use comma after mentioning a side effect, but some of them used dot. for example: </p>
<pre>... | <p>You can use the following pattern:</p>
<pre><code>\.(\s*(?!(?:i|she)\b)\w+(?:\s+\w+)?\s*)(?=[^\w\s]|$)
</code></pre>
<p>This matches a dot, then captures one or two words where the first one is none of your mentioned pronouns (you will need to expand that list most likely). This has to be followed by a character t... |
Don't show part of website depend on url <p>I had 2 websites www.example-with-prices.com and www.example-without-prices.com.</p>
<p>Both sites are basically the same, except one doesn't show the prices of the products and it's a lot of trouble to maintain both sites. </p>
<p>Now I rebuild these websites and want to ... | <p>Added by default to hide - Then show if not a no price host </p>
<pre><code><style>#hideshow{display:none}</style>
<div id='hideshow' data-value="price1" style="display:none">
<table> price table here </table>
</div>
<script>
$('[id^="hideshow"]').on('click', fu... |
How to implement an abstract method when abstract class is used in a variadic context <p>How to implement in the following code the abstract base class in a generic case. The code is simplified from a library I am working on. So an explicit implementation for int and double is not an option. </p>
<pre><code>template &... | <p>What about the following example?</p>
<p>First of all, I think you need define <code>virtual</code> the <code>send()</code> method in <code>Foo</code> (if you want it pure virtual).</p>
<p>Next, you can declare a intermediate template class (<code>Foo2</code>) where implement the <code>override</code> <code>send()... |
SQL columns filtered differently <p>It's been a while since I deal with SQL. Let's say I have a table Transaction with the following columns: Company, Year, Value.</p>
<p>I want to create a resultset that sums the total value for each Company, but in one column I want 2015 and in other 2016.</p>
<pre><code>Company | ... | <p>Here's one option using <code>conditional aggregation</code>:</p>
<pre><code>select company,
sum(case when year = 2015 then value end) total2015,
sum(case when year = 2016 then value end) total2016
from Transaction
group by company
</code></pre>
|
Django - Get Id of the ForeignKey Object in List View <p>I have two models linked by Foreign Key. RunConfig RunConfig<strong>Status</strong></p>
<pre><code>class RunConfig(models.Model):
config_name = models.CharField(max_length=100)
class RunConfigStatus(models.Model):
config_run_name = models.CharFiel... | <p>Of course it's possible. You're already accessing the runconfig name, you can do exactly the same thing with the pk:</p>
<pre><code><a href="{% url 'runconfig-detail' pk=run.config_name.id %}">
</code></pre>
<p>However you should really pick a less confusing name for the foreign key; the field <code>config_n... |
STL algorithm for smallest max element than a given value <p>Recently I came across this code fragment:</p>
<pre><code>// look for element which is the smallest max element from
// a given iterator
int diff = std::numeric_limits<int>::max();
auto it = nums.rbegin();
auto the_one = nums.rbegin();
for (; it != gi... | <pre><code>auto the_one = std::min_element(nums.rbegin(), given,
[given](int a, int b) {
bool good_a = a > *given;
bool good_b = b > *given;
return (good_a && good_b) ? a < b : good_a;
});
</code></pre>
<p>The trick is to write a comparison function that declares any "good" element (on... |
delete pixel from the raster image with specific range value <p><strong>update :</strong>
any idea how to delete pixel from specific range value raster image with
using <code>numpy/scipy</code> or <code>gdal</code>?</p>
<p><strong>or how to can create new raster with some class using raster calculation expressions</s... | <p>Rasters are 2-D arrays of values, with each value being stored in a pixel (which stands for picture element). Each pixel must contain some information. It is not possible to delete or remove pixels from the array because rasters are usually encoded as a simple 1-dimensional string of bits. Metadata commonly helps ex... |
Define vm function correctly in Controller As <p>I'm new in javascript and AngularJS.</p>
<p>So... May be is a stupid question, but I have two way to define functions in javascript. </p>
<p><strong>In the following to controllers please look at "grupoCancha" and "grupoVisible"</strong> (I pasted the hole script becau... | <p>the only difference I see is using vm with two last functions in your second code sample. When you use</p>
<pre><code>function grupoVisible(canchaComplejo){
return vm.grupoMostrado === canchaComplejo;
}
</code></pre>
<p>this function is private to the current JS code of your controller (since your controller is... |
Why is are the dicts in this list of dicts empty? <p>As the title implies; I'm unsure as to why the dictionaries in this list of dictionaries are empty. I print the dictionaries out before I append them to the list and they all have 4 keys/values. </p>
<p>Please ignore the 'scrappiness' of the code- I always go throug... | <p>I presume you mean this:</p>
<pre><code> print len(self.data_dict)
self.master_list.append(self.data_dict)
print self.data_dict
self.data_dict.clear()
</code></pre>
<p>The <code>dict</code> is empty because <em>you clear it</em>. Everything is a reference in Python.</p>
<pre><code>>>> d = {k:v for k,v... |
How to maintain the size of a ListView when used within a UserControl and parent WindowDialog <p>I've been fighting this xaml for hours now. It should be very simple. I have a general <strong>WindowDialog</strong> (Billing.WindowDialog) with a <strong>ContentPresenter</strong> displaying a UserControl (NovaLibraries.Vi... | <p>By removing </p>
<pre><code>HorizontalAlignment="Center" VerticalAlignment="Center"
</code></pre>
<p>from the ContentPresenter, the ListView and its parent UserControl behave as expected. </p>
|
How to use CSS when installed from npm in Angular2 <p>I am trying to install the below:</p>
<pre><code>npm install bootstrap-material-design
</code></pre>
<p>I then added the below to my package.json</p>
<pre><code>"dependencies": {
...
"bootstrap-material-design": "0.5.10"
}
</code></pre>
<p>So in angular2... | <p>It's better you include in your main module file like in <code>app.ts</code> file:</p>
<pre><code>// Just make sure you use the relative path here
import '../../node_modules/bootstrap-material-design/dist/css/bootstrap-material-design.css'
import '../../node_modules/bootstrap-material-design/dist/css/ripples.min.cs... |
How do I combine two nested MySQL queries into one View? <p>I have two queries, almost similar, but never the less,They must be treated as separate as they have different meanings and values, I want to combine them into one view, I tied doing <code>UNION</code>, but the result was they were all combined into one table,... | <p>One view doesn't product <em>two</em> result sets. But you can identify where they come from:</p>
<pre><code>CREATE VIEW TEAM_SUMMARY AS
SELECT 'Team1' as which,
c.country_name AS CountryName_T1, count(Team1) AS NoOfGames,
SUM(Team1_score) AS TotalGoalsFor,
SUM(Team2_score) AS Tota... |
click on div with javascript jquery <p>how can i do something with javascript to click on div like</p>
<p>i have a div with display none like this</p>
<pre><code><div style="display:none;" id="button">Hello World</div>
</code></pre>
<p>when that div changed display to block then with javascript must clic... | <p>Try this one</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function(){
$('#button').trigger('focusin');
});</code></pre>
</div>
</div>
</p>
|
Realurl-Configuration for news-Extensi <p>I have an problem with the news-configuration for realurl.
TYPO3: 7.6.11
realurl: 2.1.4
news: 5.2.0</p>
<p>I created the following realurl_conf.php. (<a href="http://pastebin.com/GsYVaaDr" rel="nofollow">http://pastebin.com/GsYVaaDr</a>):</p>
<pre><code><?php
// real... | <p>First, change the 'enableCHashCache' => true to 'enableCHashCache' => FALSE in your realurl_conf.php for remove cHash=.... from your url. and change below code in postVatSets array for realurl. Try this solution and let me know your feedback. This code works for me.</p>
<pre><code>'postVarSets' => array(
... |
GraphQL Viewer for mutations <p>Is it a good practice to have a viewer for GraphQL mutations? Theoretically this makes sense to me as some mutation end points shouldn't be possible if you are not logged in, etc.</p>
<p>But when I see examples on the web, I only see implementation of GraphQL viewers for queries. For mu... | <p>The <code>viewer</code> field isn't a good practice, either for mutations or queries. It's a remnant of Facebook's legacy GraphQL platform from before it was open-sourced, which didn't allow arguments on root query fields. This meant that all of the fields needed to be moved one level down, below <code>viewer</code>... |
Two pickers in the same UIViewcontroller <p>I am making an app where a user has the option to use two UIPickers in the same view controller. How can this be done. I am wanting one picker to display beach names and another to display animals living at the beach. </p>
<p>Thanks for your help</p>
| <p>Here's a quick guide to doing this:</p>
<p>1.Initialize pickers, and picker data sets in the class:</p>
<pre><code> var pickerView1 = UIPickerView()
var pickerView2 = UIPickerView()
var pickerView1Data: [String] = ["Waikiki", "Long Beach", ...]
var pickerView2Data: [String] = ["Crab", "Seal", ...]
</code></pre... |
extract value from a set in python <p>here is the output in sql query output in set format in python. how to extract just the value to a variable
ResultSet({'(u'tx', None)': [{u'value': 31399946096.0, u'time': u'2016-10-05T05:06:15.009545466Z'}]})</p>
<p>i need v=31399946096.0</p>
<p>thanks</p>
| <p>i tried this way to get it the value out, is there any other way
result=({'(u'tx', None)': [{u'value': 31399946096.0, u'time': u'2016-10-05T05:06:15.009545466Z'}]})</p>
<p>r=list(result)<br>
for i in r:<br>
print i[0]['value'] </p>
<p>31399946096.0</p>
|
C++ Return Performace <p>I have a question about performance. I think this can also applies to other languages (not only C++).</p>
<p>Imagine that I have this function:</p>
<pre><code>int addNumber(int a, int b){
int result = a + b;
return result;
}
</code></pre>
<p>Is there any performance improvement if I ... | <p>To answer this question you can <a href="http://gcc.godbolt.org/">look at the generated assembler code</a>. With -O2, x86-64 gcc 6.2 generates exactly the same code for both methods:</p>
<pre><code>addNumber(int, int):
lea eax, [rdi+rsi]
ret
addNumber2(int, int):
lea eax, [rdi+rsi]
ret
</cod... |
Button for updating data <p>I have a list of buttons that each pass on a different value. The code should store this value as a variable or session, which then is passed on to a function that updates the table row of the value. I tried just storing this value as a variable and then passing it on, but that didn't work s... | <p>So you are saying that the Pending function is returning TRUE, and redirecting you to membership.php ? or index.php ( or are these the same ) - </p>
<ul>
<li>if that query fails and returns false - you would just end up on the page that you had posted to . </li>
</ul>
|
Choosing between an INSTEAD OF/AFTER trigger and a UDF <p>I have a business rule in my database that says an ID must match a list of specific ID's in order to be valid. I can't use a CHECK constraint in this instance as it requires a subquery to find the valid ID's, hence I need to use a trigger.</p>
<p>Put simply, in... | <p>You can use User Defined Function and encapsulate your validation codes in it. It should look something like this.</p>
<pre><code>-- Create Dummy Table
CREATE TABLE Employee
( ID INT, Name VARCHAR(50), Age TINYINT)
GO
-- Function to verify age of employee
CREATE FUNCTION dbo.verifyAge
( @Age TINYINT)
RETUR... |
Fixing Sizing in Spritekit <p>I am creating an app in SpriteKit using C# on Xamarin, and I am trying to position "Tiles" correctly on a 1024x768 scene. Here is my code for the tiles.</p>
<pre><code> public class GameScene : SKScene
{
Tile tile1 = new Tile(320, 320, UIColor.Blue);
Tile tile2 = new Tile(320,... | <p>That is doing exactly what you are coding. </p>
<ul>
<li><p>1st</p>
<p>you need to learn about aspect mode, you are doing a 3:4 scene but trying to render it in a 9:16 device, You have 4 choices:</p></li>
</ul>
<blockquote>
<p><strong>.AspectFill:</strong> This is default in XCodes template and will scale th... |
ruby on rails active record find depends on params <p>Hello Stack Overflowers.
I need to know, how to write rails query which depends on GET params. For exapmle i have action</p>
<pre><code>localhost/users?text=aaa&city=NY
</code></pre>
<p>and now i want to write query to search all users where firstname,lastname... | <p>In your user model you can either define a scope or a search function. For example </p>
<pre><code>def self.search(name)
where("name LIKE ?", "%#{name}%")
end
</code></pre>
<p>Then in your controller assuming you are going to search through your index view the code will probably be something like this </p>
<pre... |
Reusing a Class - Will Unused IBOutlets Cause a Crash <p>Let's say I have a Storyboard ViewController with 10 labels, each is connected to its viewControllerClass via IBOutlet.</p>
<p>Now I make a NEW ViewController that is extremely similar. However, it only has 9 labels. Those nine labels should be handled by the co... | <p>It is perfectly safe to have IBOutlets that have not been connected in a storyboard or xib. The only side effect is that these outlets will be nil. </p>
|
Confusing bug with brackets on my function <pre><code>def cube_of(valz):Â Â Â Â
    '''Returns the cube of values'''   Â
    if len(valz) == 0:   Â
        return 0   Â
    else:   Â
        new_val = [valz[0] ** 3]   Â
        return  [new_val] + [cube_of(valz... | <p><code>cube_of(valz[1:])</code> is already a list. There's no need to wrap it in brackets.</p>
<pre><code>return [new_val] + cube_of(valz[1:])
</code></pre>
|
Display "long" pandas dataframe in jupyter notebook with "foldover"? <p>Let's say I have a pandas dataframe with many columns:</p>
<p><a href="http://i.stack.imgur.com/bjFlz.png" rel="nofollow"><img src="http://i.stack.imgur.com/bjFlz.png" alt="enter image description here"></a></p>
<p>I can view all of the columns b... | <p>In addition to setting max cols like you did, I'm importing <code>display</code></p>
<pre><code>import pandas as pd
pd.set_option('display.max_columns', None)
from IPython.display import display
</code></pre>
<p>creating a frame then a simple for loop to display every 30 cols</p>
<pre><code>df = pd.DataFrame([ra... |
get TypeError when i import my own .py file <p>I am doing a sort program.i have two files called bubble(a bubble sort program) and cal_time(calculate the time),and they are in the same directory.</p>
<p>The problem is ,bubble work alone fluently. however,when i import bubble to my cal_time file and callback bubble s... | <p>Your issue lies here:</p>
<pre><code>result.append(random.random)
</code></pre>
<p>You are appending the method <code>random.random</code> onto the list â which has the type <code>builtin_function_or_method</code> (thus resulting in the error you are receiving â how would you compare functions?).</p>
<p>Inst... |
iOS constraint style: addConstraints vs .isActive = true <p>I have some code which is creating auto-layout constraints programatically, and adding them to a view.</p>
<p>There are two ways to do this - call <code>addConstraints</code> on the superView, or set <code>.isActive = true</code> on each constraint (which int... | <p>According to the documentation on <code>addConstraint:</code> setting the <code>active</code> property is recommended for <em>individual constraints</em>. (note: <code>active</code> property is only available iOS 8+).</p>
<blockquote>
<p>When developing for iOS 8.0 or later, set the constraintâs active
proper... |
javascript / jQuery Press spacebar repeatedly <p>What i'm trying to achieve is focus on a button and then press spacebar repeatedly, the focus part i resolved.</p>
<p>I searched and found this " <a href="http://stackoverflow.com/questions/15045033/simulate-click-on-spacebar-each-5-secondes-in-jquery">Simulate click on... | <p>The example on <a href="http://plnkr.co/edit/33yTNn1dKFhKMwSls5MU" rel="nofollow">that question</a> is pretty good.
You don't need the focus. You just need to call the button "action" function.</p>
<p>Here is the solution anyway, for that same example linked above:</p>
<pre><code>var presscount = 0;
var sendEvery... |
Script to download manually generated excel file on reference website? <p>I am specifically looking at the ReferenceUSA website. To download information, one has to manually select all the items, then click download, and then on another page click to generate a CSV file. Is there anyway to automate this kind of process... | <p>You could try Selenium, here is an example to open a web page, and click a button.</p>
<pre><code>>>> from selenium import webdriver
>>> browser = webdriver.Chrome() ## now web browser opened
>>> browser.get("https://www.python.org") ## now python.org web page opened
</code></pre>
<p>T... |
Swapping columns (left / right) on alternate rows <p>I have a series of rows, each containing two columns, split 50/50 in width.</p>
<p>I'd like every other row to swap the left column (<code>.image</code>) to the right right, but I need to maintain the sequence in the HTML as it's displayed as one column on smaller s... | <p>you may use <code>display:table</code><em>(optionnal)</em>, <code>:nth-child(even)</code> and <code>direction</code> to swap div position :
<a href="http://codepen.io/gc-nomade/pen/VKXPAV" rel="nofollow">codepen</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">... |
Insert Row based on user input in multiple sheets <p>Excel 2010
Searching for macro to insert rows based on user input. User providing Row number to insert row.</p>
<ol>
<li>Based on user input - Row to be inserted in multiple sheets ( accounts, process,data,...and so on) have 19 sheets</li>
<li>Copy formula and forma... | <p>Edited:</p>
<pre><code>Sub Insert_Row()
Dim SelRow as Integer, i as Integer, j as Integer
If Selection.Rows.Count > 1 Then Exit Sub
SelRow = Selection.Row
On Error Goto nonNumeric
j = InputBox("What row to insert data into?", "Pick a row")
On Error GoTo 0
GoTo NumericEntry
nonNumeric... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.