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() {
char inputOne;
char inputTwo;
printf("Insert a char: ");
scanf("%c", &inputOne);
// &inputOne is the pointer to inputOne.
printf("Insert another char: ");
scanf("%c", &inputTwo);
if (inputOne == inputTwo) {
printf("You have inserted the same char!\n");
printf("Chars inserted: %c, %c\n", inputOne, inputTwo);
} else {
printf("You have inserted two different chars!\n");
printf("Chars inserted: %c, %c\n", inputOne, inputTwo);
}
}
</code></pre>
<p>when compiled does not return any error, but when I launch the application on the Terminal, I am not able to insert the second character.
Here is an example of what happens:</p>
<pre><code>Macbook-Pro-di-Rodolfo:~ Rodolfo$ /Users/Rodolfo/Documents/GitHub/Fondamenti\ di\ C/esempio-if-else ; exit;
Insert a char: a
Insert a second char: You have inserted two different chars!
Chars inserted: a,
logout
[Process completed]
</code></pre>
<p>Can anybody explain me why this happens?</p>
| <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 another char: ");
scanf("%c", &inputTwo);
scanf("%c", &inputTwo);
if (inputOne == inputTwo) {
printf("You have inserted the same char!\n");
printf("Chars inserted: %c, %c\n", inputOne, inputTwo);
} else {
printf("You have inserted two different chars!\n");
printf("Chars inserted: %c, %c\n", inputOne, inputTwo);
}
}
</code></pre>
|
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 can someone please explain that process</p>
| <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 /25 provides 128 addresses and a /26 provides 64 addresses. So we will need a /25 with 128 addresses (126 usable).</p>
|
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 the GPS system. Not all methods are available on all devices, obviously. Rather than knowing how location was determined, you merely request location within a desired level of accuracy, and the framework will call back and notify you of an update in position. The actual position is not guaranteed to be pinpoint accurate.</p>
|
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 it in uppercase and end it back. Everything seems to work, except for sending back the uppercase. Here is the code:</p>
<p>TCPServer:</p>
<pre><code>import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
public static void main(String[] args) throws Exception {
System.out.println("SERVER");
String clientSentence;
String capitalizedSentence;
ServerSocket server = new ServerSocket(6789);
TCPClient.main(null);
while (true) {
Socket connection = server.accept();
System.out.println("<S> Connection!");
BufferedReader fromClient = new BufferedReader(
new InputStreamReader(connection.getInputStream()) );
DataOutputStream toClient = new DataOutputStream(connection.getOutputStream());
clientSentence = fromClient.readLine();
System.out.println("<S> Recieved: " + clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + '\n';
System.out.print("About to send: " + capitalizedSentence);
toClient.writeBytes(capitalizedSentence);
}
}
}
</code></pre>
<p>TCPClient:</p>
<pre><code>import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;
public class TCPClient {
public static void main(String[] args) throws Exception {
System.out.println("CLIENT");
String sentence;
String modSentence;
BufferedReader inUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientToServer = new Socket("localhost", 6789);
DataOutputStream outServer = new DataOutputStream(clientToServer.getOutputStream());
BufferedReader inServer = new BufferedReader(
new InputStreamReader(clientToServer.getInputStream()) );
System.out.println("<C> Type now: ");
sentence = inUser.readLine();
System.out.println("<C> Got it!");
System.out.println("<C> Sending " + sentence + " to server...");
outServer.writeBytes(sentence + '\n');
outServer.flush();
System.out.println("<C> Server respodse:");
modSentence = inServer.readLine();
System.out.println("<C> From server: " + modSentence);
clientToServer.close();
}
}
</code></pre>
<p>Console:</p>
<pre><code>SERVER
CLIENT
<C> Type now:
efd
<C> Got it!
<C> Sending efd to server...
<C> Server respodse:
asd
</code></pre>
<p>and...</p>
<p>Nothing</p>
| <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, another static function.</p>
|
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);
</code></pre>
<p>Here, <code>CGEventRef</code> is a pointer on a <code>__CGEvent</code> structure on which I know nothing. I manipulate this type only through its interface.</p>
<p>How can I bind such opaque types using Ctypes?</p>
<p><strong>Links</strong></p>
<ol>
<li><a href="https://developer.apple.com/reference/coregraphics/1658572-quartz_event_services?language=objc" rel="nofollow">https://developer.apple.com/reference/coregraphics/1658572-quartz_event_services?language=objc</a></li>
</ol>
| <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 "helloworld1" and second message is sent by "helloworld2" .</p>
<p>When i run the below code i get output as below </p>
<pre><code>Yes you made it Hi helloworld2
Yes you made it Hi helloworld1
</code></pre>
<p>My question is why is it the 2nd message is processed at first? I was expecting the output as below because the first message is sent by helloworld1</p>
<pre><code>Yes you made it Hi helloworld1
Yes you made it Hi helloworld2
</code></pre>
<p><strong>Code for ActorApp:</strong></p>
<pre><code>import akka.actor.{ActorSystem, Props}
object ActorApp {
def main(args :Array[String]) ={
val system = ActorSystem("SimpleActorSystem")
val actorObj1 = system.actorOf(Props[HelloWorld],"helloworld1")
actorObj1 ! "Hi helloworld1"//first message sent
val actorObj2 =system.actorOf(Props[HelloWorld],"helloworld2")
actorObj2 ! "Hi helloworld2"//second message sent
}
}
</code></pre>
<p><strong>Code for Actor:</strong> </p>
<pre><code>import akka.actor.Actor
class HelloWorld extends Actor {
def receive = {
case dataStr:String => println("Yes you made it "+dataStr)
}
}
</code></pre>
| <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 guaranteed for any given sender-receiver pair. If you send multiple messages from "helloworld1" they will be received in the order you sent them (however messages from other sources may come in between).</p>
<p>See <a href="http://doc.akka.io/docs/akka/current/general/message-delivery-reliability.html" rel="nofollow">the documentation</a> for an in-depth explanation.</p>
|
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 the data? Because when I use single words it does work perfect. </p>
<p><strong>arrays and dummy data:</strong></p>
<pre><code>var exercises = [exercise]()
var filteredExercises = [exercise]()
// SOME DUMMY DATA FOR THE TABLEVIEW
let exercise1 = exercise(exerciseName: "Incline Bench Press")
let exercise2 = exercise(exerciseName: "Decline Bench Press")
let exercise3 = exercise(exerciseName: "Bench Press")
exercises.append(exercise1)
exercises.append(exercise2)
exercises.append(exercise3)
</code></pre>
<p><strong>Searchbar function:</strong></p>
<pre><code>// ***************** SEARCHBAR FUNCTIONS ************** //
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == "" {
inSearchMode = false
tableView.reloadData()
}else{
inSearchMode = true
let lower = searchBar.text!.lowercased()
// each exercise in array is $0 and we taking the name value and the range of the inserted text is that contained in the name
filteredExercises = exercises.filter({$0.exerciseName.range(of: lower) != nil})
tableView.reloadData()
}
}
</code></pre>
<p><strong>showing in the cell:</strong></p>
<pre><code>// ***************** TABLE DELEGATE FUNCTIONS ******************* //
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "exerciseCell", for: indexPath) as? exerciseCell {
// let exercise = exercises[indexPath.row]
let exer: exercise!
if inSearchMode {
print(filteredExercises)
exer = filteredExercises[indexPath.row]
cell.updateUI(exercise: exer)
}else{
exer = exercises[indexPath.row]
cell.updateUI(exercise: exer)
}
// cell.updateUI(exercise: exercise)
return cell
}else{
return UITableViewCell()
}
}
</code></pre>
<p>Hope someone sees the problem.</p>
| <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 exercise3 = exercise(exerciseName: "Bench Press")
</code></pre>
<p>... so <code>lower</code> can never match anything in <code>exercises</code>.</p>
|
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 values. This should be simple enough and I am creating the hash of arrays correctly. However, when I print the associated values I get "ARRAY(0x7ff4bbb0c7b8)" in its place. </p>
<p>The file "INFILE" is tab delimitated and looks like this, for example: </p>
<pre><code>AAAAA AAAAA
BBBBB BBBBB BBBBB
</code></pre>
<p>Here is my code: </p>
<pre><code>use strict;
use warnings;
open(INFILE, '<', '/path/to/file') or die $!;
my $count = 0;
my %hash = (
AAAAA => [ "QWERT", "YUIOP" ],
BBBBB => [ "ASDFG", "HJKL", "ZXCVB" ],
);
while (my $line = <INFILE>){
chomp $line;
my $hash;
my @elements = split "\t", $line;
my $number = grep exists $hash{$_}, @elements;
open my $out, '>', "/path/out/Cluster__Number$._$number.txt" or die $!;
foreach my $sequence(@elements){
if (exists ($hash{$sequence})){
print $out ">$sequence\n$hash{$sequence}\n";
}
else
{
$count++;
print "Key Doesn't Exist ", $count, "\n";
}
}
}
</code></pre>
<p>Current output looks like: </p>
<pre><code>>AAAAA
ARRAY(0x7fc52a805ce8)
>AAAAA
ARRAY(0x7fc52a805ce8)
</code></pre>
<p>Expected output will look like: </p>
<pre><code>>AAAAA
QWERT
>AAAAA
YUIOP
</code></pre>
<p>Thank you very much for your help. </p>
| <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>$hash{$sequence}</code> array on the following line, with the elements separated by a comma:</p>
<pre><code>print $out ">$sequence\n";
print $out join ', ', @{ $hash{$sequence} };
</code></pre>
|
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 load only on top of the scroll view and not the all screen.<br>
I tried 2 different things until now, but none of the work:</p>
<ol>
<li><p>Add view controller inside scroll view in <code>prepareForSegue</code>:</p>
<pre><code> override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let addViewController = segue.destination as! AddViewController
addChildViewController(addViewController)
addViewController.view.frame = CGRect(x: 0, y: 0, width: width, height: height)
scrollView.addSubview(addViewController.view)
didMove(toParentViewController: self)
}
</code></pre></li>
<li><p>Add view controller in UIButton action: </p></li>
</ol>
<p>@IBAction func addDidTouch(_ sender: AnyObject) { </p>
<pre><code> let addViewController = AddViewController()
addChildViewController(addViewController)
addViewController.view.frame = CGRect(x: 0, y: 0, width: width, height: height)
scrollView.addSubview(addViewController.view)
didMove(toParentViewController: self)
}
</code></pre>
<p>Both of this solutions crashes my app.<br>
Is there a way to implement this correctly ?</p>
| <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 = CGSize(width: screenWidth*3, height: 1)
let first = getStoryboard(StoryboardName.Main).instantiateViewControllerWithIdentifier("FirstViewController") as! FirstViewController
let second = getStoryboard(StoryboardName.Main).instantiateViewControllerWithIdentifier("SecondViewController") as! SecondViewController
let third = getStoryboard(StoryboardName.Main).instantiateViewControllerWithIdentifier("ThirdViewController") as! ThirdViewController
self.addChildViewController(first)
self.scrollView.addSubview(first.view)
first.willMoveToParentViewController(self)
self.addChildViewController(second)
self.scrollView.addSubview(second.view)
second.willMoveToParentViewController(self)
self.addChildViewController(third)
self.scrollView.addSubview(third.view)
third.willMoveToParentViewController(self)
first.view.frame.origin = CGPointZero
second.view.frame.origin = CGPoint(x: screenWidth, y: 0)
third.view.frame.origin = CGPoint(x: 2*screenWidth, y: 0)
</code></pre>
<p>You may want to disable scroll of your scroll view if you want just to add(move) to another view controller only by your add button.</p>
|
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></pre>
<p>I've tested in Python 2 and 3 and it does what I expect, but I wonder whether it's really safe and whether it's idiomatic. The above code should be equivalent to the following rather more verbose alternative:</p>
<pre><code>iterator = iter(some_iterable)
while True:
try:
x = next(iterator)
except StopIteration:
break
# do stuff with x
if some_condition(x):
y = next(iterator)
# do stuff with y
</code></pre>
| <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 StopIteration exception, but when you are using a <code>for</code> loop based on the number of <code>next()</code> calls and your iteration it may be different.</p>
<p>For example in this case for even number of iteration it doesn't raise an exception but for odds it does. And the reason is that in even iteration numbers your next is always one item in front of the for loop, while for odds it's not like so.</p>
<pre><code>In [1]: it = iter(range(4))
In [2]: for x in it:
...: print(x)
...: next(it)
...:
0
2
In [3]: it = iter(range(3))
In [4]: for x in it:
print(x)
next(it)
...:
0
2
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-4-1b3db7079e29> in <module>()
1 for x in it:
2 print(x)
----> 3 next(it)
4
StopIteration:
</code></pre>
|
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',
outlet: 'auth',
component: LoginComponent
}
];
<router-outlet></router-outlet>
<router-outlet name="auth"></router-outlet>
</code></pre>
<p>So now I am trying to access this URL and expecting to get the HomeComponent in the primary outlet and the LoginComponent in the auth outlet: </p>
<p><a href="http://localhost:4200/(auth:login)" rel="nofollow">http://localhost:4200/(auth:login)</a></p>
<p>But it only loads the LoginComponent and not the HomeComponent.</p>
| <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: { 'auth': ['login'] } }]">Sign in</a>
</code></pre>
<p>Or:</p>
<pre><code>http://localhost/home(auth:login)
</code></pre>
|
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 implement a singly linked non-circular list without such a condition?</p>
<pre><code>package sample;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class SinglyLinkedList<T> implements Iterable<T> {
private Node<T> head = new Node<T>(null);
private Node<T> last = null;
public SinglyLinkedList(T... elements) {
addAll(elements);
}
public void add(T element) {
if (head.next == null) {
head.next = new Node<T>(element);
last = head.next;
} else {
Node<T> newNode = new Node<T>(element);
last.next = newNode;
last = last.next;
}
}
public void addAll(T... elements) {
for (T element : elements) {
add(element);
}
}
@Override
public String toString() {
Iterator<T> iterator = iterator();
if (!iterator.hasNext()) {
return "[]";
}
StringBuilder builder = new StringBuilder();
builder.append("[");
while (iterator.hasNext()) {
T element = iterator.next();
builder.append(element);
if (!iterator.hasNext()) {
return builder.append("]").toString();
}
builder.append(", ");
}
return builder.toString();
}
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
Node<T> current = head;
@Override
public boolean hasNext() {
return current.next != null;
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Node<T> temp = current;
current = current.next;
return temp.next.element;
}
};
}
private static class Node<T> {
private Node<T> next;
private T element;
Node(T element) {
this.element = element;
}
@Override
public String toString() {
return element.toString();
}
}
}
</code></pre>
| <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 can simply call a method on some other object. And then, the "if" is "hidden" within the code that initially generated that "other object" and gave it to your client code. (you find some nice examples how that works in these <a href="https://www.youtube.com/playlist?list=PLD0011D00849E1B79" rel="nofollow">videos</a>).</p>
<p>But - I think this would be clear overkill in this case! </p>
<p>The point is: from a readability point of view, that one check really doesn't hurt (you could refactor things into more methods maybe). And performance ... doesn't matter either. If your code is called so often that it would matter, the JIT will kick in anyway, and probably create code that that takes the correct branch directly for most cases.</p>
<p>Thus: this is a nice implementation; and I think you shouldn't worry about this one if-check there!</p>
|
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>
<p>select the fname and last name from the same department where are more than 2 employes named Mike.</p>
| <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() {
Person *Callum;
Callum = malloc(sizeof(*Callum));
init(Callum);
printf("Age: %d, height: %f\n", Callum.age, Callum.height);}
void init(Person * individual)
printf("Age: "); scanf("%d", &(individual->age));
printf("Height: "); scanf("%f", &(individual->height));}
</code></pre>
<p>I'm going to try to explain what I think is happening and if you could correct my logic I would be very grateful:</p>
<ul>
<li>We have a pointer called Callum of type Person. </li>
<li>'Callum = malloc(sizeof(*Callum));' => Does this mean our variable callum has been allocated the memory size of our struct on the heap? </li>
<li>Person points to our variable Callum. Edit: Sorry I got confused typing it out, I meant individual is pointing to our struc Person.</li>
<li>The program reads in an input and assigns it to the address of individual, which is the location of our variable Callum. We then print the values of Callum. </li>
</ul>
<p>Sorry, this is rattling my brain. I know the basic mechanics of a struc and a pointer but I just can't visualize what is happening. Any help would be appreciated. Thank you. </p>
| <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 <code>main()</code>, as the <code>Callum</code> is pointer type, you should use the pointer member dereference operator <code>-></code></p>
<pre><code> printf("Age: %d, height: %f\n", Callum->age, Callum->height);
</code></pre>
<p>That said, regarding the questions</p>
<blockquote>
<ul>
<li><em><code>Callum = malloc(sizeof(*Callum));</code> => Does this mean our variable <code>callum</code> has been allocated the memory size of our <code>struct</code> on our heap?</em></li>
</ul>
</blockquote>
<ul>
<li>Yes, as long as <code>malloc()</code> is success.</li>
</ul>
<blockquote>
<ul>
<li><em>Person points to our variable Callum</em></li>
</ul>
</blockquote>
<ul>
<li>Not really. The correct way to express is <code>Callum</code> is a variable of type pointer to <code>Person</code>.</li>
</ul>
|
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 third row place it in front of the first row, take the fourth row and place it at the back etc.</p>
<p>At the moment I can fill a temporary array with one row and place it in the totalArray but this will get overwritten by with the next row.
I can not use ArrayList or multi dimensional arrays.</p>
<p>The code to make it more clear:</p>
<pre><code>class1() {
in = new Scanner(System.in);
out = new PrintStream(System.out);
}
public void lineToArray (Scanner intScanner) {
int i = 0;
int[] tempArray = new int[100];
while (intScanner.hasNext()) {
tempArray[i] = intScanner.nextInt();
i++;
}
}
public void readFile() {
while (in.hasNext()) {
in.useDelimiter("::");
String line = in.next();
Scanner lineScanner = new Scanner(line);
lineToArray(lineScanner);
}
}
void start() {
readFile();
}
</code></pre>
<p>and </p>
<pre><code>public class Class2 {
int[] totalArray = new int[1000];
Class2() {
}
public void addToFront(int[] tempArray, int i) {
//totalArray = tempArray + totalArray
}
public void addToBack(int[] tempArray, int i) {
//totalArray = totalArray + tempArray
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
</code></pre>
<p>Bear in mind that I'm a beginner</p>
| <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++){
if(i == 0){
ans.append(s[i]);
}
else if(i%2 == 0){
ans.append("::"+s[i]);
} else{
ans.reverse();
StringBuilder add = new StringBuilder(s[i]);
add.reverse();
ans.append("::"+add);
ans.reverse();
}
}
w.println(ans);
w.close();
}
</code></pre>
<p><strong>Output:</strong>
<br/>
<code>1 2 3::4 5:: 6 7 8 9::10 11 12::13</code><br/>
<code>10 11 12::4 5::1 2 3:: 6 7 8 9::13</code></p>
|
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 the matrix entries
</code></pre>
<p>But, if the matrix is very large it is not practical to load the entire i, j and data vectors into memory.</p>
<p>How do you build a coo_matrix such that (data, (i, j)) is fed (with an iterator or generator) from disk and the array/vector objects on disk are either in .npy or pickle formats? </p>
<p>Pickle is the better option as numpy.save/load are not optimized for scipy sparse. Maybe there is a another faster format.</p>
<p>Both numpy.genfromtext() and numpy.loadtxt() are cumbersome, slow and memory hogs.</p>
| <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 <code>csr</code> matrix constructed from the <code>coo</code> might be a little more compact, since its <code>indptr</code> array has one value per row. The <code>data</code> and <code>indices</code> arrays will be the same size as the <code>coo</code> (give or take given duplicates and sorting).</p>
<p><code>dok</code> and <code>lil</code> formats can be used for incremental matrix creation, but they won't save memory in the long run. Both still have to have an entry for each non-zero data point. In the <code>lil</code> case you'll have a bunch of lists; while the <code>dok</code> is an actual dictionary.</p>
<p>None of the sparse formats is 'virtual', creating elements 'on-the-fly' as needed.</p>
<p>I don't see how the various methods of loading the 3 defining arrays helps if their total size too large.</p>
<pre><code>In [782]: data=np.ones((10,),int)
In [783]: rows=np.arange(10)
In [784]: cols=np.arange(10)
In [785]: M=sparse.coo_matrix((data,(rows,cols)))
In [786]: M.data
Out[786]: array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
In [787]: M.data is data
Out[787]: True
In [789]: M.col is cols
Out[789]: True
</code></pre>
<p>Basically the <code>coo</code> format is a way of storing these 3 arrays. The real work, all the math, summation, even indexing, is performed with the <code>csr</code> format. </p>
|
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 same line is repeating for all columns so I want to concatenate all the 5 values for that particular column.</p>
<p>please let me know how can i do that.
below is the query which is fetching 5 values and I want those values into one row only separated by comma.</p>
<pre><code>SELECT PAC.PACKAGED_ITEM_GID
FROM SHIPMENT SH, ORDER_MOVEMENT OM,
ORDER_MOVEMENT_D OMD, S_SHIP_UNIT SSU, S_SHIP_UNIT_LINE SUL,
PACKAGED_ITEM PAC
WHERE OM.SHIPMENT_GID = SH.SHIPMENT_GID
AND OM.ORDER_MOVEMENT_GID = OMD.ORDER_MOVEMENT_GID
AND OMD.S_SHIP_UNIT_GID = SSU.S_SHIP_UNIT_GID
AND SSU.S_SHIP_UNIT_GID=SUL.S_SHIP_UNIT_GID
AND SUL.PACKAGED_ITEM_GID = PAC.PACKAGED_ITEM_GID
AND SH.SHIPMENT_GID = 'ULA/SAO.5000070143'
</code></pre>
| <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 order_movement om ON om.shipment_gid = sh.shipment_gid
JOIN order_movement_d omd ON omd.order_movement_gid = om.order_movement_gid
JOIN s_ship_unit ssu ON ssu.s_ship_unit_gid = omd.s_ship_unit_gid
JOIN s_ship_unit_line sul ON sul.s_ship_unit_gid = ssu.s_ship_unit_gid
JOIN packaged_item pac ON pac.packaged_item_gid = sul.packaged_item_gid
WHERE sh.shipment_gid = 'ula/sao.5000070143';
</code></pre>
<p>As you are selecting the <code>packaged_item_gid</code> only, which is available in <code>s_ship_unit_line</code>, you can select from this table alone and look up matching shipments in an <code>IN</code> clause.</p>
<pre><code>SELECT GROUP_CONCAT(packaged_item_gid) as packaged_item_gids
FROM s_ship_unit_line
WHERE s_ship_unit_gid in
(
select ssu.s_ship_unit_gid
FROM shipment sh
JOIN order_movement om ON om.shipment_gid = sh.shipment_gid
JOIN order_movement_d omd ON omd.order_movement_gid = om.order_movement_gid
JOIN s_ship_unit ssu ON ssu.s_ship_unit_gid = omd.s_ship_unit_gid
WHERE sh.shipment_gid = 'ula/sao.5000070143'
);
</code></pre>
|
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 takes for it to finish.</p>
<pre><code>from multiprocessing import Pool,cpu_count
def f(x):
for i in range(100000000):
x*x
return x*x
with Pool(8) as p:
a = p.map(f,[x for x in range(8)])
#~ f(5)
</code></pre>
<p>Calling <code>f()</code> without multiprocessing takes about 7s (<code>time</code>'s "real" output). Calling <code>f()</code> 8 times with a pool of 8 as seen above, takes around 7s again. If I call it 8 times with a pool of 4 I get around 13.5s, so there's some overhead in starting the script, but it runs twice as long. So far so good. Now here comes the part that I do not understand. If there are 8 cpu-s each with 4 cores, if I call it 32 times with a pool of 32, as far as I see it should run for around 7s again, but it takes 32s which is actually slightly longer than running <code>f()</code> 32 times on a pool of 8.</p>
<p>So my question is <code>multiprocessing</code> not able to make use of cores or I don't understand something about cores or is it something else?</p>
| <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 all the programs that has the endswith .py. So of the cpu time on your computer, time is allotted to python3.* which in turn allot time to the program you are running. This speed will depend on what hardware you have, what operation you are running, and how cpu-time is allotted between all these instances. </p>
<p><strong>How is cpu-time allotted?</strong> It is an like an while loop, the OS is distributing incremental between programs, and the python interpreter is incremental distributing it's distribution time to programs runned by the python interpretor. This is the reason the entire computer halts when a program misbehaves.</p>
<p><strong>Many processes does not equal</strong> more access to hardware. It does equal more allotted cpu-time from the python interpretor allotted time. Since you increase the number of programs under the python interpretor which do work for your application. </p>
<p><strong>Many processes does equal</strong> more work horses. </p>
<hr>
<p>You see this in practice in your code. You increase the number of workhorses to the point where the python interpreters allotted cpu-time is divided up between so many processes that all of them slows down. </p>
|
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 not root and get some error like this:</p>
<pre><code>E: Could not open lock file /var/lib/dpkg/lock - open (13: Permission denied)
E: Unable to lock the administration directory (/var/lib/dpkg/), are you root?
</code></pre>
<p>How can i install a package if it is not included in pip? What is the solution?</p>
| <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 install software from <code>apt</code> without sudo, I'd suggest you compile the software yourself and install it to your local home directory. For most packages, this is relatively straightforward (There are some software packages that will not work well when installed into your home directory).</p>
<p>Google "apt-get without sudo" for more <a href="http://unix.stackexchange.com/questions/42567/how-to-install-program-locally-without-sudo-privileges">instructions</a>.</p>
|
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.myTableView.delegate = self
self.myTableView.reloadData()
}</p>
<p>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arr.count
}</p>
<pre><code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "incTV")
cell.textLabel?.text = "X"
cell.detailTextLabel?.text = "Y"
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
myTableView.deleteRows(at: [indexPath], with: .fade)
arr.remove(at: (indexPath as NSIndexPath).row)
self.myTableView.reloadData()
}
}
override func viewWillAppear(_ animated: Bool) {
myTableView.reloadData()
}
</code></pre>
| <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 an extended Http class). </p>
<p>I've replicated simple tests from the <a href="https://angular.io/docs/ts/latest/guide/testing.html" rel="nofollow">Angular.io Docs</a> to spy on a service and wait for after component initialization to check if the service function has been fired and its content. <strong>Every time I run the last test using fakeAsync (and async), which checks the content of the currentUser variable in header.component, I receive the following error</strong>...</p>
<pre><code> Error: Uncaught (in promise): Error: Template parse errors:
'header-section' is not a known element:
1. If 'header-section' is an Angular component, then verify that it is part of this module.
2. If 'header-section' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. ("
[ERROR ->]<header-section></header-section>
<router-outlet></router-outlet>
<footer-section></footer-sectio"): AppComponent@1:2
'router-outlet' is not a known element:
1. If 'router-outlet' is an Angular component, then verify that it is part of this module.
2. If 'router-outlet' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. ("
<header-section></header-section>
[ERROR ->]<router-outlet></router-outlet>
<footer-section></footer-section>"): AppComponent@2:2
'footer-section' is not a known element:
1. If 'footer-section' is an Angular component, then verify that it is part of this module.
2. If 'footer-section' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. ("
<header-section></header-section>
<router-outlet></router-outlet>
[ERROR ->]<footer-section></footer-section>"): AppComponent@3:2
</code></pre>
<p>These selectors are from my <strong>AppComponent</strong>...</p>
<pre><code>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
moduleId: module.id,
template: `
<header-section></header-section>
<router-outlet></router-outlet>
<footer-section></footer-section>`
})
export class AppComponent {
constructor() {}
test(): string {
return 'this is a test';
}
}
</code></pre>
<p>My <strong>header.component.spec</strong>...</p>
<pre><code>import { Http, Request, RequestOptionsArgs, Response, XHRBackend, RequestOptions, ConnectionBackend, Headers } from '@angular/http';
import { HttpIntercept } from '../../services/auth/auth.service';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule, JsonpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';
import { RouterTestingModule } from "@angular/router/testing";
import { appRoutes } from '../../routes';
import { Cookie } from 'ng2-cookies/ng2-cookies';
import { AppComponent } from '../app/app.component';
import { HeaderComponent } from './header.component';
import { FooterComponent } from '../footer/footer.component';
import { HomeComponent } from '../home/home.component';
import { Four0FourComponent } from '../404/four0four.component';
import { UserProfileComponent } from '../user-profile/user-profile.component';
import { UserService } from '../../services/user/user.service';
import { ClockService } from '../../services/clock/clock.service';
import { Observable } from 'rxjs/Observable';
import { TestBed, async, fakeAsync, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { User } from '../../models/user/user.model';
class MockRouter { public navigate() { }; }
describe('HeaderComponent Test', () => {
let fixture;
let comp;
let userService;
let spy;
let user = new User({
_id: 123456,
userName: 'testName',
firstName: 'testFirst',
lastName: 'testLast',
email: 'test@email.com',
create: 'now',
role: 'user'
});
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
BrowserModule,
HttpModule,
FormsModule,
JsonpModule,
RouterTestingModule.withRoutes(appRoutes)
],
declarations: [
HomeComponent,
UserProfileComponent,
Four0FourComponent,
FooterComponent,
HeaderComponent,
AppComponent
],
providers: [
{
provide: Http,
useFactory: (
backend: XHRBackend,
defaultOptions: RequestOptions) =>
new HttpIntercept(backend, defaultOptions),
deps: [XHRBackend, RequestOptions]
},
Cookie
]
});
fixture = TestBed.createComponent(HeaderComponent);
comp = fixture.componentInstance;
userService = fixture.debugElement.injector.get(UserService);
spy = spyOn(userService, 'getMe')
.and.returnValue(Observable.of(user));
});
it('should instantiate component', () => {
expect(fixture.componentInstance instanceof HeaderComponent).toBe(true);
});
it('should not show currentUser before OnInit', () => {
expect(spy.calls.any()).toBe(false, 'getMe not yet called');
});
it('should still not show currentUser after component initialized', () => {
// Set cookie token, for the getMe to call
Cookie.set('token', 'test_token_alpha');
fixture.detectChanges();
expect(spy.calls.any()).toBe(true, 'getMe called');
});
//The problem test is bellow
it('should show currentUser after getMe promise', fakeAsync(() => {
fixture.detectChanges();
tick();
fixture.detectChanges();
expect(comp.currentUser).toEqual(user);
}));
});
</code></pre>
<p>Here's my <strong>header.component</strong>...</p>
<pre><code>import { Component } from '@angular/core';
import { Cookie } from 'ng2-cookies/ng2-cookies';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/interval';
import { UserService } from '../../services/user/user.service';
import { ClockService } from '../../services/clock/clock.service';
import { User } from '../../models/user/user.model';
@Component({
selector: 'header-section',
providers: [
UserService,
ClockService
],
moduleId: module.id,
template: `
<style>
header{
background: rgb(55, 129, 215);
position: relative;
}
.user-sign{
position: absolute;
top:0;
right:0;
margin: 23px 5%;
}
.app-title{
font-family: cursive;
padding: 15px;
text-align: center;
font-size: 36px;
color: white;
}
.user-sign button:hover{
cursor: pointer;
}
.active{
color: orange;
}
</style>
<header>
<a routerLink='/' routerLinkActive='active'>Home</a>
<a routerLink='/profile' routerLinkActive='active'>Profile</a>
<a routerLink='/yoloswaq69420blazeitfgt' routerLinkActive='active'>404</a>
<div class='user-sign'>
<h3 *ngIf='currentUser'>Welcome, {{currentUser.userName}}</h3>
<button *ngIf='!currentUser' type='button' (click)='testRegisterUser()'>Sign up</button>
<button *ngIf='!currentUser' type='button' (click)='testUser()'>Sign in</button>
<button type='button' (click)='logout()'>Sign out</button>
</div>
<h1 class='app-title'>MEA2N Fullstack</h1>
</header>`
})
export class HeaderComponent {
errorMessage: string;
public currentUser: User;
clock = this.clockService.currentTime;
constructor(private userService: UserService, private clockService: ClockService) { }
ngOnInit() {
let token = Cookie.get('token');
if (token)
this.userService.getMe().subscribe(user => this.currentUser = user);
}
login(email: string, password: string) {
this.userService.login(email, password)
.subscribe(() => {
return this.userService.getMe()
.subscribe(user => {
this.currentUser = user;
})
});
}
logout() {
this.userService.logout();
this.currentUser = null;
}
registerUser(username: string, email: string, password: string) {
this.userService.signup(username, email, password)
.subscribe(() => {
return this.userService.getMe()
.subscribe(user => {
this.currentUser = user;
})
});
}
testUser() {
this.login('jc.thomas4214@gmail.com', 'flight1855');
}
testRegisterUser() {
this.registerUser('Jason', 'jc.thomas4214@gmail.com', 'flight1855');
}
}
</code></pre>
<p>I've suspected that this error is occurring because of how I'm initializing my TestBed.configureTestingModule().</p>
<p>I've tried...</p>
<ol>
<li>Reordering both app.module and TestBed module declarations</li>
<li>adding schema: [CUSTOM_ELEMENTS_SCHEMA] to both modules</li>
</ol>
| <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: [
{provide: UserService, useClass: MockUserService},
{provide: ClockService, useClass: MockClockService}
]
});
fixture = TestBed.createComponent(HeaderComponent);
});
</code></pre>
<p>In this example the Services have been mocked but they can be spied too as you have correctly done for the UserService </p>
|
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 database to login. If the login is successful, it returns a JSON object.</p>
<pre><code> string sAddress = "http://hitsparkinteractive.com/api.php";
// Get the hash
string addrParams = "action=authenticate";
addrParams += "&username=" + user;
addrParams += "&password=" + pwd;
WebRequest webRequest = WebRequest.Create(sAddress + "?" + addrParams);
webRequest.Timeout = 3000;
WebResponse webResponse = webRequest.GetResponse();
JObject retJSON;
retJSON = JObject.Parse(webResponse.ToString());
</code></pre>
<p>This is working code from Visual Basic 6, that uses WinHTTPRequest.</p>
<pre><code>Private Function AuthenticateUser(ByVal index As Long, ByVal Username As String, ByVal Password As String) As Long
Dim HTTP As WinHttpRequest, sAddress As String, addrParams As String
Dim JSONParser As Object, retJSON As String, ErrorCode As String, ErrorMsg As String
On Error Resume Next
sAddress = "http://hitsparkinteractive.com/api.php"
addrParams = "action=authenticate"
addrParams = addrParams & "&username=" & Username
addrParams = addrParams & "&password=" & Password
Set HTTP = New WinHttpRequest
HTTP.Open "GET", sAddress & "?" & addrParams, False
HTTP.SetTimeouts 250, 250, 250, 3000
HTTP.Send
retJSON = HTTP.ResponseText
Set HTTP = Nothing
' Parse your JSON here.
Set JSONParser = JSON.parse(retJSON) ' What is returned is Scripting.Dictionary object
If Not JSONParser Is Nothing Then
If JSONParser.Exists("error") Then ' keys are case sensitive I believe
' We errored out
ErrorCode = JSONParser.Item("error")
Select Case ErrorCode
Case "3"
AuthenticateUser = 1
Case Else
AuthenticateUser = 2
End Select
ErrorMsg = JSONParser.Item("message")
Call AlertMsg(index, ErrorMsg)
Exit Function
ElseIf JSONParser.Exists("hash") Then ' we got our hash, sucessfully authenticated
TempPlayer(index).Hash = JSONParser.Item("hash")
AuthenticateUser = 0
Exit Function
End If
Else
AuthenticateUser = 3
Call AlertMsg(index, "Request timed out, please try again.")
Exit Function
End If
End Function
</code></pre>
| <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/en-us/library/system.net.webresponse.getresponsestream(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2" rel="nofollow"><code>GetResponseStream</code></a>.</p>
|
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>
<pre><code> ___
300 -| | |
200 -| ___ | |
100 -| | | ___ | |
0 -|_|___|_|___|_|___|______
a b c
</code></pre>
<p>How can I accomplish that?</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=element_text(angle=-90, vjust=0.5, hjust=0))
</code></pre>
<p><a href="http://i.stack.imgur.com/dSA2o.png" rel="nofollow"><img src="http://i.stack.imgur.com/dSA2o.png" alt="enter image description here"></a></p>
|
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 don't even care if the underlying content is in Markdown or HTML. I just want a way to copy indented lists that were created in a WYSIWYG editor and paste them into something that retains the indentation without bringing over the underlying HTML or Markdown or whatever runs the WYSIWYG system.</p>
<p>Example: say I have this list.</p>
<pre><code><ol>
<li>Main Heading
<ul>
<li>List item 1</li>
<li>List item 2</li>
</ul>
<li>Secondary Heading
<ul>
<li>List item 1</li>
<li>List item 2</li>
</ul>
</ol>
</code></pre>
<p>It appears as:</p>
<ol>
<li>Main Heading
<ul>
<li>List item 1</li>
<li>List item 2</li>
</ul></li>
<li>Secondary Heading
<ul>
<li>List item 1</li>
<li>List item 2</li>
</ul></li>
</ol>
<p>I want to be able to select the list, copy it with Command+C, and paste it into either (a) a spreadsheet where the destination column represents the level of indentation, so that column A is unindented, column B is indented one level, etc., or (b) a plain text document where the indentation is represented as tabs or spaces.</p>
| <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 you copy and paste some text, you are copying the text and the formatting, the CSS styling will be ignored.</p>
|
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 made it super laggy. After having done some research I found that a better way to approach this is to make a huge array containing all of the vertices (each shape separated by degenerate triangles) and then make one <code>gl.drawArray()</code> call per frame.</p>
<p>Here is the part of my code that runs on load:</p>
<pre><code>function loadGraphics() {
// ground
// buffers
quadVertexPositionBuffer = gl.createBuffer();
vertices = [];
verticesItemCount = 0;
quadVertexColorBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, quadVertexColorBuffer);
var colors = [
0.0, 0.4, 0.0, 1.0,
0.0, 0.4, 0.0, 1.0,
0.0, 0.4, 0.0, 1.0,
0.0, 0.4, 0.0, 1.0,
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.DYNAMIC_DRAW);
quadVertexColorBuffer.itemSize = 4;
quadVertexColorBuffer.numItems = 4;
}
</code></pre>
<p>Here is the part that runs per frame:</p>
<pre><code>function drawGraphics() {
// draw code for graphics
gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
gl.clearColor(0.35, 0.4, 1.0, 1.0 );
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
mat4.perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 100.0, pMatrix);
mat4.identity(mvMatrix);
// perspective
var cameraX = camera.x, cameraY = camera.y, cameraZ = camera.z;
mat4.rotate(mvMatrix, rotMatrix[1], [1, 0, 0]);
mat4.rotate(mvMatrix, rotMatrix[0], [0, 1, 0]);
mat4.translate(mvMatrix, [-cameraX/33, -cameraY/33, -cameraZ/33]);
debug.add("{camera} x:"+camera.x+",y:"+camera.y+",z:"+camera.z+";");
debug.add("\n{mouse delta} x:"+mouse.x-mouse.prevX+",y:"+mouse.y-mouse.prevY+";");
debug.add("\n{rm}[0]:"+rotMatrix[0]+",[1]:"+rotMatrix[1]);
// ground
gl.bindBuffer(gl.ARRAY_BUFFER, quadVertexColorBuffer);
gl.vertexAttribPointer(shaderProgram.vertexColorAttribute, quadVertexColorBuffer.itemSize, gl.FLOAT, false, 0, 0);
// land plots
vertices = [];
verticesItemCount = 0;
for (var i = 0; i < landPlots.length; i++) {
var oX = landPlots[i].x*3;
var oZ = landPlots[i].z*3;
var plotVertices = [
-1.5+oX, 0.0, 1.5+oZ, 1.0,
1.5+oX, 0.0, 1.5+oZ, 1.0,
-1.5+oX, 0.0, -1.5+oZ, 1.0,
1.5+oX, 0.0, -1.5+oZ, 1.0
];
pushDrawArray(plotVertices, 4);
for(var j = 1; j <= 2; j++) {
debug.add(" " + renderLandPlotIntersection(landPlots[i], j));
}
}
gl.bindBuffer(gl.ARRAY_BUFFER, quadVertexPositionBuffer);
gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, 4, gl.FLOAT, false, 0, 0);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.DYNAMIC_DRAW);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, verticesItemCount);
}
function renderLandPlotIntersection(landPlot, side) {
var x = landPlot.x;
var z = landPlot.z;
var lvl = landPlot.level;
var olvl = null;
var plot;
switch (side) {
case 0: plot =getLandPlot(x-1, z ); if (plot !== null) olvl = plot.level/66; else return 0; break;
case 1: plot =getLandPlot(x, z+1); if (plot !== null) olvl = plot.level/66; else return 0; break;
case 2: plot =getLandPlot(x+1, z ); if (plot !== null) olvl = plot.level/66; else return 0; break;
case 3: plot =getLandPlot(x, z-1); if (plot !== null) olvl = plot.level/66; else return 0; break;
default: throw "Land plot intersection drawing: side out of range."; return -1;
}
var intersectionVertices = [
x*3, lvl, z*3,
x*3, lvl, z*3,
x*3, olvl, z*3,
x*3, olvl, z*3
];
pushDrawArray(intersectionVertices, 4);
return +1;
}
function pushDrawArray(array, itemCount) {
if (vertices.length > 0) {
// degenerate
vertices.push(vertices[vertices.length-3]);
vertices.push(vertices[vertices.length-2]);
vertices.push(vertices[vertices.length-1]);
vertices.push(array[0]);
vertices.push(array[1]);
vertices.push(array[2]);
verticesItemCount += 2 ;
}
gl.bufferSubData(gl.ARRAY_BUFFER, verticesItemCount*4, array);
verticesItemCount += itemCount;
}
</code></pre>
<p>I started using <code>DYNAMIC_DRAW</code>, though I don't really know how to use it. <code>verticesItemCount</code> marks how many vertices are in the <code>vertices</code> array.</p>
<p><code>gl.drawArrays()</code> returns this error: </p>
<blockquote>
<p>[.Offscreen-For-WebGL-060B7ED8]GL ERROR :GL_INVALID_OPERATION : glDrawArrays: attempt to access out of range vertices in attribute 1 localhost/:1 WebGL: too many errors, no more errors will be reported to the console for this context.</p>
</blockquote>
<p>How can I fix this code to not cause an error?</p>
| <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>Doing <code>moment(date).toISOString()</code> gives <code>2016-10-08T09:00:00.000Z</code> which is not what I want.</p>
| <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 to get a string in your custom format.</p>
<p>Here there is a working example using a string input, you can use the same code also if your input is a javascript Date object.</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>// Input date as string
var s = '2016-10-08T09:00:00Z';
// Reset time part
// var m = moment(s).startOf('day'); // no UTC
var m = moment.utc(s).startOf('day'); // UTC mode
// Format using custom format
console.log(m.format('YYYYMMDD[T]HHmmss[Z]'));</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script></code></pre>
</div>
</div>
</p>
|
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:
static const double y;
public:
B();
};
class C : public A {
private:
static const int y;
public:
C();
};
</code></pre>
<p>Both children only differ in the type of their static member <code>y</code>. The implementation of both C and B is the same except on the initialization of the static member:</p>
<pre><code>B::B() : y (1.2) { setX(y) }
C::C() : y (2) { setX(y) }
</code></pre>
<p>But the problem with this approach is that in the implementation file I have to write twice the same code for <code>B</code> and <code>C</code>. Is there a proper way to write this such that I do not need to write twice the call to <code>setX</code>?</p>
<p>In the real problem the classes are a little more complicated, but the situation at hand is the same. In particular, initialization of <code>y</code> requires non-trivial constructors and so it has to be in the implementation file. </p>
| <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:
B() : A(1.2), y(1.2)
{}
};
</code></pre>
<p>Only problem is that base class constructor gets called first, so you need to repeat constant data value twice. You can easily macro it though.</p>
|
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>Example 2:</p>
<pre><code>class Dog
class << self
def another_class_method
:still_another_way
end
end
end
def test_heres_still_another_way_to_write_class_methods
assert_equal :still_another_way, Dog.another_class_method
end
</code></pre>
<p>May I know which way of writing the class method is preferred in Ruby and why? Are there situations where one is preferred over another?</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 consensus for using one over the other.</p>
<p>I personally use <code>def self.my_method</code> to minimize indentation</p>
|
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 using <code>SCOPE_IDENTITY()</code>. It works in SQL Server and returns the identity correctly but when I try to aquire it, convert the int into string and set it in a label for testing it reads as 0.</p>
<p>My stored procedure is as follows.</p>
<pre><code>SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE IdentityTest
@FirstName varchar(50),
@LastName varchar(50),
@id int output
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO Employees (FirstName, LastName)
VALUES (@FirstName, @LastName)
SET @id = SCOPE_IDENTITY()
RETURN @id
END
</code></pre>
<p>In my form.aspx.cs I have the following code to acess the DB.</p>
<pre><code>protected void Button1_Click(object sender, EventArgs e)
{
SqlCommand cons = new SqlCommand("IdentityTest", cncon);
cons.CommandType = CommandType.StoredProcedure;
cons.Parameters.Add("@FirstName", SqlDbType.NVarChar);
cons.Parameters.Add("@LastName", SqlDbType.NVarChar);
cons.Parameters.Add("@id", SqlDbType.Int);
cons.Parameters["@FirstName"].Value = nom.Value;
cons.Parameters["@LastName"].Value = dirclie.Value;
cons.Parameters["@id"].Value = IdCliente;
string IdClientesString = IdCliente.ToString();
cncon.Open();
cons.ExecuteNonQuery();
Label1.Text = IdClientesString;
cncon.Close();
}
</code></pre>
| <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</strong> the value:</p>
<pre><code>cons.ExecuteNonQuery();
int newIdValue = Convert.ToInt32(cons.Parameters["@id"].Value);
</code></pre>
|
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.225\",\"success\":-1,\"cs\":[{\"c\":\"http:\/\/ads.yahoo.com\/cms\/v1?esig=2~0e5920937f6aadb48bff63caeaefd5a0b961c753&nwid=1117471&sigv=1\",\"id\":16116},{\"c\":\"http:\/\/ade.clmbtech.com\/uid\/sync.htm?pid=19844&xid=<SSO User Id>\",\"id\":19844}],\"fpc\":\"ade1eb41-40a7-4937-9179-86ed1641f77e-10otg~1\"},{\"snippet\":\"\",\"adSlot\":\"208039\",\"section\":\"0\",\"position\":\"2\",\"ip\":\"223.165.29.225\",\"success\":-1,\"cs\":[{\"c\":\"http:\/\/ads.yahoo.com\/cms\/v1?esig=2~0e5920937f6aadb48bff63caeaefd5a0b961c753&nwid=1117471&sigv=1\",\"id\":16116},{\"c\":\"http:\/\/ade.clmbtech.com\/uid\/sync.htm?pid=19844&xid=<SSO User Id>\",\"id\":19844}],\"fpc\":\"ade1eb41-40a7-4937-9179-86ed1641f77e-10otg~1\"},{\"snippet\":\"\",\"adSlot\":\"208038\",\"section\":\"0\",\"position\":\"1\",\"ip\":\"223.165.29.225\",\"success\":-1,\"cs\":[{\"c\":\"http:\/\/ads.yahoo.com\/cms\/v1?esig=2~0e5920937f6aadb48bff63caeaefd5a0b961c753&nwid=1117471&sigv=1\",\"id\":16116},{\"c\":\"http:\/\/ade.clmbtech.com\/uid\/sync.htm?pid=19844&xid=<SSO User Id>\",\"id\":19844}],\"fpc\":\"ade1eb41-40a7-4937-9179-86ed1641f77e-10otg~1\"},{\"snippet\":\"\",\"adSlot\":\"208039\",\"section\":\"0\",\"position\":\"3\",\"ip\":\"223.165.29.225\",\"success\":-1,\"cs\":[{\"c\":\"http:\/\/ads.yahoo.com\/cms\/v1?esig=2~0e5920937f6aadb48bff63caeaefd5a0b961c753&nwid=1117471&sigv=1\",\"id\":16116},{\"c\":\"http:\/\/ade.clmbtech.com\/uid\/sync.htm?pid=19844&xid=<SSO User Id>\",\"id\":19844}],\"fpc\":\"ade1eb41-40a7-4937-9179-86ed1641f77e-10otg~1\"}]")
</code></pre>
| <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~0e5920937f6aadb48bff63caeaefd5a0b961c753&nwid=1117471&sigv=1"
id:16116
__proto__:Object.......
</code></pre>
|
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 are the weeks of year and the values are the strings I want, but I can't figure out how to generate that programatically.</p>
<pre><code>library(tidyverse)
library(lubridate)
holiday_dates = c(
"2016-01-01",
'2016-01-18',
'2016-02-15',
'2016-05-08',
'2016-05-30',
'2016-06-19',
'2016-07-04',
'2016-09-16',
'2016-10-10',
'2016-11-11',
'2016-11-24',
'2016-12-25'
)
holiday_names = c(
'New Years Day',
'Martin Luther King Day',
'Presidents Day',
'Mothers Day',
'Memorial Day',
'Fathers Day',
'Independence Day',
'Labor Day',
'Columbus Day',
'Veterans Day',
'Thanksgiving',
'Christmas Day'
)
holidays = data.frame(Date = as.Date(holiday_dates), Holiday = holiday_names) %>%
mutate(WeekOfYear = week(Date))
# can't figure out how to make this a list with names generates from the WeekOfYear column
holiday_labels = data.frame(WeekOfYear = seq(1,52)) %>%
left_join(holidays) %>%
.$Holiday
my_data %>%
ggplot(aes(x=WeekOfYear, y=Gross, group=WeekOfYear)) +
geom_line() +
scale_x_discrete(
names = holiday_labels,
na.value = ""
)
</code></pre>
| <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 as your data.</li>
</ul>
<p>For example:
</p>
<pre><code>data_frame(WeekOfYear = 1:52, Gross = rnorm(52)) %>%
ggplot(aes(x = WeekOfYear, y = Gross)) +
geom_line() +
scale_x_continuous(
labels = holiday_names,
breaks = week(as.Date(holiday_dates))
) +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
</code></pre>
<p><img src="http://i.imgur.com/KuAumjV.png" alt=""></p>
<p>Note that I also rotated the x-axis labels to make it readable.</p>
|
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( x= "b",y="a",data=df )
</code></pre>
<p>i get </p>
<p><a href="http://i.stack.imgur.com/7mzYW.png" rel="nofollow"><img src="http://i.stack.imgur.com/7mzYW.png" alt="enter image description here"></a></p>
<p>i write orient </p>
<pre><code>sns.boxplot( x= "c",y="a",data=df , orient = "v")
</code></pre>
<p>and get</p>
<pre><code>TypeError: unsupported operand type(s) for /: 'str' and 'int'
</code></pre>
<p>but </p>
<pre><code>sns.boxplot( x= "c",y="a",data=df , orient = "h")
</code></pre>
<p>works coreect!
what's wrong?</p>
<pre><code>TypeError Traceback (most recent call last)
<ipython-input-16-5291a1613328> in <module>()
----> 1 sns.boxplot( x= "b",y="a",data=df , orient = "v")
C:\Program Files\Anaconda3\lib\site-packages\seaborn\categorical.py in boxplot(x, y, hue, data, order, hue_order, orient, color, palette, saturation, width, fliersize, linewidth, whis, notch, ax, **kwargs)
2179 kwargs.update(dict(whis=whis, notch=notch))
2180
-> 2181 plotter.plot(ax, kwargs)
2182 return ax
2183
C:\Program Files\Anaconda3\lib\site-packages\seaborn\categorical.py in plot(self, ax, boxplot_kws)
526 def plot(self, ax, boxplot_kws):
527 """Make the plot."""
--> 528 self.draw_boxplot(ax, boxplot_kws)
529 self.annotate_axes(ax)
530 if self.orient == "h":
C:\Program Files\Anaconda3\lib\site-packages\seaborn\categorical.py in draw_boxplot(self, ax, kws)
463 positions=[i],
464 widths=self.width,
--> 465 **kws)
466 color = self.colors[i]
467 self.restyle_boxplot(artist_dict, color, props)
C:\Program Files\Anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, *args, **kwargs)
1816 warnings.warn(msg % (label_namer, func.__name__),
1817 RuntimeWarning, stacklevel=2)
-> 1818 return func(ax, *args, **kwargs)
1819 pre_doc = inner.__doc__
1820 if pre_doc is None:
C:\Program Files\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in boxplot(self, x, notch, sym, vert, whis, positions, widths, patch_artist, bootstrap, usermedians, conf_intervals, meanline, showmeans, showcaps, showbox, showfliers, boxprops, labels, flierprops, medianprops, meanprops, capprops, whiskerprops, manage_xticks, autorange)
3172 bootstrap = rcParams['boxplot.bootstrap']
3173 bxpstats = cbook.boxplot_stats(x, whis=whis, bootstrap=bootstrap,
-> 3174 labels=labels, autorange=autorange)
3175 if notch is None:
3176 notch = rcParams['boxplot.notch']
C:\Program Files\Anaconda3\lib\site-packages\matplotlib\cbook.py in boxplot_stats(X, whis, bootstrap, labels, autorange)
2036
2037 # arithmetic mean
-> 2038 stats['mean'] = np.mean(x)
2039
2040 # medians and quartiles
C:\Program Files\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py in mean(a, axis, dtype, out, keepdims)
2883
2884 return _methods._mean(a, axis=axis, dtype=dtype,
-> 2885 out=out, keepdims=keepdims)
2886
2887
C:\Program Files\Anaconda3\lib\site-packages\numpy\core\_methods.py in _mean(a, axis, dtype, out, keepdims)
70 ret = ret.dtype.type(ret / rcount)
71 else:
---> 72 ret = ret / rcount
73
74 return ret
TypeError: unsupported operand type(s) for /: 'str' and 'int'
</code></pre>
| <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 boxplots
sns.boxplot(x="b", y="a", data=df, orient='h')
# vertical boxplots
sns.boxplot(x="a", y="b", data=df, orient='v')
</code></pre>
<p>Mixing up the columns will cause seaborn to try to calculate the summary statistics of the boxes on categorial data, which is bound to fail.</p>
|
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 first:</p>
<p>(The same number cannot be used twice in one triple, but can be used by all other triples)</p>
<p>For example, <code>[3, 6, 18]</code> is one because <code>18</code> goes evenly into <code>6</code> which goes evenly into <code>3</code>.</p>
<p>So given <code>[1, 2, 3, 4, 5, 6]</code> it should find:</p>
<pre><code>[1, 2, 4] [1, 2, 6] [1, 3, 6]
</code></pre>
<p>and return <code>3</code> (the number of triples it found)</p>
<h2>What I've tried:</h2>
<p>I made a couple of functions that work but are not efficient enough. Is there some math concept I don't know about that would help me find these triples faster? A module with a function that does better? I don't know what to search for...</p>
<pre><code>def foo(q):
l = sorted(q)
ln = range(len(l))
for x in ln:
if len(l[x:]) > 1:
for y in ln[x + 1:]:
if (len(l[y:]) > 0) and (l[y] % l[x] == 0):
for z in ln[y + 1:]:
if l[z] % l[y] == 0:
ans += 1
return ans
</code></pre>
<p>This one is a bit faster:</p>
<pre><code>def bar(q):
l = sorted(q)
ans = 0
for x2, x in enumerate(l):
pool = l[x2 + 1:]
if len(pool) > 1:
for y2, y in enumerate(pool):
pool2 = pool[y2 + 1:]
if pool2 and (y % x == 0):
for z in pool2:
if z % y == 0:
ans += 1
return ans
</code></pre>
<p>Here's what I've come up with with help from y'all but I must be doing something wrong because it get's the wrong answer (it's really fast though):</p>
<pre><code>def function4(numbers):
ans = 0
num_dict = {}
index = 0
for x in numbers:
index += 1
num_dict[x] = [y for y in numbers[index:] if y % x == 0]
for x in numbers:
for y in num_dict[x]:
for z in num_dict[y]:
print(x, y, z)
ans += 1
return ans
</code></pre>
<p>(<code>39889</code> instead of <code>40888</code>) - oh, I accidentally made the index var start at 1 instead of 0. It works now.</p>
<h1>Final Edit</h1>
<p>I've found the best way to find the number of triples by reevaluating what I needed it to do. This method doesn't actually find the triples, it just counts them.</p>
<pre><code>def foo(l):
llen = len(l)
total = 0
cache = {}
for i in range(llen):
cache[i] = 0
for x in range(llen):
for y in range(x + 1, llen):
if l[y] % l[x] == 0:
cache[y] += 1
total += cache[x]
return total
</code></pre>
<p>And here's a version of the function that explains the thought process as it goes (not good for huge lists though because of spam prints):</p>
<pre><code>def bar(l):
list_length = len(l)
total_triples = 0
cache = {}
for i in range(list_length):
cache[i] = 0
for x in range(list_length):
print("\n\nfor index[{}]: {}".format(x, l[x]))
for y in range(x + 1, list_length):
print("\n\ttry index[{}]: {}".format(y, l[y]))
if l[y] % l[x] == 0:
print("\n\t\t{} can be evenly diveded by {}".format(l[y], l[x]))
cache[y] += 1
total_triples += cache[x]
print("\t\tcache[{0}] is now {1}".format(y, cache[y]))
print("\t\tcount is now {}".format(total_triples))
print("\t\t(+{} from cache[{}])".format(cache[x], x))
else:
print("\n\t\tfalse")
print("\ntotal number of triples:", total_triples)
</code></pre>
| <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 grater than it, then every triple of numbers is a valid solution so just to print out all the solutions is going to be just as slow as what you are doing now.</p>
<p>If you have a lower "density" of numbers that divide other numbers, one thing you can do to speed things up is to search for pairs of numbers instead of triples. This will take time that is only O(N^2), meaning the running time goes up by 4 times when you double the length of the input list. Once you have a list of pairs of numbers you can use it to build a list of triples.</p>
<pre><code># For simplicity, I assume that a number can't occur more than once in the list.
# You will need to tweak this algorithm to be able to deal with duplicates.
# this dictionary will map each number `n` to the list of other numbers
# that appear on the list that are multiples of `n`.
multiples = {}
for n in numbers:
multiples[n] = []
# Going through each combination takes time O(N^2)
for x in numbers:
for y in numbers:
if x != y and y % x == 0:
multiples[x].append(y)
# The speed on this last step will depend on how many numbers
# are multiples of other numbers. In the worst case this will
# be just as slow as your current algoritm. In the fastest case
# (when no numbers divide other numbers) then it will be just a
# O(N) scan for the outermost loop.
for x in numbers:
for y in multiples[x]:
for z in multiples[y]:
print(x,y,z)
</code></pre>
<p>There might be even faster algorithms, that also take advantage of algebraic properties of division but in your case I think a O(N^2) is probably going to be fast enough.</p>
|
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);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
Writer writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(query);
writer.flush();
writer.close();
/*conn.addRequestProperty("username", strings[0]);
conn.addRequestProperty("duration", strings[1]);
conn.addRequestProperty("distance", strings[2]);*/
Log.v(TAG, strings[0] + " - " + strings[1] + " - " + strings[2]);
//conn.connect();
} catch(Exception e) {
Log.e(TAG, "exception", e);
}
return null;
}
</code></pre>
<p>but the request just doesn't take effect on the server... on the server I should see the data sent, but I don't see them</p>
<p>I also tried this:</p>
<pre><code>curl -XPOST --data "username=duri&duration=600&distance=555" http://someurl.com/
</code></pre>
<p>and it works... what could be the problem?</p>
| <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;
HttpURLConnection urlConnection = null;
try {
url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
String data = URLEncoder.encode("userName", "UTF-8")
+ "=" + URLEncoder.encode(userName, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "="
+ URLEncoder.encode(password, "UTF-8");
urlConnection.connect();
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(data);
wr.flush();
stream = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"), 8);
String result = reader.readLine();
return result;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
Log.i("Result", "SLEEP ERROR");
}
return null;
}
</code></pre>
<p>Hope this helps. :)</p>
|
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: .touchUpInside )
}
func buttonWasPressed()
{
// Do something
}
</code></pre>
<p>I personally tend to make selectors private/fileprivate for encapsulation reasons. Hence, the above <code>buttonWasPressed</code> method would be defined as:</p>
<pre><code>@objc private func buttonWasPressed()
{
// Do something
}
</code></pre>
<p>I am curious why that is the case? Am I missing something here?</p>
<p>Thank you for your help in advance. I apologise if my question seems too obvious.</p>
| <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 access specifier, you are making a claim that isn't true. That's why I don't do it. YMMV.</p>
|
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 "Appearence" (specially the non-client area) without customizing every single one of them.
I've done some researches (obviously) and I found something that resembles perfectly what I'm trying to do: <a href="http://mahapps.com/" rel="nofollow">MahApps.Metro</a> Template.
But I don't want to use some third party code because I like to have control all over my application and I want to customize what I want by myself. So I'd like to know what is the correct (and the best, maybe) way to do so. I've read plenty of posts about <code>Window</code> customizing but I didn't find anything that explained how to do that in <strong>that</strong> way.</p>
<p>I hope to have well-explained myself and I thank you all in advance for the help!</p>
| <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>
</ul>
<p>There are several videos available on youtube on Expression Blend for making custom UI in XAML. You can try that.</p>
|
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 efficient algorithm? My problem is 2D.</p>
| <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", however we assign points, these triangles can't be included. The rest are candidates. For each candidate, go to its neighbours, and try to grow it. So we get roughly 3 * the number of triangles as composite quad candidates, and each successfully grown triangles is no longer a candidate, but still not "bad". All the quads must be convex. If a triangle fails to grow at all, it is still
a "candidate", but it is "finished". As soon as a better candidate emerges,
it is no longer a candidate and becomes "bad", no successful set may include
it.</p>
<p>Now for the next stage, it's the same basic idea, try to unite with all
possible neighbours, and eliminate from the candidate list anything you
absorb. If you can't grow successfully, you become "finished". But
you can't just unite with anybody, if not convex, you have to add
extra triangles to become convex. </p>
<p>Eventually all of our candidates will either be absorbed or "finished",and we have a winner.</p>
<p>The question is whether this algorithm will create an exponential explosion of candidates or if we can eliminate them quickly enough to prevent that happening. I don't know the answer to that. But I think that if you try to unite with the larger neighbours first, you can pretty quickly eliminate most of the possible sub-sets.</p>
|
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. 3 columns (name, age,gender). I want to load each of the text files into R and merge them into 1 data frame.</p>
<p>So far I have:</p>
<pre><code>txt_files = list.files(path='names/', pattern="*.txt");
do.call("rbind", lapply(txt_files, as.data.frame))
</code></pre>
<p>This has created a list of the file names but not the contents of the files. I'm able to read in the content of one file and create a data frame but I can't seem to do it for multiple files at once. If anyone could offer any help I'd really appreciate it as I'm completely stuck!</p>
<p>Thanks in advance!</p>
| <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 <- lapply(txt_files_ls, function(x) {read.table(file = x, header = T, sep =",")})
# Combine them
combined_df <- do.call("rbind", lapply(txt_files_df, as.data.frame))
</code></pre>
<p>At least that worked for me when I created a couple of sample text files.
Hope that helps.</p>
|
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, what am I doing wrong?</p>
<pre><code>public class ArrayOrdered {
public static boolean isArrayInSortedOrder(int[] array, int index)
{
boolean b;
int a1;
int a2;
if(array.length == 1 || index == 1){//base case
b=true;
}else{
b=false;
a1 = array[index - 1];
a2 = array[index - 2];
if((a1 > a2)){//ordered
isArrayInSortedOrder(array, index - 1);
}
}
return b;
}
public static void main(String[] args) {
int index=20;
int[] array={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
boolean bool = isArrayInSortedOrder(array, index);
if(bool)
System.out.println("Array ordered");
if(!bool)
System.out.println("Array NO ordered");
}
}
</code></pre>
| <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[index - 1];
int a2 = array[index - 2];
if (a1 > a2) {
return isArrayInSortedOrder(array, index - 1);
}
return false;
}
</code></pre>
|
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>
<ol>
<li><p>Calling my Controller's Action Method Get Data</p>
<pre><code><script>
$(document).ready(function () {
$.get("@Url.Action("GetData","Driver")",function(data){
$("#dataForSecond").html(data);
alert("Second ActionResult");
});
});
</code></pre>
<p></p></li>
<li><p>Get Data Method in my Controller just returns:</p>
<pre><code> public ActionResult GetData()
{
logger.AddLog("INTO 2nd Action Method");
var secondData = "I m Dummy";
//System.Threading.Thread.Sleep(500);
logger.AddLog("Setting loggedInAgent Value Again");
// ViewBag.loggedInAgents = "11";
return Json(secondData, JsonRequestBehavior.AllowGet);
}
</code></pre></li>
<li><p>For testing I did following in Client side but no REFRESHING took place, only a POP up as before. Whats going on with my code, I have no clue.</p>
<pre><code>$(function () {
var refreshInterval = 5000;
var url="@Url.Action("GetData","Driver")";
setInterval(function () {
$("#View1").load(url);
}, refreshInterval);
</code></pre></li>
</ol>
| <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",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error');
},
success: function (data) {
alert('ok');
}
});
[HttpGet]
public async Task<JsonResult> List(int nrRecs)
{
var product = db.products.Take(4);
return Json(await product.ToListAsync());
}
</code></pre>
|
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 like 1 this gives me 1 instead of 1.0. How can I get a decimal place even for exact numbers (1.0 instead of 1)?</p>
| <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 this method:</p>
<pre><code>star = stargazer(attitude, digits=1, digits.extra=1)
star = gsub("& ([0-9]+) ", "& \\1\\.0 ", star)
cat(star, sep = "\n")
# % Table created by stargazer v.5.2 by Marek Hlavac, Harvard University. E-mail: hlavac at fas.harvard.edu
# % Date and time: Sat, Oct 08, 2016 - 8:11:26 PM
# \begin{table}[!htbp] \centering
# \caption{}
# \label{}
# \begin{tabular}{@{\extracolsep{5pt}}lccccc}
# \\[-1.8ex]\hline
# \hline \\[-1.8ex]
# Statistic & \multicolumn{1}{c}{N} & \multicolumn{1}{c}{Mean} & \multicolumn{1}{c}{St. Dev.} & \multicolumn{1}{c}{Min} & \multicolumn{1}{c}{Max} \\
# \hline \\[-1.8ex]
# rating & 30.0 & 64.6 & 12.2 & 40.0 & 85.0 \\
# complaints & 30.0 & 66.6 & 13.3 & 37.0 & 90.0 \\
# privileges & 30.0 & 53.1 & 12.2 & 30.0 & 83.0 \\
# learning & 30.0 & 56.4 & 11.7 & 34.0 & 75.0 \\
# raises & 30.0 & 64.6 & 10.4 & 43.0 & 88.0 \\
# critical & 30.0 & 74.8 & 9.9 & 49.0 & 92.0 \\
# advance & 30.0 & 42.9 & 10.3 & 25.0 & 72.0 \\
# \hline \\[-1.8ex]
# \end{tabular}
# \end{table}
</code></pre>
<p>In this example, the pattern "& ([0-9]+) " looks for "& " followed by a string of digits, followed by a space. It then replaces this with "& ", the same group of digits it found (using //1), a period (//. because periods must be escaped, as they are special characters in regex), a decimal zero and a space.</p>
<p>Some different summary formats produced by stargazer could possibly have other things you may need to include in the search string, such as numbers followed by a character other than a space (e.g. a comma). Or maybe numbers that aren't preceded by an <code>&</code> might need replacing in some instances.</p>
<p>In any case the general approach is the same.</p>
|
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</code> before Travis can push to Heroku.</p>
<p><strong>What I want to do</strong></p>
<blockquote>
<p>How do I pass in my heroku credentials to Travis as requested without the >risk of putting it on version control?</p>
</blockquote>
<p>Here is the Build on Travis: <a href="https://travis-ci.org/AfolabiOlaoluwa/LawVille/jobs/166099588" rel="nofollow">https://travis-ci.org/AfolabiOlaoluwa/LawVille/jobs/166099588</a></p>
<p><strong>.travis.yml</strong></p>
<pre><code>language: ruby
rvm:
- 2.2.4
env:
global:
- secure: {{ I have my travis encrypted key here }}
- secure: {{ I another travis encrypted key here }}
- DB=sqlite
- DB=mysql
- DB=postgresql
- secure: {{ I have another travis encrypted key here }}
deploy:
provider: heroku
api_key:
secure: {{ I have HEROKU API KEY encrypted by travis here }}
script:
- RAILS_ENV=test bundle exec rake db:migrate --trace
- bundle exec rake db:test:prepare
before_script:
- mysql -e 'create database strano_test'
- psql -c 'create database strano_test' -U postgres
after_success:
- gem install heroku
- yes | ruby ./config/initializers/travis_deployer.rb
- git remote add heroku git@heroku.com:lawville.git
- heroku keys:clear
- yes | heroku keys:add
- git push heroku master
</code></pre>
| <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 href="https://docs.travis-ci.com/user/deployment/heroku" rel="nofollow">here</a></p>
<p>If you need to store your credentials to be used on Travis, you can add secure environment to Travis. Go to <code>More options > Settings</code> there you can add the credentials as environment variables. Just make sure <code>Display value in build log</code> is set as off</p>
|
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 error as well. </p>
<p>Here is where the kCircleHeightBackground cgfloat is set
`open class SCLAlertView: UIViewController {</p>
<pre><code>public struct SCLAppearance {
let kDefaultShadowOpacity: CGFloat
let kCircleHeightBackground: CGFloat
let kCircleTopPosition: CGFloat
let kCircleBackgroundTopPosition: CGFloat
let kCircleHeight: CGFloat
let kCircleIconHeight: CGFloat
let kTitleTop:CGFloat
let kTitleHeight:CGFloat
let kWindowWidth: CGFloat
var kWindowHeight: CGFloat
var kTextHeight: CGFloat
let kTextFieldHeight: CGFloat
let kTextViewdHeight: CGFloat
let kButtonHeight: CGFloat
let contentViewColor: UIColor
let contentViewBorderColor: UIColor
let titleColor: UIColor
</code></pre>
<p>`</p>
<p>and then i'm getting an error at "appearance.kCircleHeightBackground"</p>
<pre><code>var appearance: SCLAppearance!
// UI Colour
var viewColor = UIColor()
// UI Options
open var iconTintColor: UIColor?
open var customSubview : UIView?
// Members declaration
var baseView = UIView()
var labelTitle = UILabel()
var viewText = UITextView()
var contentView = UIView()
// "I get an error here at appearance.kCircleHeightBackground"__________var circleBG = UIView(frame:CGRect(x:0, y:0, width: appearance.kCircleHeightBackground, height: appearance.kCircleHeightBackground))
var circleView = UIView()
var circleIconView : UIView?
var duration: TimeInterval!
var durationStatusTimer: Timer!
var durationTimer: Timer!
var dismissBlock : DismissBlock?
fileprivate var inputs = [UITextField]()
fileprivate var input = [UITextView]()
internal var buttons = [SCLButton]()
fileprivate var selfReference: SCLAlertView?
public init(appearance: SCLAppearance) {
self.appearance = appearance
super.init(nibName:nil, bundle:nil)
setup()
}
</code></pre>
<p><a href="http://i.stack.imgur.com/qh83Z.png" rel="nofollow">Image of error i get</a></p>
| <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 your <code>setup()</code>-method.</p>
|
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 of the authentications that I found from the web requires login but our website doesn't so I can't really use token bearer.</p>
<p>What are the list of things that I must implement or consider? are there any threats and how do I get around them? </p>
| <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 here <a href="http://bitoftech.net/2014/07/16/enable-oauth-refresh-tokens-angularjs-app-using-asp-net-web-api-2-owin/" rel="nofollow">http://bitoftech.net/2014/07/16/enable-oauth-refresh-tokens-angularjs-app-using-asp-net-web-api-2-owin/</a> (clientId,ClientSecret part)</p>
<p>Hope this helps.</p>
|
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; i++)
{
static_cast<BaseObject*>((void*)(int(p) + sizeof(T) * i))->OnDestroy();
}
delete [] p;
}
};
</code></pre>
<p>And let's assume that it works as intended (it's a simplified version, written now without the check but basically you know what this code should do).<br>
With this part I don't have a problem. However, check this out:</p>
<pre><code>class AActor
: public BaseObject
{
public:
virtual void OnDestroy() override
{
// some code here
}
};
template <typename T>
class SimplifiedHolder
{
protected:
std::shared_ptr<T> m_shared;
std::size_t m_size;
public:
// Some not important code here
// WE ASSUME HERE THAT IT ALWAYS HOLDS ARRAY
// sizeOfArray always > 1
template <typename U>
SimplifiedHolder(U *ptr, std::size_t sizeOfArray)
: m_size(sizeOfArray)
{
m_shared = std::shared_ptr<T>(ptr,
std::bind(&myArrayDeleter<U>(), std::placeholders::_1, m_size));
}
// And now as we initialize our shared_ptr with template
// we can check if it is exactly of type "U"
template <typename U>
bool IsExactlyOfType()
{
if(!m_shared)
return false;
return ((void*)std::get_deleter<myArrayDeleter<U>>(m_shared)) != nullptr;
}
};
</code></pre>
<p>However, the method <code>IsExactlyOfType</code> isn't working. That's because I initialized <code>shared_ptr</code> with <code>std::bind</code>. <code>std::get_deleter</code> always returns <code>nullptr</code> because the wrong type is specified in the template. I don't know what type to pass. I tried also with non-array code in which <code>myDeleter</code> is a functor with only one argument and it works perfectly with code like this:</p>
<pre><code>template <typename U>
bool IsExactlyOfType()
{
if(!m_shared)
return false;
return ((void*)std::get_deleter<myDeleter<U>>(m_shared) != nullptr;
}
</code></pre>
<p>I know I could go with <code>typeid(U) == typeid(*m_shared.get())</code> but this is not what I want. I have much more complicated code and in that case only this method is good.</p>
<p>Can a more experienced programmer tell me what type to specify to <code>std::get_deleter</code>?</p>
| <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>std::_Binder<std::_Unforced,grim::impl::TObjectArrayDeleter<APlayer>,std::_Ph<1> const &,unsigned int &> &
</code></pre>
<p>In function:</p>
<pre><code>std::_Binder<std::_Unforced,grim::impl::TObjectArrayDeleter<APlayer>,std::_Ph<1> const &,unsigned int const &> *
</code></pre>
<p>Take a look at the end - it appended additional const. I needed to change it manually, so now my code looks like this:</p>
<pre><code>using D = std::_Binder<std::_Unforced,grim::impl::TObjectArrayDeleter<U>,
std::_Ph<1> const &,unsigned int &>;
return ((void*)std::get_deleter<D>(m_shared)) != nullptr;
</code></pre>
|
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) Kittens, 2) Puppies, 3) Sloths, and 4) Elephants. I used pairwise comparisons (i.e., showing people two random pictures of the animal and asking them to select the cutest one) to obtain these rankings. I also have the full amount of comparisons within data sets (i.e., all puppies were compared with each other in the puppy data set).</p>
<p>I'm now trying to merge the data sets together to produce a global ranking of the cutest animal. </p>
<p>The main issue of relative ranking is that the cutest animal in one set may not necessarily be the cutest in the other set. For example, let's say that baby elephants are considered to be less than attractive, and so, the least cutest kitten will always beat the cutest elephant. How should I get around this problem? </p>
<p>I am thinking of doing a few cross comparisons across data sets (Kittens vs Elephants, Puppies vs Kittens, etc) to create some sort of base importance, but this may become problematic as I add on the number of animals and the type of animals. </p>
<p>I was also thinking of looking further into filling in sparse matrices, but I think this is only applicable towards one data set as opposed to comparing across multiple data sets?</p>
| <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 same number of comparisons,</li>
<li>you don't need to do comparison inside specific data set only (let all animals 'play' against all other animals, then if you need ranking for one dataset, just use global ranking ignoring animals from others).</li>
</ul>
<p>Using <em>rankade</em> (here's a <a href="https://rankade.com/ree#ranking-system-comparison" rel="nofollow">comparison</a> with aforementioned ranking systems and Microsoft's <em>TrueSkill</em>) you can record outputs for 2+ items as well, while with Elo or Glicko you don't. It's extremely messy and difficult for people to rank many items, but a small multiple comparison (e.g. 3-5 animals) should be suitable and useful, in your work.</p>
|
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 whole thing like in:</p>
<pre><code>shape(shape, mouseX, mouseY, 600, 600);//parameters: shape, x-coor, y-coor, new width, new height;
</code></pre>
<p>and, to change the color of each element (just like the line above).
The code:</p>
<pre><code>PShape shape;
int noOfChilds;
/***************************************************************************/
void setup()
{
size(1000, 600);
shape = loadShape("a.svg");
noOfChilds = shape.getChildCount();
print(noOfChilds);
shapeMode(CENTER);
}
/***************************************************************************/
void draw()
{
background(100);
shape.enableStyle();
stroke(255);
shape(shape, mouseX, mouseY, 600, 600);
//
shape.disableStyle();
for(int i = 0; i < noOfChilds; i++)
{
pushMatrix();
translate(300, 300);
PShape ps = shape.getChild(i);
fill(random(255),random(255),random(255));
shape(ps, 0, 0);//shape(ps, 0, 0, anyValue, anyValue); seems to fail :'(
popMatrix();
}
}
/***************************************************************************/
</code></pre>
| <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() {
background(204);
shape(s);
}
void mousePressed() {
// Shrink the shape 90% each time the mouse is pressed
s.scale(0.9);
}
</code></pre>
<p>Increases or decreases the size of a shape by expanding and
contracting vertices. Shapes always scale from the relative origin of
their bounding box. Scale values are specified as decimal percentages.
For example, the method call scale(2.0) increases the dimension of a
shape by 200%. Subsequent calls to the method multiply the effect. For
example, calling scale(2.0) and then scale(1.5) is the same as
scale(3.0). This transformation is applied directly to the shape; it's
not refreshed each time draw() is run.</p>
</blockquote>
<p>You could also use the more general <code>scale()</code> function. More info can be found in <a href="https://processing.org/reference/scale_.html" rel="nofollow">the reference</a>.</p>
<p>Note that you might also have to adjust where you draw your shapes, potentially using the <code>translate()</code> function.</p>
|
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><a href="http://i.stack.imgur.com/24YXH.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/24YXH.jpg" alt="enter image description here"></a></p>
<ul>
<li>Case 1: Only one button is visible. Align is center.</li>
<li>Case 2: Displaying another button. Two buttons are visible.</li>
<li>Case 3: Displaying an OFF button. Three buttons are visible.</li>
<li>Case 4: Hiding ON and Close. OFF is center.</li>
<li><p>Case 5: A fourth new button is added to the stack/page.</p>
<pre><code>//Buttons
private int startX { get; set; }
private int width { get; set; }
private int gap { get; set; }
private Boolean showOnBtn { get; set; }
private Boolean showOffBtn { get; set; }
private Boolean showCloseBtn { get; set; }
public Buttons(int startX, int width, int gap)
{
this.startX = startX;
this.width = width;
this.gap = gap;
}
</code></pre></li>
</ul>
<p>Example of my if else attempt:</p>
<pre><code> //Page
width = 600px;
Button onBtn = new Button();
Private void Update(){
if (showOnBtn){
onBtn.startX = 242;
onBtn.width = 116;
onBtn.gap = 0;
if (showOffBtn || showCloseBtn) {
onBtn.startX = 126;
onBtn.width = 116;
onBtn.gap = 113;
etc etcâ¦
}
}
}
</code></pre>
| <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
break;
//OFF
case 3:
//set UI elements to apropriate states here
break;
//ON/CLOSE/OFF/NEW
case 4:
//set UI elements to apropriate states here
break;
//ON
default:
//set UI elements to apropriate states here
break;
}
</code></pre>
<p>you'll just need to figure out where you are setting the "caseDecider" variable, and where you are placing the switch. Switches are often a better option than if/else because of readability, flexibility, and requiring less typing.</p>
<p>EDIT: if you want to simplify setting each of your 5 states, write a function that sets each state. Something like: </p>
<pre><code>private void setState1()
{
onBtn.startX = 242;
onBtn.width = 116;
onBtn.gap = 0;
}
</code></pre>
<p>for each state. Then you just call that function whenever you want to set that state.</p>
|
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(df)
for title in titles:
if title == titles[0]:
continue
df.plot(titles[0],title, linestyle='--', marker='o')
plt.savefig(title+'.png')
</code></pre>
<p>But if, instead, data was missing <code>Column1</code> like:</p>
<pre><code>Column2; Column3
4; 6
2; 6
3; 8
1; 1
4; 2
</code></pre>
<p>How do I plot it?</p>
<p>May be, something like <code>df.plot(title, linestyle='--', marker='o')</code>?</p>
| <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 2
</code></pre>
<p>so if you want to plot col 2 as X axis and 3 as Y axis you could do something like:</p>
<pre><code>df.set_index('Column2')['Column3'].plot()
</code></pre>
|
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 to upload file. <br /></p>
<p>But when i'm trying to execute restTemplate.exchange() i am getting error:
"Caused by: java.lang.ClassCastException: org.springframework.core.io.ByteArrayResource cannot be cast to java.lang.String
".</p>
<p>Here is my class:</p>
<pre class="lang-java prettyprint-override"><code>@Data
@Service
class StackOverflowComAcceptor implements JobOfferService {
private final static String BASE_URL = "http://stackoverflow.com";
private final ConnectionService2 connectionService2;
private final StackOverflowComFactory stackOverflowComFactory;
private final RestTemplate restTemplate;
@Autowired
private CVProvider cvProvider;
@Override
@SneakyThrows
public void accept(JobOffer jobOffer) {
//List<Connection.KeyVal> templateDataEntries = stackOverflowComFactory.create();
ConnectionRequest connectionRequest = ConnectionRequest
.builder()
//url is in joboffer
.url("http://stackoverflow.com/jobs/apply/110247")
.method(Connection.Method.GET)
.data(new ArrayList<Connection.KeyVal>() )
.build();
ConnectionResponse submit1 = connectionService2.submit(connectionRequest);
Document document = submit1.getDocument();
String csrf = extractCSRF(document);
String cvurl = "http://stackoverflow.com/jobs/apply/upload-resume";
//String cvurl = "http://stackoverflow.com/jobs/apply/upload-resume?jobId=110247&fkey=" + csrf;
InputStream inputStream = cvProvider.asInputStream();
byte[] bytes = IOUtils.toByteArray(inputStream);
Map<String, String> uriVariables = new HashMap<>();
uriVariables.put("fkey", csrf);
uriVariables.put("jobId", "110247");
HttpHeaders partHeaders = new HttpHeaders();
partHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
ByteArrayResource byteArrayResource = new ByteArrayResource(bytes, "test.pdf");
MultiValueMap<String, Object> data = new LinkedMultiValueMap<>();
data.add("qqfile", byteArrayResource);
HttpEntity<MultiValueMap<String, Object>> requestEntity =
new HttpEntity<>(data, partHeaders);
ByteArrayHttpMessageConverter byteArrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
// byteArrayHttpMessageConverter.setSupportedMediaTypes(Arrays.asList(new MediaType[]{MediaType
// .APPLICATION_OCTET_STREAM}));
FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
formHttpMessageConverter.setSupportedMediaTypes(Arrays.asList(
new MediaType[]{MediaType.APPLICATION_OCTET_STREAM}));
//restTemplate.getMessageConverters().add(byteArrayHttpMessageConverter);
restTemplate.getMessageConverters().add(formHttpMessageConverter);
ResponseEntity<Object> model = restTemplate.exchange(cvurl, HttpMethod.POST, requestEntity, Object.class ,
uriVariables);
System.out.println(model);
}
private String extractCSRF(Document document) {
String s = document.getElementsByTag("script").get(0).toString();
Pattern p = Pattern.compile("Careers.XSRF_KEY = \\\"([a-z0-9]{32})\\\""); // Regex for the value of the key
Matcher m = p.matcher(s);
String csrf = null;
while( m.find() )
{
csrf = m.group(1); // value only
}
System.out.println(csrf);
return csrf;
}
}
</code></pre>
<p>Here is my stacktrace:</p>
<pre class="lang-java prettyprint-override"><code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testStacka' defined in file [D:\WWW\Epomis\epomis\build\classes\main\net\elenx\epomis\service\com\stackoverflow\Test.class]: Invocation of init method failed; nested exception is java.lang.ClassCastException: org.springframework.core.io.ByteArrayResource cannot be cast to java.lang.String
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:751) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.4.1.BUILD-SNAPSHOT.jar:1.4.1.BUILD-SNAPSHOT]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761) ~[spring-boot-1.4.1.BUILD-SNAPSHOT.jar:1.4.1.BUILD-SNAPSHOT]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371) ~[spring-boot-1.4.1.BUILD-SNAPSHOT.jar:1.4.1.BUILD-SNAPSHOT]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) ~[spring-boot-1.4.1.BUILD-SNAPSHOT.jar:1.4.1.BUILD-SNAPSHOT]
at net.elenx.Epomis.main(Epomis.java:22) [main/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_74]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_74]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_74]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_74]
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) [idea_rt.jar:na]
Caused by: java.lang.ClassCastException: org.springframework.core.io.ByteArrayResource cannot be cast to java.lang.String
at org.springframework.http.converter.FormHttpMessageConverter.writeForm(FormHttpMessageConverter.java:292) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.http.converter.FormHttpMessageConverter.write(FormHttpMessageConverter.java:254) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.http.converter.FormHttpMessageConverter.write(FormHttpMessageConverter.java:89) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.web.client.RestTemplate$HttpEntityRequestCallback.doWithRequest(RestTemplate.java:849) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:617) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:588) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:507) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at net.elenx.epomis.service.com.stackoverflow.StackOverflowComAcceptor.accept(StackOverflowComAcceptor.java:99) ~[main/:na]
at net.elenx.epomis.service.com.stackoverflow.Test.afterPropertiesSet(Test.java:40) ~[main/:na]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1642) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1579) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
... 19 common frames omitted
Process finished with exit code 1
</code></pre>
<p>Any ideas how to solve the problem?</p>
| <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 as I click in the Word document, the API resumes and reads CustomXmlParts successfully.</p>
<p>Any work around this? I also tried to call context.document.getSelection to mimic cursor click, but did not help.</p>
<pre><code>Office.context.document.customXmlParts.getByNamespaceAsync("MyXmlTag", function (asyncResult) {
if (asyncResult.value.length > 0) {
asyncResult.value[0].getNodesAsync("/", function (asyncNodeResult) {
if (asyncNodeResult.status == Office.AsyncResultStatus.Failed) {
console.log(" Failed to read word document. " + JSON.stringify(asyncResult));
} else {
asyncNodeResult.value[0].getNodeValueAsync(function (result) {
if (result.status == Office.AsyncResultStatus.Failed) {
console.log(" getNodeValueAsync: Failed " + JSON.stringify(asyncResult));
}
else {
//result.valuse is xml data
}
});
}
});
}
else {
console.log(" CustomXML part is not found");
}
});
</code></pre>
<p>` </p>
| <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 the HTML/JS is finished loading), or is it in completely separate code? How is your code triggered?</li>
<li>Does the issue occur in all custom XML you have tried, or just specific custom XML?</li>
</ul>
|
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() -> Element? {
self.values = (
self.values.1,
self.values.0 + self.values.1
)
return self.values.0
}
}
var generator = FibonacciGenerator()
while let next = generator.next() {
if next > 10 {
break
}
print(next)
}
</code></pre>
<p>Why do we use <code>let</code> and not <code>var</code> in the <code>while</code> loop (before the next statement)?</p>
| <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="nofollow">this post</a>: "Projects not directly supported in this release", however have tried next command with no success:</p>
<pre><code>msbuild PathToMyProject.sqlproj /t:SqlSchemaCompare /p:SqlScmpFilePath=SomePath/ComparationConfiguration.scmp /p:target=PathToMyProject.sqlproj /p:Deploy="true"
</code></pre>
<p>and can't find the way how to do this. Is it ever possible?<br/>
From the other side it looks like I can compare database schema to dacpac file(compilation output of sqlproj) to get changes that are not present on database project, however for automation of database changes tracking it looks useless because each time I got some changes I need manually open related solution, do comparison, update target database project and then checking changes to repository</p>
| <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 = df[df['colName']==0 or df['colName']==1]
df = df[df['colName']==0 | df['colName']==1]
</code></pre>
<p>Any other ideas?</p>
| <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)].index
df = df.loc[indexer,:]
</code></pre>
|
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 a seed file with it. </p>
<p>Any ideas on the best way to create my seed files? </p>
<p>For example, should I create a reference the content from separate files? or should I just keep the text in one seed file? Would it be possible to show an example of a recommendation?</p>
| <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 name or by all file in certain directory.</p>
|
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 ('upload_link_secure')to upload the file to. Please can someone advise?</p>
<p>my HTML:</p>
<pre><code><form id="upload" action="'+upload_link_secure+'" method="PUT" enctype="multipart/form-data">
<input type="file" id="vidInput">
<button type="submit" id="submitFile" onclick="uploadMyVid(\''+upload_link_secure+'\')">Upload Video</button>
</form>
</code></pre>
<p>my javascript:</p>
<pre><code> var uploadMyVid = function(upload_link_secure){
var form = document.getElementById('upload')
// FETCH FILEIST OBJECTS
var vidFile = document.getElementById('vidInput').files;
var xmlhttp = new XMLHttpRequest;
xmlhttp.open('PUT', ); // NOT SURE HOW TO COMPLETE THIS LINE???
xmlhttp.send(vidFile);
}
</code></pre>
| <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="file" id="file">
<button type="submit">Upload Video</button>
</form>
</code></pre>
<p>js</p>
<pre><code>var form = document.getElementById("upload-form"),
actionPath = "";
formData = null;
form.addEventListener("submit", (e) => {
e.preventDefault();
formData = new FormData(form);
actionPath = form.getAttribute("action");
xhr.open("POST", actionPath);
xhr.send(formData);
}, false);
</code></pre>
|
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 "undefined is not an object(evaluating 'dataSource.rowIdentites'). </p>
<pre><code>import React,{Component} from 'react';
import { Text, View,StyleSheet,Image,TextInput,ListView} from 'react-native';
import axios from 'axios';
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1!==r2});
class WordList extends Component{
state = {albums: []}
componentdidMount(){
axios.get('https://rallycoding.herokuapp.com/api/music_albums')
.then(response => this.setState({albums:response.data}));
this.dataSource = ds.cloneWithRows(this.state.albums);
}
render() {
return (
<ListView
dataSource={this.state.dataSource}
renderRow={(rowData) => <Text>{rowData}</Text>}
/>
);
}
}
export default WordList;
</code></pre>
<p>I am able to get static lists to render perfectly, but when using a list from the Web is where I run into trouble. Please let me know where I am going wrong.</p>
<p>Thanks.</p>
| <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';
import axios from 'axios';
class WordList extends Component {
constructor (props) {
super(props)
this.state = {
albums: []
}
this.dataSource = new ListView.DataSource({rowHasChanged: (r1, r2) => r1!==r2});
}
componentdidMount(){
axios.get('https://rallycoding.herokuapp.com/api/music_albums')
.then(response => this.setState({albums:response.data}));
}
render() {
return (
<ListView
dataSource={this.dataSource.cloneWithRows(this.state.albums)}
renderRow={(rowData) => <Text>{rowData}</Text>}
/>
);
}
}
export default WordList;
</code></pre>
|
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 with y=1-y, which i obtain with:</p>
<pre><code>var data2 = data.map(function(el) {el.y = 1-el.y; return el});
data2[0]
Object {x: 1, y: 0.73, classifier: 1}
data2[1]
Object {x: 2, y: 0.12, classifier: 1}
</code></pre>
<p>which is the correct form that i want the data in. However the issue is i want to preserve the original data as well. Right now even data has mutated data.</p>
<pre><code>data[0]
Object {x: 1, y: 0.73, classifier: 1}
data[1]
Object {x: 2, y: 0.12, classifier: 1}
</code></pre>
<p>Is map the right function to use here? Am i using it correctly?</p>
| <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.classifier
};
});
</code></pre>
|
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 an efficient way during run-time in my java application so I can look up a few entries? I've never used an sql-file to retrieve data in java before so I don't know what is the best strategy.
By the way, I'm creating an application that reads large graphs and another xml database so memory usage is fairly high.</p>
| <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::RectangleShape> operator()()
{
return std::unique_ptr<sf::RectangleShape>(player);
} // RectangleShape Getter
</code></pre>
<p>But it says there is no matching function for the parenthesis operator. How else should this be done?</p>
| <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 absolutely not be freed from outside the class.</p>
<p>It would help to have more information about the owning class, but if I can assume that <code>player</code> is a data member, then your first example is technically fine. However it is often more idiomatic to return a reference than pointer.</p>
<pre><code>class SomeClass
{
sf::RectangleShape player;
sf::RectangleShape& operator()()
{
return player;
}
};
</code></pre>
<p>If the above assumption is incorrect, you should show your full class definition so we have more information to form a correct solution.</p>
|
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 = QPushButton(win)
b1.setText("Button1")
b1.move(50,20)
b1.clicked.connect(b1_clicked)
b2=QPushButton(win)
b2.setText("Button2")
b2.move(50,50)
QObject.connect(b2,SIGNAL("clicked()"),b2_clicked)
win.setGeometry(100,100,200,100)
win.setWindowTitle("PyQt")
win.show()
sys.exit(app.exec_())
def b1_clicked():
print("Button 1 clicked")
def b2_clicked():
print("Button 2 clicked")
if __name__ == '__main__':
window()
</code></pre>
<p>The app does what is supposed to, which is to open a dialog box with two buttons on it, when run inside IDLE. When I try to run the same program from cmd I get this message:</p>
<p>Traceback (most recent call last):
File "C:\Python34\Basic2buttonapp.py", line 2, in
from PyQt4.QtCore import *
ImportError: No module named 'PyQt4'</p>
<p>I've already tried typing python.exe inside cmd to see if Im running the correct version of python from within the cmd, but this does not seem to be the problem. I know it has to do with the communication between python 3.4 and the module, but it seems weird to me that it only happens when trying to run it from cmd. </p>
<p>If anyone has the solution I'll be very thankful. </p>
| <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>...or within IDLE:</p>
<pre><code>import sys
print(sys.executable)
</code></pre>
<p>If those two don't match, there is your problem. To fix it, you need to update your <code>PATH</code> variable to put the <em>parent folder</em> of the Python executable referred to by IDLE at the front. You can get instructions of how to do this on Windows <a href="http://stackoverflow.com/questions/9546324/adding-directory-to-path-environment-variable-in-windows">here</a>.</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 parameters (and use the new ones) from within the android application? I can seem to get access to firebase database url using <code>R.string.firebase_database_url</code> but that's about it.</p>
<p>Now, I know, I can get around this by throwing in an intermediate layer connecting to Firebase with custom credentials but I am trying NOT to do so.</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 answer for an example of how to use it: <a href="http://stackoverflow.com/questions/38472933/how-can-i-store-to-different-storage-buckets-using-firebase-storage">How can i store to different storage buckets using Firebase Storage</a></p>
|
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 doesn't work for length of decimals above 15.</p>
<p>If I use, for e.g:</p>
<pre><code>round(random.uniform(0, 0.5), 100)
</code></pre>
<p>It returns 0.586422176354875, but I need a code that returns a number with 100 decimals. </p>
<p><strong>Can you help me?</strong></p>
<p>Thanks!</p>
| <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 Python, there is the <a href="https://docs.python.org/2/library/decimal.html" rel="nofollow"><code>decimal</code> built-in module</a> which can help:</p>
<pre><code>>>> from decimal import Decimal
>>> Decimal('1.2345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901')
Decimal('1.2345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901')
</code></pre>
<p>Decimal can have any precision you need and it won't introduce <a href="http://stackoverflow.com/q/19473770/389289">floating point errors</a>, but it will be much slower.</p>
<h2>random</h2>
<p>Now you just have to create a string with 100 decmals and give it to <code>Decimal</code>.</p>
<p>This will create one random digit:</p>
<pre><code>random.choice('0123456789')
</code></pre>
<p>This will create 100 random digits and concatenate them:</p>
<pre><code>''.join(random.choice('0123456789') for i in range(100))
</code></pre>
<p>Now just create a <code>Decimal</code>:</p>
<pre><code>Decimal('0.' + ''.join(random.choice('0123456789') for i in range(100)))
</code></pre>
<p>This creates a number between 0 and 1. Multiply it or divide to get a different range.</p>
|
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">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class Speak extends React.Component {
render() {
return (
<div>
<input ref={(c) => this._input = c} defaultValue="Hello World!"/>
<button onClick={this.say.bind(this) }>Say</button>
</div>
);
}
say() {
if (this._input !== null) {
alert(this._input.value);
}
}
};
ReactDOM.render(<Speak />, document.getElementById('App'));</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="App" /></code></pre>
</div>
</div>
</p>
| <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, number, jersey):
self.__name = name
self.__number = number
self.__jersey = jersey
def setname(self, name):
self.__name = name
def setnumber(self, number):
self.__number = number
def setjersey(self, jersey):
self.__jersey = jersey
def getname(self):
return self.__name
def getnumber(self):
return self.__number
def getjersey(self):
return self.__jersey
def displayData(self):
print("")
print("Player Information ")
print("------------------------")
print("Name:", self.__name)
print("Phone Number:", self.__number)
print("Jersey Number:", self.__jersey)
import players_Class
def displayMenu():
print("1. Display Players")
print("2. Add Player")
print("3. Remove Player")
print("4. Edit Player")
print("9. Exit Program")
print("")
return int(input("Selection> "))
def printPlayers(players):
if len(players) == 0:
print("Player not in List.")
else:
for x in players.keys():
players[x].displayData(self)
def addplayers(players):
newName = input("Enter new Players Name: ")
newNumber = int(input("Players Phone Number: "))
newJersey = input("Players Jersey Number: ")
players[newName] = (newName, newNumber, newJersey)
return players
def removeplayers(players):
removeName = input("Enter Player Name to be removed: ")
if removeName in players:
del players[removeName]
else:
print("Player not found in list.")
return players
def editplayers(players):
oldName = input("Enter the Name of the Player you want to edit: ")
if oldName in players:
newName = input("Enter the player new name: ")
newNumber = int(input("Players New Number: "))
newJersey = input("Players New Jersey Number: ")
players[oldName] = petClass.Pet(newName, newNumber, newJersey)
else:
print("Player Not Found")
return players
print("Welcome to the Team Manager")
players = {}
menuSelection = displayMenu()
while menuSelection != 9:
if menuSelection == 1:
printPlayers(players)
elif menuSelection == 2:
players = addplayers(players)
elif menuSelection == 3:
players = removeplayers(players)
elif menuSelection == 4:
players = editplayers(players)
menuSelection = displayMenu()
print ("Exiting Program...")
</code></pre>
| <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 to lazy(ie. they forget to add FetchType.LAZY) resulting in tons of unecessary joins and in some cases resulting in 6 tables being joined which was not needed.</p>
<p>Everything should really be lazy unless the developer moves to JQL to eagerly fetch something. It then is more consistent and aids the developers from not making these mistakes every time they add a ManyToOne annotation</p>
<p>OR, in hibernate 5.2, can one still use hibernate annotations instead? but then I need to somehow get rid of JPA annotations off the classpath as I am afraid they accidentally come back to us(us all being human and all).</p>
<p>I found this great article which explains it better than I could have on how everything should be lazy as well <a href="https://vladmihalcea.com/2014/12/15/eager-fetching-is-a-code-smell/" rel="nofollow">https://vladmihalcea.com/2014/12/15/eager-fetching-is-a-code-smell/</a></p>
<p>thanks,
Dean</p>
| <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 behavior, you could at least tweak the compile time: You could add a <em>Checkstyle</em> rule (or anything similar) that enforces your coworkers to always set the fetch type explicitly. </p>
<p>Example for Checkstyle:</p>
<pre><code><module name="RegexpSinglelineJava">
<property name="format" value="@(One|Many)ToOne(?!\([^)]*fetch)"/>
<property name="message" value="Please declare the fetch type (and use EAGER sparingly)"/>
<property name="ignoreComments" value="true"/>
</module>
</code></pre>
<p>That would add a compile time warning, if the fetch was not defined after a <code>@OneToOne</code> or <code>@ManyToOne</code>.</p>
|
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 to scroll horizontally in notepad. I have looked up a number of solutions but none of them do this so far. Thanks for any suggestions.</p>
<pre><code>import urllib.request
page = urllib.request.urlopen("http://www.google.com")
webfile = page.readlines()
with open("file01.txt", 'w') as f:
for line in webfile:
f.write(str(line))
f.close()
</code></pre>
| <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 elements in an array easily enough using similar indexing(or slicing) to lists. But it seems that I am unable to do anything with each (i,j) entry when I try to access it in a loop. </p>
<pre><code>row= 3
column = 2
space = np.random.randint(2, size=(row, column))
print space, "\n"
print space[0,1]
print space[1,0] #test if I can access indiivdual elements
</code></pre>
<p>output:</p>
<pre><code>[[1,1
[1,1
[0,0]]
1
1
</code></pre>
<p>for example, using the above I want to iterate over every row and column and print each entry. I would think to use something like the following:</p>
<pre><code>for i in space[0:row,:]:
for j in space[:,0:column]:
print space[i,j]
</code></pre>
<p>the output I get is</p>
<pre><code>[1,1]
[1,1]
[1,1]
[1,1]
[1,1]
[1,1]
[1,1]
[1,1]
[1,1]
</code></pre>
<p>Obviously this does not work. I believe the problem is that I'm accessing entire rows and columns instead of elements within any given row and column. I've been going over the numpy docs for a couple of hours and I am still unsure of how to go about this. </p>
<p>My main concern is I want to change each (i,j) entry by using a loop and some conditionals, for example (using the above loop): </p>
<pre><code>for i in space[0:row,:]:
for j in space[:,0:column]:
if [i+1,j] + [i,j+1] == 2:
[i,j] = 1
</code></pre>
| <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 indexing are here</a>.</p>
<p>But it looks, that you should also read up basic <a href="https://wiki.python.org/moin/ForLoop" rel="nofollow">python-loops</a>.</p>
<p>Start simple and read some docs and tutorials. After i saw <strong>Praveen</strong>'s comment, i felt a bit bad with this simple answer here which does not offer much more than his comment, but maybe the links above are just what you need.</p>
<p><strong>A general remark on learning numpy by trying</strong>:</p>
<ul>
<li>regularly use arr.shape to check the dimensions</li>
<li>regularly use arr.dtype to check the data-type </li>
</ul>
<p>So in your case the following should have given you a warning (not a python one; one in your head) as you probably expected i to iterate over values of <strong>one</strong> dimension:</p>
<pre><code>print((space[0:row,:]).shape)
# output: (3, 2)
</code></pre>
|
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><code>text = "the drug side-effects are: night mare. nausea. night sweat. bad dream. dizziness. severe headache. I suffered. she suffered. she told I should change it."
</code></pre>
<p>I wrote a regular expression code to detect one word (such as, headache) or two words (such as, bad dream) surround by two dots:</p>
<h1>detecting a word surrounded by two dots:</h1>
<pre><code>text= re.sub (r'(\.)(\s*\w+\s*\.)',r',\2 ', text )
</code></pre>
<h1>detecting two words surrounded by two dots:</h1>
<pre><code>text = re.sub (r'(\.)(\s*\w+\s\w+\s*\.)',r',\2 ', text11 )
</code></pre>
<p>This is the output:</p>
<pre><code>the drug side-effects are: night mare, nausea, night sweat. bad dream, dizziness, severe headache. I suffered, she suffered. she told I should change it.
</code></pre>
<p>But it should be: </p>
<pre><code>the drug side-effects are: night mare, nausea, night sweat, bad dream, dizziness, severe headache. I suffered. she suffered. she told I should change it.
</code></pre>
<p>My code did not replace <code>dot</code> after <code>night sweat to ','</code>. I addition, <code>if a sentence starts with a subject pronoun (such as I and she) I do not want to change dot to comma after it, even if it has two words (such as, I suffered)</code>. I do not know how to add this condition to my code. </p>
<p>Any suggestion? Thank you !</p>
| <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 that is neither a word character nor a space (e.g. <code>.</code> <code>!</code> <code>:</code> <code>,</code>) or the end of the string.</p>
<p>You will then have to replace it with <code>,\1</code></p>
<p>In python</p>
<pre class="lang-py prettyprint-override"><code>import re
text = "the drug side-effects are: night mare. nausea. night sweat. bad dream. dizziness. severe headache. I suffered. she suffered. she told I should change it."
text = re.sub(r'\.(\s*(?!(?:i|she)\b)\w+(?:\s+\w+)?\s*)(?=[^\w\s]|$)', r',\1', text, flags=re.I)
print(text)
</code></pre>
<p>Outputs</p>
<pre><code>the drug side-effects are: night mare, nausea, night sweat, bad dream, dizziness, severe headache. I suffered. she suffered. she told I should change it.
</code></pre>
<p>This is likely not absolutely failsafe and you might have to expand the pattern for some edge cases.</p>
|
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 have just one website and place the price information in <code><div></code> what is shown just if you use www.example-with-price.com.<br>
I try to use something like this, but I can not find a way to hide if the user go to my site using www.example-without-prices.com</p>
<pre><code><div id='hideshow' data-value="price1" style="display:none">
<table> price table here </table>
</div>
<script>
$('[id^="hideshow"]').on('click', function(event) {
var dataValue = $(this).attr('data-value');
dataValue = $('#'+dataValue);
$(dataValue).toggle('hide');
});
** <!-- add something what toggle hide if user enters site via www.example-without-prices.com -->
</script>
</code></pre>
| <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', function(event) {
var dataValue = $(this).attr('data-value');
dataValue = $('#'+dataValue);
$(dataValue).toggle('hide');
});
** <!-- add something what toggle hide if user enters site via www.example-without-prices.com -->
if (window.location.hostname !== 'www.example-without-prices.com') {
$('#hideshow').show();
}
</script>
</code></pre>
|
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 <typename T>
struct Foo
{
virtual void send(T t) = 0;
};
template <typename...T>
struct Bar : Foo<T>...
{
void send(T t) override { // does not compile because
// abstract method not implemented
}
};
int main() {
// example usage
Bar<int, double> b;
b.send(1);
b.send(2.3);
}
</code></pre>
<p>Many thanks in advance.</p>
<p><strong>Edit</strong>: Added virtual to abstract method.</p>
| <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()</code></p>
<p>Last, you can use a template <code>send()</code> method in <code>Bar</code> to select the correct virtual <code>send()</code> method.</p>
<pre><code>#include <iostream>
template <typename T>
struct Foo
{ virtual void send(T t) = 0; };
template <typename T>
struct Foo2 : Foo<T>
{
void send(T) override
{ std::cout << "sizeof[" << sizeof(T) << "] " << std::endl; }
};
template <typename...T>
struct Bar : Foo2<T>...
{
template <typename U>
void send (U u)
{ Foo2<U>::send(u); }
};
int main()
{
Bar<int, double> b;
b.send(1); // print sizeof[4]
b.send(2.3); // print sizeof[8]
}
</code></pre>
|
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 | Total 2015 | Total 2016 |
</code></pre>
<p>Sounds pretty basic but I haven't been able to figure it out.</p>
<p>Should I create two queries, one for each year? If so, how can I join both results later?</p>
| <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.CharField(max_length=200,unique=True )
config_name = models.ForeignKey('RunConfig',on_delete=models.CASCADE,)
Overall_Status = models.CharField(max_length=50,blank=True,null=True)
</code></pre>
<p>I am currently using a CBV list view for RunConfigStatus. I would like to href/link the foreign key object to its detail view. is this possible?</p>
<pre><code>class RunConfigStatusListView(LoginRequiredMixin,ListView):
model = RunConfigStatus
context_object_name = 'run_config_status_list'
</code></pre>
<p>On my Template:</p>
<pre><code>{% for run in run_config_status_list %}
<td><a href={% url 'runconfigstatus-detail' pk=run.id %}>{{run.config_run_name}}</a></td>
<td>{{run.config_name}}</td>
<td>{{run.Overall_Status}}</td>
</code></pre>
<p>I want that config_name should have a href which will redirect to RunConfig detail view</p>
<pre><code> <td><a href={% url 'runconfig-detail' pk=**NOT SURE** %}>{{run.config_name}}</a></td>
</code></pre>
<p>Screen Shot of my current output, <a href="http://i.stack.imgur.com/v16Mq.png" rel="nofollow"><img src="http://i.stack.imgur.com/v16Mq.png" alt="enter image description here"></a></p>
<p>I would like to click on Config Name values and it should redirect to its detail view. (In this case Test, MyFirstTest on all entries)</p>
| <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_name</code> doesn't point to a name, it points to a RunConfig instance.</p>
|
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 != given; ++it) // this terminates
{
int local_diff = *it - *given;
// if the element is less than/equal to given we are not interested
if (local_diff <= 0)
continue;
if (local_diff < diff)
{
// this update the global diff
diff = local_diff;
the_one = it;
}
}
</code></pre>
<p>I was wondering if anyone can think of an elegant stl algorithm to replace the above. Essentially we have to go through all the elements, and also keep track of the one which we need. This is not similar to <code>std::max_element</code> (atleast I can't model it that way).</p>
| <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 (one that's greater than <code>*given</code>) to compare smaller than any "not good" element. Two "good" elements are compared normally; two "bad" elements are always declared equivalent.</p>
|
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</strong>(better)</p>
<p>for example i have a raster image with the
5 class : </p>
<pre><code>1. 0-100
2. 100-200
3. 200-300
4. 300-500
5. 500-1000
</code></pre>
<p>and i want to delete class 1 range value
or maybe class <code>1,2,4,5</code> </p>
<p>i begin with this script :</p>
<pre><code>import numpy as np
from osgeo import gdal
ds = gdal.Open("raster3.tif")
myarray = np.array(ds.GetRasterBand(1).ReadAsArray())
#print myarray.shape
#print myarray.size
#print myarray
new=np.delete(myarray[::2], 1)
</code></pre>
<p>but i cant to complete</p>
<p>the image
<a href="http://i.stack.imgur.com/S4bk4.jpg" rel="nofollow">White in class 5 and black class 1</a></p>
| <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 explain where line breaks are and the length of the bitstring, so that the 1-D bitstring can be understood as a 2-D array. If you "remove" a pixel, then you break the raster. The 2-D grid is no longer valid.</p>
<p>Of course, there are many instances where you do want to effectively discard or clean the raster of data. Such an example might be to remove pixels that cover land from a raster of sea-surface temperatures. To accomplish this goal, many geospatial raster formats hold metadata describing what are called NoData values. Pixels containing a NoData value are <strong>interpreted</strong> as not existing. Recall that in a raster, each pixel must contain some information. The NoData paradigm allows the structure and format of rasters to be met, while also giving a way to <strong>mask</strong> pixels from being displayed or analyzed. There is still data (bits, 1s and 0s) at the masked pixels, but it only serves to identify the pixel as invalid.</p>
<p>With this in mind, here is an example using <code>gdal</code> which will mask values in the range of 0-100 so they are NoData, and "do not exist". The NoData value will be specified as 0. </p>
<pre><code>from osgeo import gdal
# open dataset to read, and get a numpy array
ds = gdal.Open("raster3.tif", 'r')
myarray = ds.GetRasterBand(1).ReadAsArray()
# modify numpy array to mask values
myarray[myarray <= 100] = 0
# open output dataset, which is a copy of original
driver = gdal.GetDriverByName('GTiff')
ds_out = driver.CreateCopy("raster3_with_nodata.tif", ds)
# write the modified array to the raster
ds_out.GetRasterBand(1).WriteArray(myarray)
# set the NoData metadata flag
ds_out.GetRasterBand(1).SetNoDataValue(0)
# clear the buffer, and ensure file is written
ds_out.FlushCache()
</code></pre>
|
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 because there are another variable to defined depends the function) </p>
<p><strong>Controller:</strong></p>
<pre><code>(function() {
'use strict';
angular
.module('example.cancha')
.controller('CanchaController', CanchaController);
CanchaController.$inject = ['$state', 'canchaService'];
function CanchaController($state, canchaService) {
var vm = angular.extend(this, {
canchasComplejo: [],
grupoCancha: grupoCancha,
grupoVisible: grupoVisible
});
(function activate() {
cargarCanchasComplejo();
})();
//funcion que llama al servicio para obtener las canchas del complejo
function cargarCanchasComplejo() {
canchaService.obtenerCanchasComplejo()
.then(function(canchasComplejo) {
vm.canchasComplejo = canchasComplejo;
});
}
function grupoCancha(canchaComplejo){
if (vm.grupoVisible(canchaComplejo)) {
vm.grupoMostrado = null;
}
else {
vm.grupoMostrado = canchaComplejo;
}
}
function grupoVisible(canchaComplejo){
return vm.grupoMostrado === canchaComplejo;
}
}
})();
</code></pre>
<p>The other way is kinda weird (may be is because I come from Java). But the definition of the function is complicated:</p>
<p><strong>Controller 2:</strong></p>
<pre><code>(function() {
'use strict';
angular
.module('example.cancha')
.controller('CanchaController', CanchaController);
CanchaController.$inject = ['$state', 'canchaService'];
function CanchaController($state, canchaService) {
var vm = angular.extend(this, {
canchasComplejo: []
});
(function activate() {
cargarCanchasComplejo();
})();
//funcion que llama al servicio para obtener las canchas del complejo
function cargarCanchasComplejo() {
canchaService.obtenerCanchasComplejo()
.then(function(canchasComplejo) {
vm.canchasComplejo = canchasComplejo;
});
}
vm.grupoCancha = function(canchaComplejo) {
if (vm.grupoVisible(canchaComplejo)) {
vm.grupoMostrado = null;
}
else {
vm.grupoMostrado = canchaComplejo;
}
};
vm.grupoVisible = function(canchaComplejo) {
return vm.grupoMostrado === canchaComplejo;
};
}
})();
</code></pre>
<p><strong>Could you explain me which way is the best to define functions and why?</strong>
Thanks!!</p>
| <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 immediately executed - <code>(function(){})()</code>) and is not accessible from the HTML. When you write it as </p>
<pre><code>vm.grupoVisible = function(canchaComplejo) {
return vm.grupoMostrado === canchaComplejo;
};
</code></pre>
<p>it may be later accessed in HTML via ng-controller="CanchaController as cc" and then cc.grupoVisible, for example:</p>
<pre><code><div ng-controller="CanchaController as cc">
<button ng-if="cc.grupoVisible()">SOME BUTTON</button>
</div>
</code></pre>
|
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 through a process of writing it out basically and then refining! </p>
<p>Code:</p>
<pre><code>import ntpath, sys, tkFileDialog, Tkinter
import xml.etree.ElementTree as ET
class Comparison:
def __init__(self, file):
self.file = ET.parse(file)
self.filename = self.get_file_name(file)
self.root = self.file.getroot()
self.file_length = len(self.root)
self.data_dict = dict()
self.master_list = list()
self.parse_xml(self.root)
print self.master_list
def get_file_name(self, file):
filename_list = list()
for char in ntpath.basename(str(file)):
filename_list.append(char)
if ''.join(filename_list[-4:]) == '.xml':
return ''.join(filename_list)
def parse_xml(self, tree):
for child in tree:
if tree == self.root:
self.step_number = child.attrib['id']
self.data_dict['Step'] = self.step_number
if len(child.tag) > 0:
self.data_dict['Tag'] = child.tag
else:
self.data_dict['Tag'] = ""
if len(child.attrib) > 0:
self.data_dict['Attrib'] = child.attrib
else:
self.data_dict['Attrib'] = ""
if child.text is not None:
self.data_dict['Text'] = child.text
else:
self.data_dict['Text'] = ""
print self.data_dict
print "Step: "+str(self.data_dict['Step'])
try:
print "Tag: "+str(self.data_dict['Tag'])
except:
pass
try:
for key,value in self.data_dict['Attrib'].iteritems():
print "Attrib: "+str(key)
print "Attrib Value: "+str(value)
except:
pass
try:
if len(str(self.data_dict['Text'])) > 0:
print "Text Length: "+str(len(str(self.data_dict['Text'])))
print "Text: "+str(self.data_dict['Text'])
except:
pass
print ""
print len(self.data_dict)
self.master_list.append(self.data_dict)
print self.data_dict
self.data_dict.clear()
if len(child) > 0:
self.parse_xml(child)
if __name__ == "__main__":
root = Tkinter.Tk()
root.iconify()
if sys.argv[1] != "":
file_a = Comparison(sys.argv[1])
else:
file_a = Comparison(tkFileDialog.askopenfilename())
</code></pre>
| <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 in zip(range(5),'abcde')}
>>> id(d)
140199719344392
>>> some_list = []
>>> some_list.append(d)
>>> some_list
[{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}]
>>> id(some_list[0])
140199719344392
>>> d.clear()
>>> some_list
[{}]
>>>
</code></pre>
<p>If you want a copy to be appended, then you need to explicitely copy it. If a shallow copy will do, then simply use <code>your_dict.copy()</code>:</p>
<pre><code>>>> d = {k:v for k,v in zip(range(5),'abcde')}
>>> d
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}
>>> id(d)
140199686153480
>>> some_list = []
>>> some_list.append(d.copy())
>>> id(some_list[0])
140199719344392
>>> d.clear()
>>> some_list
[{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}]
>>>
</code></pre>
|
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.Views.DxLibraryView). The <strong>UserControl</strong> itself has a <strong>ListView</strong> (in row=0) and followed by other controls in the below rows. </p>
<p>The good news: When the WindowDialog presents the UserControl, it correctly displays the UserControl to the size of the display screen and minimizing the
WindowDialog (or resizing it) does correctly change the size of the UserControl and shrinks the ListView correctly.</p>
<p>The problem (the bad news): When a filter is placed on the list contained within the ListView, so that the ListView has fewer items, it shrinks due to lack of items and the entire UserControl shrinks. This becomes very distracting when the list is large with a hundred items then shrinks to 4 items as this causes the entire UserControl to shrink in size.</p>
<p>What I Need: <strong>I need the UserControl initially to be maximized to the size of the screen with the ListView using all available space. The UserControl is to shrink (or enlarge) according to its parent WindowDialog--not according to the contents of the ListView.</strong></p>
<p>Thanks for reading all this. Any help is most appreciated.</p>
<p>The WindowDialog:</p>
<pre><code><Window x:Class="Billing.WindowDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
WindowStyle="SingleBorderWindow"
WindowStartupLocation="CenterOwner"
Title="{Binding DialogTitle}">
<ContentPresenter x:Name="DialogPresenter" Content="{Binding .}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Window>
using System.Windows;
using Client;
namespace Billing
{
/// <summary>
/// Interaction logic for WindowDialog.xaml
/// </summary>
public partial class WindowDialog : Window, IWindowDialog
{
public WindowDialog()
{
InitializeComponent();
}
}
}
</code></pre>
<p>C# code to dispaly the UserControl: </p>
<pre><code> var dialog = new WindowDialog
{
Title = "ICD Library",
ShowInTaskbar = false,
Topmost = false
};
DialogService dialogService = new DialogService();
dialogService.ShowDialog(
dialog,
new DxLibraryViewModel(null, null)
);
// Opens a window and returns only when the newly opened window is closed.
public void ShowDialog<TDialogViewModel>(IWindowDialog windowdialog, TDialogViewModel viewModel,
Action<TDialogViewModel> onDialogClose, bool sizetocontent = false)
{
// Assign the viewmodel as the DataContext of the WindowDialog.xaml
windowdialog.DataContext = viewModel;
// Set window size.
SizeToContent SizeToContent = SizeToContent.Manual;
WindowState WindowState = WindowState.Maximized;
if (sizetocontent)
{
SizeToContent = SizeToContent.WidthAndHeight;
WindowState = WindowState.Normal;
}
// The WindowDialog is the mainwindow.
(windowdialog as WindowDialog).WindowState = WindowState;
(windowdialog as WindowDialog).SizeToContent = SizeToContent;
// Open MainWindow in modal fashion (Returns only when the newly opened window is closed).
// Implicict DataTemplate in App.XAML used to display usercontrol.
windowdialog.ShowDialog();
}
public void ShowDialog<TDialogViewModel>(IWindowDialog mainwindow, TDialogViewModel viewModel, bool sizetocontent = false)
{
ShowDialog(mainwindow, viewModel, null, sizetocontent);
}
</code></pre>
<p>The UserControl is:</p>
<pre><code><UserControl x:Class="NovaLibraries.Views.DxLibraryView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:c="clr-namespace:NovaLibraries.Converters"
mc:Ignorable="d"
BorderBrush="Black" BorderThickness="2" Background="Beige" >
<UserControl.Resources>
<!--Display a checkmark without the surrounding box as an image-->
<c:CheckMarkConverter x:Key="mycheckmark" />
<Style x:Key="ItemContStyle" TargetType="{x:Type ListViewItem}">
<Style.Resources>
<!--ORANGE-->
<LinearGradientBrush x:Key="OrangeBrush" StartPoint="0.5,0" EndPoint="0.5,1" >
<GradientStop Offset="0.1" Color="#AA00CC00" />
<GradientStop Offset="0.8" Color="Orange" />
</LinearGradientBrush>
</Style.Resources>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=chronic}" Value="true">
<Setter Property="Background" Value="{StaticResource OrangeBrush}" />
</DataTrigger>
</Style.Triggers>
</Style>
</UserControl.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="100*" />
<RowDefinition Height="275" />
</Grid.RowDefinitions>
<ListView Grid.Row="0"
ItemContainerStyle="{StaticResource ItemContStyle}"
ItemsSource="{Binding DxView.View}"
SelectedItem="{Binding SelectedItem}"
IsEnabled="{Binding CanSelect}"
Width="781" >
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Path=rank}" Header="Rank" Width="50" />
<GridViewColumn DisplayMemberBinding="{Binding Path=code}" Header="ICD-9" Width="50" />
<GridViewColumn DisplayMemberBinding="{Binding Path=cdesc}" Header="Diagnosis" Width="550" />
</GridView>
</ListView.View>
</ListView>
</Grid>
</UserControl>
</code></pre>
| <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 using webpack, how do I import? The docs for the package say the below and the package was installed in <code>node_modules/bootstrap-material-design/</code>:</p>
<pre><code><!-- Bootstrap Material Design -->
<link rel="stylesheet" type="text/css" href="dist/css/bootstrap-material-design.css">
<link rel="stylesheet" type="text/css" href="dist/css/ripples.min.css">
</code></pre>
<p>So in the head do I include via the below:</p>
<pre><code> <!-- Bootstrap Material Design -->
<link rel="stylesheet" type="text/css" href="node_modules/bootstrap-material-design/dist/css/bootstrap-material-design.css">
<link rel="stylesheet" type="text/css" href="node_modules/bootstrap-material-design/dist/css/ripples.min.css">
</code></pre>
<p>Or will angular2 already include?</p>
| <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.css'
// your component (example code below)
@Component({
selector: 'app',
templateUrl: 'app.template.html'
})
</code></pre>
<p>And that's it. Webpack will take care of the reset.</p>
<p><strong>Edit:</strong></p>
<p>If you have created the app using <code>angular-cli/ng-cli</code> then you can also include these stylesheets to <code>angular-cli.json</code></p>
|
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, which is not what I want, I would like them to appear as <strong>entirely separate tables under one view</strong>, here is what I did:</p>
<pre><code>CREATE VIEW TEAM_SUMMARY AS
SELECT DISTINCT COUNTRY.country_name AS CountryName_T1,count(Team1)AS NoOfGames,
SUM(Team1_score) AS TotalGoalsFor,SUM(Team2_score) AS TotalGoalsAgainst
FROM COUNTRY,MATCH_RESULTS WHERE
country_name = Team1
group by country_name
UNION
SELECT DISTINCT COUNTRY.country_name AS CountryNameT_2,count(Team2)AS NoOfGames,
SUM(Team2_score) AS TotalGoalsFor,SUM(Team1_score) AS TotalGoalsAgainst
FROM COUNTRY,MATCH_RESULTS WHERE
country_name = Team2
group by country_name;
</code></pre>
<p><strong>UPDATE:
So, the output of my current query is something like this:</strong></p>
<pre><code>mysql> SELECT * FROM TEAM_SUMMARY;
+----------------------+-----------+---------------+-------------------+
| CountryName | NoOfGames | TotalGoalsFor | TotalGoalsAgainst |
+----------------------+-----------+---------------+-------------------+
| Algeria | 1 | 1 | 1 |
| Argentina | 4 | 5 | 1 |
| Australia | 2 | 2 | 6 |
| Belgium | 3 | 5 | 2 |
| Bosnia & Herzegovina | 1 | 3 | 1 |
| Brazil | 6 | 7 | 13 |
| Cameroon | 2 | 1 | 8 |
| Chile | 1 | 3 | 1 |
| Columbia | 3 | 7 | 1 |
| Costa Rica | 2 | 1 | 1 |
| Croatia | 1 | 1 | 3 |
| Ecuador | 1 | 0 | 0 |
| England | 1 | 1 | 2 |
| France | 3 | 5 | 1 |
| Germany | 4 | 9 | 3 |
| Ghana | 1 | 1 | 2 |
| Greece | 1 | 2 | 1 |
| Honduras | 2 | 1 | 5 |
| Iran | 1 | 0 | 0 |
| Italy | 2 | 0 | 2 |
| Ivory Coast | 1 | 2 | 1 |
| Japan | 2 | 1 | 4 |
| Mexico | 1 | 1 | 0 |
| Netherlands | 4 | 4 | 1 |
| Nigeria | 2 | 3 | 3 |
| Portugal | 1 | 2 | 1 |
| Russia | 1 | 1 | 1 |
| South Korea | 2 | 2 | 5 |
| Spain | 2 | 1 | 7 |
| Switzerland | 2 | 4 | 6 |
| Uruguay | 2 | 3 | 4 |
| USA | 2 | 2 | 3 |
| Algeria | 3 | 6 | 6 |
| Argentina | 3 | 3 | 3 |
| Australia | 1 | 1 | 3 |
| Belgium | 2 | 1 | 1 |
| Bosnia & Herzegovina | 2 | 1 | 3 |
| Brazil | 1 | 4 | 1 |
| Cameroon | 1 | 0 | 1 |
| Chile | 3 | 3 | 3 |
| Columbia | 2 | 5 | 3 |
| Costa Rica | 3 | 4 | 1 |
| Croatia | 2 | 5 | 3 |
| Ecuador | 2 | 3 | 3 |
| England | 2 | 1 | 2 |
| France | 2 | 5 | 2 |
| Germany | 3 | 9 | 1 |
| Ghana | 2 | 3 | 4 |
| Greece | 3 | 1 | 4 |
| Honduras | 1 | 0 | 3 |
| Iran | 2 | 1 | 4 |
| Italy | 1 | 2 | 1 |
| Ivory Coast | 2 | 2 | 4 |
| Japan | 1 | 1 | 2 |
| Mexico | 3 | 4 | 3 |
| Netherlands | 3 | 11 | 3 |
| Nigeria | 2 | 0 | 2 |
| Portugal | 2 | 2 | 6 |
| Russia | 2 | 1 | 2 |
| South Korea | 1 | 1 | 1 |
| Spain | 1 | 3 | 0 |
| Switzerland | 2 | 3 | 1 |
| Uruguay | 2 | 1 | 2 |
| USA | 2 | 3 | 3 |
+----------------------+-----------+---------------+-------------------+
64 rows in set (0.01 sec)
</code></pre>
<p><strong>UPDATE2: Each query provides 32 row, and here they are combined into 64 rows so I don't know which belongs to which query, you can see that <code>USA</code> is the last row of each query and then it starts with <code>Algeria</code> again for the second query with different values that do not represent the column description.</strong></p>
<p><strong>What I want is something like this:</strong></p>
<pre><code>+------+--------+ +------+--------+
| code | SUM(*) | | code | SUM(*) |
+------+--------+ +------+--------+
| AAA | 4 | | AAA | 4 |
| BBB | 3 | | CCC | 1 |
+------+--------+ +------+--------+
</code></pre>
<p>Then I did some searching in order to use <code>JOIN</code> as shown here <a href="http://stackoverflow.com/questions/23700893/combine-results-of-two-unrelated-queries-into-single-view">Combine results of two unrelated queries into single view</a> but, this scenario is much less complicated than mine and couldn't apply it on my scenario, Any Idea?</p>
| <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 TotalGoalsAgainst
FROM COUNTRY c JOIN
MATCH_RESULTS mr
ON c.country_name = mr.Team1
GROUP BY country_name
UNION ALL
SELECT 'Team2' as which,
c.country_name AS CountryNameT_2,
count(Team2) AS NoOfGames,
SUM(Team2_score) AS TotalGoalsFor,
SUM(Team1_score) AS TotalGoalsAgainst
FROM COUNTRY c JOIN
MATCH_RESULTS mr
ON c.country_name = mr.Team2
GROUP BY country_name;
</code></pre>
<p>Notes:</p>
<ul>
<li><code>SELECT DISTINCT</code> with <code>GROUP BY</code> is almost always unnecessary (as in this case.</li>
<li>Use <code>UNION ALL</code> by default. Only use <code>UNION</code> when you specifically want to incur the overhead for removing duplicates.</li>
<li>Table aliases make the query easier to write and to read.</li>
<li>The above adds a column <code>which</code> to specify where each row comes from.</li>
</ul>
|
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 click on that div ?</p>
<p>i have tried this but i want to make it like i said above </p>
<pre><code><script type="text/javascript">
$(document).ready(function(){
$('#button').trigger('click');
});
</script >
</code></pre>
| <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
// realurl naming precedence configuration
$TYPO3_CONF_VARS['FE']['addRootLineFields'] .= 'tx_realurl_pathsegment,alias,title';
$TYPO3_CONF_VARS['EXTCONF']['realurl']['p372493.mittwaldserver.info'] = array(
'init' => array(
'enableCHashCache' => true,
'appendMissingSlash' => 'ifNotFile',
'adminJumpToBackend' => true,
'enableUrlDecodeCache' => true,
'enableUrlEncodeCache' => true,
'emptyUrlReturnValue' => '/',
// Allow for proper SEO 404 handling
'postVarSet_failureMode' => ''
),
'redirects' => array(),
'preVars' => array(
array(
'GETvar' => 'no_cache',
'valueMap' => array(
'nc' => 1
),
'noMatch' => 'bypass'
),
array(
'GETvar' => 'L',
'valueMap' => array(
// Sprachvariable Deutsch
'de' => '0',
),
'noMatch' => 'bypass',
),
),
// PAGEPATH mit Standard-Realurl-Konfiguration
'pagePath' => array(
'type' => 'user',
'userFunc' => 'EXT:realurl/class.tx_realurl_advanced.php:&tx_realurl_advanced->main',
'spaceCharacter' => '-',
'languageGetVar' => 'L',
'rootpage_id' => 1,
'expireDays' => 30,
// Nimmt Sysordner aus der Rootline (aktuell auskommentiert!)
'excludeDoktypes' => '254',
'segTitleFieldList' => 'tx_realurl_pathsegment,alias,title'
),
'fixedPostVars' => array(
'newsDetailConfiguration' => array(
array(
'GETvar' => 'tx_news_pi1[action]',
'valueMap' => array(
'detail' => '',
),
'noMatch' => 'bypass'
),
array(
'GETvar' => 'tx_news_pi1[controller]',
'valueMap' => array(
'News' => '',
),
'noMatch' => 'bypass'
),
'dateFilter' => array(
array(
'GETvar' => 'tx_newss_pi1[year]',
),
array(
'GETvar' => 'tx_newss_pi1[month]',
'valueMap' => array (
'january' => '01',
'february' => '02',
'march' => '03',
'april' => '04',
'may' => '05',
'june' => '06',
'july' => '07',
'august' => '08',
'september' => '09',
'october' => '10',
'november' => '11',
'december' => '12',
),
),
array(
'GETvar' => 'tx_newss_pi1[day]',
),
),
array(
'GETvar' => 'tx_news_pi1[news]',
'lookUpTable' => array(
'table' => 'tx_news_domain_model_news',
'id_field' => 'uid',
'alias_field' => 'title',
'addWhereClause' => ' AND NOT deleted',
'useUniqueCache' => 1,
'useUniqueCache_conf' => array(
'strtolower' => 1,
'spaceCharacter' => '-'
),
'languageGetVar' => 'L',
'languageExceptionUids' => '',
'languageField' => 'sys_language_uid',
'transOrigPointerField' => 'l10n_parent',
'autoUpdate' => 1,
'expireDays' => 180,
),
),
),
),
'postVarSets' => array(
'_DEFAULT' => array(
// NEWS
'newsCategoryConfiguration' => array(
array(
'GETvar' => 'tx_news_pi1[overwriteDemand][categories]',
'lookUpTable' => array(
'table' => 'sys_category',
'id_field' => 'uid',
'alias_field' => 'title',
'addWhereClause' => ' AND NOT deleted',
'useUniqueCache' => 1,
'useUniqueCache_conf' => array(
'strtolower' => 1,
'spaceCharacter' => '-'
),
),
),
),
'newsTagConfiguration' => array(
array(
'GETvar' => 'tx_news_pi1[overwriteDemand][tags]',
'lookUpTable' => array(
'table' => 'tx_news_domain_model_tag',
'id_field' => 'uid',
'alias_field' => 'title',
'addWhereClause' => ' AND NOT deleted',
'useUniqueCache' => 1,
'useUniqueCache_conf' => array(
'strtolower' => 1,
'spaceCharacter' => '-'
),
),
),
),
'28' => 'newsDetailConfiguration',
# '701' => 'newsDetailConfiguration', // For additional detail pages, add their uid as well
# '71' => 'newsTagConfiguration',
# '72' => 'newsCategoryConfiguration',
'controller' => array(
array(
'GETvar' => 'tx_news_pi1[action]',
'noMatch' => 'bypass'
),
array(
'GETvar' => 'tx_news_pi1[controller]',
'noMatch' => 'bypass'
),
),
// 'archiv' => array(
// 'GETvar' => '',
// noMatch => 'bypass'
// ),
// NEWS
),
),
'fileName' => array (
'defaultToHTMLsuffixOnPrev' => true,
'index' => array(
'sitemap.xml' => array(
'keyValues' => array(
'type' => 841132,
),
),
'feed.rss' => array(
'keyValues' => array(
type => 9818,
),
),
'calender.ical' => array (
'keyValue' => array(
type => 9819,
),
),
'robots.txt' => array(
'keyValues' => array(
'type' => 841133
),
),
'drucken.html' => array(
'keyValues' => array(
'type' => '98',
'print' => '1'
),
),
'index.html' => array(
'keyValues' => array(
'type' => '0',
),
),
),
'defaultToHTMLsuffixOnPrev' => true,
'acceptHTMLsuffix' => true,
),
);
?>
</code></pre>
<p>Das News-Plugin habe ich folgendermaÃen konfiguriert. </p>
<pre><code>plugin.tx_news {
settings {
backPid = 25
listPid = 25
detail {
showPrevNext = 1
showSocialShareButtons = 0
}
list {
media {
image >
image {
maxWidth = 75
maxHeight = 75
}
}
}
link {
skipControllerAndAction = 1
hrDate = 1
hrDate {
day = d
month = m
year = Y
}
}
paginate {
itemsPerPage = 10
insertAbove = 1
insertBelow = 1
templatePath =
prevNextHeaderTags = 1
maximumNumberOfLinks = 3
}
analytics.social {
facebookLike = 0
facebookShare = 0
twitter = 0
}
}
predefine.archive = +1 Month
}
</code></pre>
<p>This configuration issues addresses in the following form:</p>
<blockquote>
<p>/nachricht/detail/News/news-title/archiv/2016/september.html?tx_news_pi1%5Bday%5D=2&cHash=bc08b3c694b77edd4d3de72396906807</p>
</blockquote>
<p>but I need adressoutput like this form:</p>
<blockquote>
<p>/nachricht/detail/News/2016/09/02/news-title.html</p>
</blockquote>
<p>nachricht is the title of the page.
The basic configuration of realurl running fine.</p>
<p>Someone has an idea or can tell me, how to update my news part of the configuration?</p>
| <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(
'_DEFAULT' => array(
//archive
'period' => array (
array (
'condPrevValue' => -1,
'GETvar' => 'tx_ttnews[pS]',
//'valueMap => array()
),
array (
'GETvar' => 'tx_ttnews[pL]',
//'valueMap => array()
),
array (
'GETvar' => 'tx_ttnews[arc]',
'valueMap' => array(
'non-archived' => -1,
),
),
),
'archive' => array(
array(
'GETvar' => 'tx_ttnews[year]' ,
),
array(
'GETvar' => 'tx_ttnews[month]' ,
'valueMap' => array(
'january' => '01',
'february' => '02',
'march' => '03',
'april' => '04',
'may' => '05',
'june' => '06',
'july' => '07',
'august' => '08',
'september' => '09',
'october' => '10',
'november' => '11',
'december' => '12',
)
),
),
'browse' => array (
array (
'GETvar' => 'tx_ttnews[pointer]',
),
),
'select' => array (
array (
'GETvar' => 'tx_ttnews[cat]',
'lookUpTable' => array (
'table' => 'tt_news_cat',
'id_field' => 'uid',
'alias_field' => 'title',
'addWhereClause'=> 'AND NOT deleted',
'useUniqueCache'=> 1,
'useUniqueCache_conf' => array (
'strtolower' => 1,
'spaceCharacter' => '-',
),
),
),
),
'article' => array(
array (
'GETvar' => 'tx_ttnews[tt_news]',
'lookUpTable' => array (
'table' => 'tt_news',
'id_field' => 'uid',
'alias_field' => 'title',
'addWhereClause'=> 'AND NOT deleted',
'useUniqueCache'=> 1,
'useUniqueCache_conf' => array (
'strtolower' => 1,
'spaceCharacter' => '-',
),
),
),
),
),
),
</code></pre>
|
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 mutations, I do not see any implementation of viewers. For example, the GitHub API doesn't have a viewer on top of all their mutations.</p>
| <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>.</p>
<p>The current way to do auth in GraphQL, at least in the JavaScript implementation, is by getting the user data based on something like an HTTP header and putting it on <code>context</code>, as mentioned here: <a href="http://graphql.org/learn/authorization/" rel="nofollow">http://graphql.org/learn/authorization/</a></p>
<p>Therefore, there is no reason to do viewer for mutations, or for queries. Most GraphQL clients don't mind, but one situation where it could make sense to have it in queries specifically is if you are using Relay 0.x, which has inherited some of Facebook's legacy GraphQL limitations. Hopefully a future version of Relay will remove this requirement.</p>
|
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>
<p>2.Set delegates, data sources, and tags (in viewDidLoad).</p>
<pre><code> pickerView1.dataSource = self
pickerView1.delegate = self
pickerView1.tag = 1
pickerView2.dataSource = self
pickerView2.delegate = self
pickerView2.tag = 2
</code></pre>
<p>3.Set number of rows</p>
<pre><code>func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
var returnIndex: Int = 0
if pickerView.tag == 1 {
returnIndex = pickerView1Data.count
} else if pickerView.tag == 2 {
returnIndex = pickerView2Data.count
}
return returnIndex
}
</code></pre>
<p>4.Return data for each row</p>
<pre><code>func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
var returnRow: String!
if pickerView.tag == 1 {
returnRow = pickerView1Data[row]
} else if pickerView.tag == 2 {
returnRow = pickerView2Data[row]
}
return returnRow
}
</code></pre>
<p>5.Capture pickerView selection</p>
<pre><code>func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
// This method is triggered whenever the user makes a change to the picker selection.
if pickerView.tag == 1 {
beachTextField.text = pickerView1Data[row]
} else if pickerView.tag == 2 {
animalTextField.text = pickerView2Data[row]
}
}
</code></pre>
<p>Of course, this is on top of everything else you have to do to set up picker views, but this should be everything that needs to be taken care of for two picker views.</p>
|
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 write the code above like this?</p>
<pre><code>int addNumber(int a, int b){
return a + b;
}
</code></pre>
<p>I have this question because the second function doesn´t declare a 3rd variable. But would the compiler detect this in the first code?</p>
| <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
</code></pre>
<p>Only without optimization turned on, <a href="https://godbolt.org/g/Qfs4rO">there is a difference</a>:</p>
<pre><code>addNumber(int, int):
push rbp
mov rbp, rsp
mov DWORD PTR [rbp-20], edi
mov DWORD PTR [rbp-24], esi
mov edx, DWORD PTR [rbp-20]
mov eax, DWORD PTR [rbp-24]
add eax, edx
mov DWORD PTR [rbp-4], eax
mov eax, DWORD PTR [rbp-4]
pop rbp
ret
addNumber2(int, int):
push rbp
mov rbp, rsp
mov DWORD PTR [rbp-4], edi
mov DWORD PTR [rbp-8], esi
mov edx, DWORD PTR [rbp-4]
mov eax, DWORD PTR [rbp-8]
add eax, edx
pop rbp
ret
</code></pre>
<p>However, performance comparison without optimization is meaningless</p>
|
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 so I figured I'd make it into a session. And that didn't work either, no idea where to go from here. </p>
<p>Here's a button example:</p>
<pre><code><tr>
<td data-title="Name"><a href="#"><img src="banner.jpg" width="400"></a></td>
<td data-title="Link">
<form name="first" action="pending.php" method="POST"><input type="hidden" name="xz" value="one"><a class="mbutton" onclick="document.forms['first'].submit();">Gedaan</a></form>
</td>
<td data-title="Status"><p class="ptable"><?= $fgmembersite->One(); ?></p></td>
</tr>
</code></pre>
<p>Here's where the form leads to:</p>
<pre><code><?PHP
include("./include/membersite_config.php");
$_SESSION['postdata'] = $_POST;
$bname = $_SESSION['postdata'];
if($fgmembersite->Pending($bname))
{
$fgmembersite->RedirectToURL("index.php");
}
?>
</code></pre>
<p>So this should pass on $bname to the function Pending().</p>
<p>And here's pending:</p>
<pre><code>function Pending($bname)
{
if(!$this->DBLogin())
{
$this->HandleError("Database login failed!");
return false;
}
$result = mysql_query("Select * from $this->tablename where confirmcode='y'",$this->connection);
if(!$result || mysql_num_rows($result) <= 0)
{
$this->HandleError("Error");
return false;
}
$row = mysql_fetch_assoc($result);
$ux = $row['username'];
$ustat = $row['one'];
$bname = $_SESSION['postdata']['xz'];
$qry = "Update $this->tablename Set $bname='In behandeling' Where username='$ux'";
if(!mysql_query( $qry ,$this->connection))
{
$this->HandleDBError("Error inserting data to the table\nquery:$qry");
return false;
}
return true;
}
</code></pre>
| <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 order for a record to be inserted into table A. The ID field (numeric) in table A must be present in tables B or C.</p>
<p>I could however use a scalar UDF to check if the ID is valid, but this seems a bit like function abuse. I've done this a few times in my database already and although it works, it just looks 'wrong'.</p>
<p>Back to the triggers, I can't decide which trigger I would need to use in this case as they seem to both work, except the error is caught at different stages.</p>
<p>Using an INSTEAD OF trigger will catch the invalid ID before it is inserted/updated, but the code for this trigger seems a little bit over complicated. (Takes 12 variables and a long unwieldy INSERT statement)</p>
<p>An AFTER trigger will perform the same task, but the error is caught after the row is inserted and then the operation is rolled back.</p>
<p>Now despite all three of these approaches working, one of these must be more 'appropriate' for the task?</p>
| <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)
RETURNS BIT
BEGIN
IF (@Age IS NULL OR @Age >= 18)
RETURN 1
RETURN 0;
END;
-- Add check constraint
ALTER TABLE dbo.Employee
ADD CONSTRAINT Chk_verifyAge CHECK (dbo.verifyAge(Age) = 1)
GO
-- Test check Constraint
INSERT INTO dbo.Employee
( ID, Name, Age )
VALUES ( 1, 'Dummy',17)
GO
</code></pre>
<p><a href="http://i.stack.imgur.com/9crZD.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/9crZD.jpg" alt="enter image description here"></a></p>
|
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, 320, UIColor.Blue);
Tile tile3 = new Tile(320, 320, UIColor.Blue);
Tile tile4 = new Tile(320, 320, UIColor.Blue);
public GameScene(IntPtr handle) : base(handle)
{
}
public override void DidMoveToView(SKView view)
{
tile1.numberOfTiles = 4;
tile1.tileNumber = 1;
tile1.setTilePosition();
tile2.numberOfTiles = 4;
tile2.tileNumber = 2;
tile2.setTilePosition();
tile3.numberOfTiles = 4;
tile3.tileNumber = 3;
tile3.setTilePosition();
tile4.numberOfTiles = 4;
tile4.tileNumber = 4;
tile4.setTilePosition();
this.AddChild(tile1.tile);
this.AddChild(tile2.tile);
this.AddChild(tile3.tile);
this.AddChild(tile4.tile);
Console.WriteLine(this.Frame.Size);
}
public override void TouchesBegan(NSSet touches, UIEvent evt)
{
}
public override void Update(double currentTime)
{
// Called before each frame is rendered
}
}
</code></pre>
<p>As you can see, the tiles are set to be 320, 320 in size. The positions are also set in the same ratio, which should be correct. However, this is the output in the simulator</p>
<p><a href="http://i.stack.imgur.com/W73Z0.png" rel="nofollow"><img src="http://i.stack.imgur.com/W73Z0.png" alt="enter image description here"></a></p>
<p>As you can see, the tiles are way too big to fit on the screen, and the positions are incorrect. How would I solve this? If there is code needed to solve this, swift or c# are both ok. Any help would be appreciated.</p>
| <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 the
scene up to the farthest borders while maintaining aspect ratio. This
will result in cropping on the closer borders of the device in lieu of
black borders on the farthest borders</p>
<p><strong>.AspectFit:</strong> This will scale the scene up to the closest borders while
maintaining aspect ratio. This will result in black borders on the
farthest borders of the device in lieu of cropping on the closer
borders</p>
<p><strong>.Fill:</strong> This will scale the scene on both sides, but will not retain
aspect ratio, giving you no cropping or black borders, but will yield
in distortion of images via a fatty or slimming effect</p>
<p><strong>.ResizeFill:</strong> This will resize the scene coordinates to that of the
view it is in. This means there is no scaling, and on larger devices
the sprites will appear smaller, with more visibility to the entire
scenes contents.</p>
</blockquote>
<ul>
<li><p>2nd:</p>
<p>You need to understand that the default origin for the scene is the bottom left corner, while all children inside the scene have it in the center. When plotting your points, you need to take this into effect.</p></li>
</ul>
<p>Now from what I am seeing here, you have <code>.ResizeFill</code> going on, and you are assuming origin of the scene is bottom left. So what is happening is your scene is getting resized to that of the IPhone 5, and due to this resize, your tiles are now off location because the center of the scene changed from the point (512,384) to point (160,284) meaning you need to ass/subtract less than you would on the phone as you would the iPad.</p>
<p>My suggestion is to use <code>.AspectFill</code> for a <code>ScaleMode</code>, and to set the scenes <code>AnchorPoint</code> to (0.5,0.5)</p>
|
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,username,email is LIKE %text% and user city is NY
Of course when there is no city in params there is no included in query in the same way where is no text show all users from city. I want to know your solutions for this case.
Greetings</p>
| <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><code>def index
@user = User.all
@user = User.search(params[:search]) if params[:search].present?
end
</code></pre>
<p>Then just do up a simple form in your views to get the data </p>
<pre><code><%= form_tag(users_path, method: :get) do %>
</code></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 code in the same way the 9 labels in the original VC are handled. </p>
<p>Can I just make the new ViewController's class the same class as the original if I make sure that in the code the 10th label is safely unwrapped? Or does every IBOutlet in the code need to have a connection in the storyboard?</p>
| <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[1:])]Â
</code></pre>
<p>So I am making this function for a demonstration which takes a list of values called <code>valz</code> and takes the cube of each value and then returns a list of these cubes.</p>
<p>For example, let's say the input is <code>[-1,2,-3,4,-5]</code> - it should return <code>[-1,8,-27,64,-125]</code> but it returns <code>[-1, [8, [-27, [64, [-125, 0]]]]]</code>.
What is causing the extra brackets? If I remove the brackets in the code then it either gives the sum of these cubes (which is not correct) or it gives an error (something about adding an <code>int</code> to a <code>list</code>). I tried to debug this and even had my friend take a look but we're both pretty stumped.</p>
| <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 by scrolling left/right. However, this is a bit inconvenient and I was wondering if there was an elegant way to display the table with "foldover":</p>
<p><a href="http://i.stack.imgur.com/2Aten.png" rel="nofollow"><img src="http://i.stack.imgur.com/2Aten.png" alt="enter image description here"></a></p>
<p>To generate the above, I manually chopped up the dataframe into chunks and displayed each chunk (which is why the spacing/etc is not perfect).</p>
<p>I was wondering if there was a way to do something like the above more cleanly, possibly by changing pandas or jupyter settings?</p>
| <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([range(200)])
cols = df.shape[1]
for i in range(0,cols,30):
display(df.iloc[:,i:i+30])
</code></pre>
<p>EDIT: Forgot to add a pic of the output</p>
<p><a href="http://i.stack.imgur.com/UT7ya.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/UT7ya.jpg" alt="enter image description here"></a></p>
|
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 sort,the interpreter show me the error message,and obviously there is no built_in function or method in my code:</p>
<blockquote>
<pre><code>Traceback (most recent call last):
File "F:/alogrithm/wzysort/cal_time.py", line 13, in <module>
bubble.bubble_sort(generate_random_list())
File "F:\alogrithm\wzysort\bubble.py", line 4, in bubble_sort
if a[indx] > a[indx+1]:
TypeError: unorderable types: builtin_function_or_method() > builtin_function_or_method()
</code></pre>
</blockquote>
<p>cal_time.py:</p>
<pre><code>import time
from wzysort import bubble
import random
def generate_random_list():
result = []
for i in range(10):
result.append(random.random)
return result
time_start = time.time()
bubble.bubble_sort(generate_random_list())
time_end = time.time()
print(time_end - time_start)
</code></pre>
<p>bubble.py:</p>
<pre><code>def bubble_sort(a):
for i in range(len(a)-1):
for indx in range(len(a[:-i-1])):
if a[indx] > a[indx+1]:
a[indx], a[indx + 1] = a[indx + 1], a[indx]
</code></pre>
| <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>Instead, you want to call the method:</p>
<pre><code>result.append(random.random())
</code></pre>
|
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 internally calls addConstraint)</p>
<p>Option 1:</p>
<pre><code>parent.addConstraints([
child.topAnchor.constraint(equalTo: parent.topAnchor, constant: 20),
child.leftAnchor.constraint(equalTo: parent.leftAnchor, constant: 5) ])
</code></pre>
<p>Option 2:</p>
<pre><code>child.topAnchor.constraint(equalTo: parent.topAnchor, constant: 20).isActive = true
child.leftAnchor.constraint(equalTo: parent.leftAnchor, constant: 5).isActive = true
</code></pre>
<p>My question is, is there any benefit to doing one over the other? (performance/etc) or does it come purely down to style.</p>
<p><em>(I don't think constraints are evaluated until the next layout pass, so I don't think it should matter that we add them one-by-one instead of in a block??)</em></p>
<p>If it is just style, what's the "more preferred" style by the community??</p>
<p><em>(personally I prefer addConstraints, however it's very close and I could be easily swayed to .isActive)</em></p>
| <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
property to YES instead of calling the addConstraint: method directly.
The active property automatically adds and removes the constraint from
the correct view. (<a href="https://developer.apple.com/reference/uikit/uiview/1622523-addconstraint" rel="nofollow">reference</a>)</p>
</blockquote>
<p>Also if you look at the interface definition for <code>addConstraint:</code> it has this comment:</p>
<blockquote>
<p>// This method will be deprecated in a future release and should be
avoided. Instead, set NSLayoutConstraint's active property to YES</p>
</blockquote>
<hr>
<p>With that being said, there is actually a 3rd [and probably better] alternative, which is to use <code>NSLayoutConstraint</code>'s class method <code>activateConstraints:</code>:</p>
<pre><code>NSLayoutConstraint.activateConstraints([
child.topAnchor.constraint(equalTo: parent.topAnchor, constant: 20),
child.leftAnchor.constraint(equalTo: parent.leftAnchor, constant: 5) ])
</code></pre>
<p>This is also a recommended solution according to the documentation and interface files. So if you have multiple constraints, this would be an easy solution and probably preferred in your situation.</p>
<p>(interface comment; emphasis mine):</p>
<blockquote>
<p>Convenience method that activates each constraint in the contained
array, in the same manner as setting active=YES. <strong>This is often more
efficient than activating each constraint individually.</strong></p>
</blockquote>
|
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 spacebar each 5 secondes in jQuery</a> " is what i want but i cant adapt it due to lack of knowledge.</p>
<p>I cant create buttons like they do in that example, so when the page loads the script should start and focus the button and press spacebar repeatdly.</p>
| <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 = 5000; //in milliseconds
$(document).ready(function() {
$("#test").on("keypress", function(e) {
if (e.which == 32) {
presscount++;
}
$("#output").text("The space key was pressed " + presscount + " times");
});
setInterval(pressKey, sendEvery);
});
function pressKey() {
var e = jQuery.Event("keypress");
e.which = 32; // # space
$("#test").trigger(e);
}
</code></pre>
|
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>
| <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>There is a button "GO", its page source code like this:</p>
<pre><code>button type="submit" name="submit" id="submit" class="search-button"...
</code></pre>
<p>Now, click this button</p>
<pre><code>>>> browser.find_element_by_id("submit").click()
</code></pre>
|
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 screens.</p>
<p>CSS:</p>
<pre><code>ul {
list-style: none;
padding-left: 0;
}
.row {
text-align: center;
}
@media (min-width: 768px) {
.image,
.text {
display: inline-block;
width: 50%;
vertical-align: middle;
}
/* alternate */
.row:nth-child(odd) .image {
float: right;
}
/* clearfix */
.row:before,
.row:after {
content: " ";
display: table;
}
.row:after {
clear: both;
}
}
</code></pre>
<p>HTML:</p>
<pre><code><ul>
<li class="row">
<div class="image">
<img src="http://placehold.it/350x150">
</div><div class="text">
<p>Lorem ipsum</p>
</div>
</li>
<li class="row">
<div class="image">
<img src="http://placehold.it/350x150">
</div><div class="text">
<p>Lorem ipsum</p>
</div>
</li>
<li class="row">
<div class="image">
<img src="http://placehold.it/350x150">
</div><div class="text">
<p>Lorem ipsum</p>
</div>
</li>
</ul>
</code></pre>
<p>I know I can do this with flexbox, which I can't use in this project. And using <code>float: left</code> doesn't allow me to vertically align the elements. What other options do I have?</p>
<p><strong>NB:</strong> I'm using <code>display: inline-block</code> for these columns, as they vary in height and I'd like them to be aligned vertically to one another.</p>
<p><strong>Edit:</strong> I've <a href="http://codepen.io/benjibee/pen/xEWgoy" rel="nofollow">made a CodePen</a> with the example using floats as shown above.</p>
| <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">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul {
margin: 0;
padding: 0;
width: 100%;
}
.row {
width: 100%;
display: table;
table-layout: fixed;
}
.row:nth-child(even) {
direction: rtl;
}
.row:nth-child(odd) .image {
text-align: right
}
.image,
.text {
display: table-cell;
direction: ltr;
border: solid;
}
.text {
background: tomato;
}
img {vertical-align:top;}
@media screen and (max-width: 640px) {
.row,
.image,
.text {
display: block;
direction:ltr
}
.row:nth-child(odd) .text {
text-align: right
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
<li class="row">
<div class="image">
<img src="http://placehold.it/350x150">
</div>
<div class="text">
<p>Lorem ipsum</p>
</div>
</li>
<li class="row">
<div class="image">
<img src="http://placehold.it/350x150">
</div>
<div class="text">
<p>Lorem ipsum</p>
</div>
</li>
<li class="row">
<div class="image">
<img src="http://placehold.it/350x150">
</div>
<div class="text">
<p>Lorem ipsum</p>
</div>
</li>
</ul></code></pre>
</div>
</div>
</p>
|
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 format from above row and autofill down.</li>
</ol>
<p>So far, able to get below code for single sheet based on selection of cell</p>
<p>Hoping to get some answers...</p>
<pre><code>Sub Insert_Row()
If Selection.Rows.Count > 1 Then Exit Sub
With Selection
.EntireRow.Copy
.Offset(1).EntireRow.Insert
Application.CutCopyMode = False
On Error Resume Next
.Offset(1).EntireRow.SpecialCells(xlCellTypeConstants).ClearContents
On Error GoTo 0
End With
End Sub
</code></pre>
| <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:
On Error GoTo 0
MsgBox("Please try again with a number.")
Exit Sub
NumericEntry:
For i = 1 to 19
Sheets(1).Select
Rows(SelRow).copy
Sheets(i).Select
Rows(j).Insert
On Error Resume Next
Rows(j).SpecialCells(xlCellTypeConstants).ClearContents
On Error GoTo 0
Next i
End Sub
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.