input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Spotify docker-maven-plugin unauthorized: authentication required public repo <p>I am having trouble pushing my docker image to the hub using the following command:</p>
<pre><code>mvn clean package docker:build -DpushImage
</code></pre>
<p>Each time I get the following response:</p>
<pre><code>[WARNING] Failed to push jdruwe/k8s-product-owner, retrying in 10 seconds (5/5).
...
[ERROR] Failed to execute goal com.spotify:docker-maven-plugin:0.4.13:build (default-cli) on project k8s-product-owner: Exception caught: unauthorized: authentication required -> [Help 1]
</code></pre>
<p>When I try to login using one of the following commands, I keep getting the errors even tough the login succeeded</p>
<pre><code>docker login -u jdruwe https://index.docker.io/v1/
OR
docker login
</code></pre>
<p>I did create an empty repo on hub just to try fixing it:</p>
<p><a href="http://i.stack.imgur.com/gPp35.png" rel="nofollow"><img src="http://i.stack.imgur.com/gPp35.png" alt="enter image description here"></a></p>
<p>Any ideas?</p>
| <p>Did you correctly configure the authentication settings? </p>
<p>User and password can be set in <strong>settings.xml</strong>:</p>
<pre><code><servers>
<server>
<id>docker-hub</id>
<username>jdruwe</username>
<password>secret-password</password>
<configuration>
<email>foo@foo.bar</email>
</configuration>
</server>
</servers>
</code></pre>
<p>Then, the <strong>pom</strong> references these settings:</p>
<pre><code> <plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>VERSION GOES HERE</version>
<configuration>
[...]
<serverId>docker-hub</serverId>
<registryUrl>https://index.docker.io/v1/</registryUrl>
</configuration>
</plugin>
</code></pre>
<p>More detailed information can be found here: <a href="https://github.com/spotify/docker-maven-plugin#authenticating-with-private-registries" rel="nofollow">https://github.com/spotify/docker-maven-plugin#authenticating-with-private-registries</a></p>
|
Which Eyeshot entity is more efficient? <p>I am using the WPF Control Eyeshot (<a href="http://www.devdept.com/" rel="nofollow">http://www.devdept.com/</a>) to build an application where I handle multiple 3D entities, but <strong>I do not perform boolean operations between them</strong>. </p>
<p>Eyeshot offers me the following options for entities of this sort (cylinders, spheres, cubes, etc): Mesh, Solid, Surface or Solid3D.</p>
<p>I am confused on which one of these should I use, as they all suffice my needs.</p>
<p>Which one is more efficient in memory consumption and performance?</p>
| <p>Mesh, definitely. Possibly with <code>Mesh.LightWeight = true</code>. This is the most cheap 3D object representation inside Eyeshot. It relies only on <code>Mesh.Vertices</code> and <code>Mesh.Triangles</code> arrays.</p>
|
C++ 'Word Jumble' <p>I have a small problem. I have attempted to make the game 'Word Jumble' with a scoring system. But sometimes, when the computer guesses a word, then it'll say: The word is: <em>blank here</em>. There should be a jumbled word there. When I try any word, it just subtracts 1.#INF points.</p>
<p>Code:</p>
<pre><code>#include<iostream>
#include<string>
#include<stdlib.h>
#include<time.h>
using namespace std;
const int size=10;
string Words[size] = {
"consecutive",
"alternative",
"consequently",
"jumbled",
"computer",
"charger",
"food",//I'm hungry
"library",
"strawberry",
"carrier"
};
string Hints[size] = {
"Following continuously.",
"Something available as another opportunity.",
"As a result.",
"This word is rather jumbled, isn't it ;)",
"The enitiy you are reading this off of",
"My phone battery is running low",
"I'm hungry, I need some _",
"Where can I go get a book?",
"It's red, and not a berry."
"Either carries stuff, or is what your data company is called."
};
void main()
{
string word,hint;
double points=0;
bool correct=false,playAgain=true;
cout << "Welcome to Word Jumble!\n";
cout << "The objective of this game is to guess the jumbled word, correctly.\n";
cout << "Say 'quit' to quit, or 'hint' for a hint.\n";
while (playAgain==true)
{
correct = false;
int guesses = 0;
srand(static_cast<unsigned int>(time(0)));
int num = rand() % size + 1;
word = Words[num];
hint = Hints[num];
string jumble = word;
int length = jumble.size();
for (int i = 0; i < length*2; ++i)
{
int index1 = (rand() % length);
int index2 = (rand() % length);
char temp = jumble[index1];
jumble[index1] = jumble[index2];
jumble[index2] = temp;
}
cout << "The word is: " << jumble << endl;
double tempPoints=0;
while (correct==false)
{
string theGuess;
cout << "Guess the word: ";
cin >> theGuess;
guesses++;
while (!cin)
{
cin.sync();
cin.clear();
cout << "Ivalid entry, try again: ";
cin >> theGuess;
}
if (theGuess == word)
{
cout << "Correct! You guessed the word in only " << guesses << " tries!\n";
tempPoints += jumble.size()*1.5;
tempPoints -= (guesses - 1) / 4.0;
points += tempPoints;
cout << "You have been awarded " << tempPoints << " points this round for a total of " << points << "!\n";
correct = true;
cout << "Would you like to play again? (y or n): ";
char tempYN;
cin >> tempYN;
while (!cin || tempYN != 'y' && tempYN != 'n')
{
cin.sync();
cin.clear();
cout << "Invalid entry.\nWould you like to play again? (y or n): ";
cin >> tempYN;
}
if (tempYN == 'y')
{
playAgain = true;
}
else
{
playAgain = false;
}
}
else if (theGuess == "hint")
{
tempPoints -= (1.0 / (jumble.size())) * 40;
cout << "Hint: " << hint << endl;
correct = false;
playAgain = true;
}
else if (theGuess == "quit")
{
correct = true;
playAgain = false;
}
else
{
double sub = (1.0 / (jumble.size())) * 20;
cout << "Incorrect word, deducting "<<sub<<" points\n";
tempPoints -= sub;
playAgain = true;
correct = false;
}
};
};
cout << "Goodbye\n";
}
</code></pre>
| <p>In the line:</p>
<pre><code>int num = rand() % size + 1;
</code></pre>
<p>You are saying to select a random number between 0 and 9 then add 1. </p>
<p>If the random number is 9 the + 1 will make it 10. This means that you are trying to access a value in the array <code>Words</code> and <code>Hints</code> at index 10. Since arrays are 0 indexed and it's size is 10 that means you only have elements at 0 - 9.</p>
<p>You also will never get the first string in the arrays.</p>
|
Creating and printing linked list from user input C++ <pre><code>#include <iostream>
using namespace std;
int main()
{
struct node
{
int data;
node * next;
};
node * head;
node * n;
node * temp;
node * q;
int number;
cout << "Enter numbers";
cin >> number;
n = new node;
n->data = number;
head = n;
temp = n;
while (cin >> number)
{
while (number != -500)
{
n = new node;
n->data = number;
temp->next = n;
temp = n;
}
}
while (head != NULL)
{
cout << head->data;
head = head->next;
}
}
</code></pre>
<p>I don't understand why this would not work. The program creates a new node then sets whatever the user entered equivalent to the variable data of that new node then it makes head and temp point to the new node. Then it gets the users second input and compares it to -500 and if it evaluates as true it creates a new node puts the data of the second input into the variable data then it links the first node and second node together then it makes temp point to the second node. If the condition of the 2nd while loop is false it goes to the third which is where it is suppose to print the list. </p>
| <p>Who sets the last node's next to NULL?</p>
<p>At n = new node; n->next is not NULL but undefined, in Debug versions usually it is 0xcccccccc or something similar value to make it visible that it is not initialized. If you try to dereference it, you will get an access violation.</p>
|
Changing colors of a group of shapes without selecting (fill & text) <p>With regard to the following code:</p>
<pre><code>Sub Macro1 ()
With ActiveSheet.Shapes.Range(Array("MyShapeGroup"))
.Fill.ForeColor.RGB = cPurp ''cPurp is global constant
.TextFrame.Characters.Font.ColorIndex = 2
End With
End Sub
</code></pre>
<p>I can execute the macro with only the change to the fill color, however, when I add in the text color change I get an Application-defined or object-defined error.</p>
<p>So I tried this:</p>
<pre><code>Sub Macro1()
With ActiveSheet.Shapes.Range(Array("MyShapeGroup")).ShapeRange
.Fill.ForeColor.RGB = cPurp
.TextFrame.Characters.Font.ColorIndex = 2
End With
End Sub
</code></pre>
<p>Which throws an 'Object doesn't support this property or method' on the <code>With</code> line.</p>
<p>Also tried this:</p>
<pre><code>Sub Macro1()
With ActiveSheet.Shapes.Range(Array("MyShapeGroup"))
.Fill.ForeColor.RGB = cPurp
.ShapeRange.TextFrame.Characters.Font.ColorIndex = 2
End With
End Sub
</code></pre>
<p>Which throws another 'Object doesn't support this property or method' on the <code>.ShapeRange</code> line. </p>
<p>Also tried this:</p>
<pre><code>Sub Macro1 ()
ActiveSheet.Shapes.Range(Array("MyShapeGroup")).Select
With Selection.ShapeRange
.Fill.ForeColor.RGB = cPurp ''cPurp is global constant
.TextFrame.Characters.Font.ColorIndex = 2
End With
End Sub
</code></pre>
<p>How can I efficiently do both the fill color change and the text color change without using a select? </p>
| <p>Try using the <code>TextFrame2.TextRange</code> property instead:</p>
<pre><code>Option Explicit
Sub test()
Dim shp As Shape
For Each shp In ActiveSheet.Shapes.Range(Array("MyShapeGroup"))
shp.Fill.ForeColor.RGB = RGB(255, 255, 0)
shp.TextFrame2.TextRange.Font.Fill.ForeColor.RGB = RGB(0, 255, 255)
Next
End Sub
</code></pre>
|
Is there a way to send (python) code to a server to compile and run but display the results on the computer that sent them? <p>I just bought a server and was wondering if there was a way to run the code remotely but store/display the results locally. For example, I write some code to display a graph, the positions on the graph are computed by the (remote) server, but the graph is displayed on the (local) tablet. </p>
<p>I would like to do this because the tablet I carry around with me on a day-to-day basis is very slow for computational physics simulations. I understand that I can setup some kind of communications protocol that allows the server to compute things and then sends the computations to my tablet for a script on my tablet to handle the data. However, I would like to avoid writing a possibly new set of communications scripts (to handle different formats of data) every single time I run a new simulation.</p>
| <p>This is a complete "<a href="http://therussiansusedapencil.com/post/175863624/the-pencil" rel="nofollow">The Russians used a pencil</a>" solution, but have you considered running a VNC server on the machine that is doing the computations? </p>
<p>You could install a VNC client onto your tablet/phone/PC and view it that way, there are tons of them available. No need to go about creating anything from scratch.</p>
|
Inspect shows record but still get undefined method <p>I'm creating a report screen, and doing my relationship lookups for the associated data. For some reason I keep getting errors when trying to get an attribute of the relationship, yet .inspect shows the information plain as day.</p>
<pre><code>orders_detail.products_cost.flavor.inspect
</code></pre>
<p>outputs</p>
<pre><code> #<Flavor flavor_id: 13, identifier: "BR", description: "Blue Razz">
</code></pre>
<p>however</p>
<pre><code>orders_detail.products_cost.flavor.flavor_id
</code></pre>
<p>outputs</p>
<pre><code>undefined method `flavor_id' for nil:NilClass
</code></pre>
<p>models</p>
<pre><code>class OrdersDetail < ActiveRecord::Base
self.table_name = "orders_detail"
belongs_to :orders_header, foreign_key: 'order_header_id'
belongs_to :address
belongs_to :products_cost
belongs_to :machine, foreign_key: 'machine_id'
end
class ProductsCost < ActiveRecord::Base
self.table_name = "products_cost"
belongs_to :product
belongs_to :size
belongs_to :units_of_measure, foreign_key: "uom_id"
belongs_to :flavor
validates :product_id, :presence => true
validates :flavor_id, :presence => true
validates :size_id, :presence => true
validates :uom_id, :presence => true
end
class Flavor < ActiveRecord::Base
has_many :product_costs
end
</code></pre>
| <p>As per discussion in comments to question, having that each of below works as expected:</p>
<pre><code>Flavor.first.flavor_id
Flavor.first.attributes
</code></pre>
<p>means, that attributes reading is not broken. The only reason is that as per error: you are referencing bad/invalid/inexistent object <code>flavor</code>.</p>
|
Java EE read resources from dispatched html <p>I'm building a servlet that uses a RequestDispatcher to load a html page for the log in.</p>
<p>The html is in /WEB-INF/templates/main.html</p>
<p>I'm trying to load an image for that html file which is on /WEB-INF/resources/image.jpg</p>
<p>I've tried with <code><img src="/WEB-INF/resources/image.jpg</code>, and also without the slash before WEB-INF.</p>
<p>I tried with <code><img src="../resources/image.jpg</code>as well.</p>
<p>None seems to work, how can I do this?</p>
| <p>You can't do this.</p>
<p>The problem is that the image is being loaded by the browser, not the application. And nothing outside the internals of the application can access anything in the <code>WEB-INF</code> directory.</p>
<p>So, you simply need to move the image someplace else.</p>
|
Is there a way to revert or undo replica set configuration <p>I have two standalone nodes, which have mongodb running on them. Both of them have a replica set configuration rs0 and start with <i>rs.initiate()</i>. But in some scenarios, I want them to run as individual nodes, but in some cases, I want one to become primary and one to become secondary. But since I have done <i>rs.initiate()</i> on both, I won't be able to add any node as secondary. So is there a way to undo the replica set configuration so that I can enable adding the secondary node.</p>
| <p>you can simply prepare a new config document and reconfigure the replication.</p>
<p>rs.reconfig(new_config_file)</p>
|
SSRS - How to hide parent report's header in a subreport? <p>I've to create a report that must be printed along with an existing report. Since the dataset is largely the same, I've created this new report as a sub-report to the existing report, and have added a before page break. So now both the existing report and (new) sub-report print on separate pages. The problem is that the header of the existing report gets printed on the sub-report also. </p>
<p>Is there a way to suppress/ hide parent report's header from the sub-report?</p>
| <p>I guees SSRS doesn't allow to do exactly what your want, but if your subreport is on the last page, you can set PrintOnLastPage = False for report header, then it will not be printed, although I'm not sure how it will look if subreport generates many pages, I afraid that only the last of subreport's pages will be without header.
In that case all you can do is hacks - you can conditionally hide all report items inside header, setting their Hidden property to smth like this <code>=IIf(Globals!PageNumber > YOUR_PAGE_NUMBER, True, False)</code>.
Or, if first part (parent report) generates unknown amount of pages, you can use PageName instead of PageNumber, and update report to change page name for subreport pages, f.e. by wrapping subreport into rectangle and specifying page name for rectangle. Expression then will be <code>=IIf(Globals!PageName = "YOUR_SUBREPORT_PAGE_NAME", True, False)</code>.</p>
|
Smart pointers and cache/memory locality <p>I am trying to understand smart pointers in context of locality. I have looked at several questions here on S/O regarding having a <code>std::vector</code> of <code>MyObject</code>s and a <code>std::vector</code> of smart pointers (<code>shared_ptr</code>/<code>unique_ptr</code>) to <code>MyObject</code>s.</p>
<p>What I haven't found the answer to is, if I have a vector of 1000 smart pointers to <code>MyObject</code>s (using <code>make_shared</code>/<code>make_unique</code>), are the objects themselves stored in random locations in memory and the smart pointers stored in a contiguous block of memory in the vector, or are the pointers and the object both stored in the contiguous block of memory in the vector?</p>
| <p>At least the elements in a vector are guaranteed to be stored contiguously. This is per the recent C++ standards.</p>
<p>The objects pointed to by the smart pointer are stored somewhere else. It will depend on the memory manager where your object will end up.</p>
<p>If you have a choice, it might be better (and faster) to store the objects directly into the vector. A pointer adds an extra layer of indirection which could slow your program down.</p>
|
How to 'Post Follow' request in AJAX <p>I try to implement Slimpay payment solution API. But I have a problem during the process.</p>
<p>From this ressource (I got from a previous request) : </p>
<pre><code>{
"_links" : {
"self" : {
"href" : "https://api-sandbox.slimpay.net/"
},
"profile" : {
"href" : "https://api-sandbox.slimpay.net/alps/v1"
},
"https://api.slimpay.net/alps#create-orders" : {
"href" : "https://api-sandbox.slimpay.net/orders"
}
}
</code></pre>
<p><strong>How to Follow a Link on the last Resource to create a HTTP Post Request ?</strong></p>
<p>I have to POST this request :</p>
<pre><code> POST Follow(https://api.slimpay.net/alps#create-orders)
Accept: application/hal+json; profile="https://api.slimpay.net/alps/v1"
Authorization: Bearer token
Content-Type: application/json
</code></pre>
<p><strong>How should I write my request in Ajax ?</strong></p>
<p>I don't get the :</p>
<pre><code> POST Follow(https://api.slimpay.net/alps#create-orders)
</code></pre>
<p>If I use :</p>
<pre><code> $.ajax({
url: 'https://api.slimpay.net/alps#create-orders',
type: 'Post',
contentType: 'application/json,
headers: {'Authorization': 'Bearer ' + token},
dataType: 'json',
</code></pre>
<p>==> this give a 401. It seems I lost the token.</p>
| <p>"Follow(namespace#relation)" means look for the <code>namespace#relation</code> key in the <strong>_links</strong> attribute of the last response you got from the server.</p>
<p>In your case, the last request you sent is: <code>GET https://api-sandbox.slimpay.net/</code> and you already quoted the response from the server. The actual URL is in the <strong>href</strong> property of the <code>https://api.slimpay.net/alps#create-orders</code> object. This is the URL you have to send your POST request to.</p>
<p>In other terms, <code>POST https://api-sandbox.slimpay.net/orders</code> is your next step in this case.</p>
<hr>
<h2>Quick word about Hypermedia in REST APIs</h2>
<p>Hypermedia is all about getting the entry point and then following relations from this entry point leaving the responsibility of building the URLs to the server.</p>
<p>It's kind of like a website where you would type the domain (e.g. stackoverflow.com) and then click on the links by using their name, not the actual URL behind. The URL may change, the name of the link won't, ever.</p>
<p>So just like you don't bookmark all the URLs of a website, you should not hard code URLs you got from the <code>_links</code> object.</p>
<p>This is a really quick idea of hypermedia, you can look for more information about it on the web.</p>
|
eregi or preg from txt file in php <p>I have website selling charge cards, I use this code for selling to customers they verify the mobile number, manually (add a line every time) recently I use SMS service and numbers stored in text file in the site, how can remove these lines, and I get the numbers from the .txt files? (the numbers stored line by line in txt file)</p>
<pre><code>if ($data[mobile] AND !eregi("^09512362982$", $data[mobile]))
if ($data[mobile] AND !eregi("^09527415120$", $data[mobile]))
if ($data[mobile] AND !eregi("^09532247462$", $data[mobile]))
if ($data[mobile] AND !eregi("^09535241919$", $data[mobile]))
if ($data[mobile] AND !eregi("^09535716327$", $data[mobile]))
$error .= "Mobile number not valid, please verify your number<br />";
</code></pre>
| <p>You can use <code>file</code> to read the contents of your text file into an array, and then <code>in_array</code> to see if the number is there.</p>
<pre><code>if (in_array($_data['mobile'], file('your_text_file.txt', FILE_IGNORE_NEW_LINES))) {
$error .= "Mobile number not valid, please verify your number<br />";
}
</code></pre>
|
Concatenate unsigned char[] value and convert to char * <p>I'm using Java NDK in order to extract some info from a "bin" file using a C struct. I have to extract info about a gateway, in for loop. I'm able to extract info, but I need to concatenate the results and add dot <code>.</code> in order to print the final IP and convert it to <code>char*</code> or <code>string</code>.
I used <code>reinterpret_cast</code> but it doesn't work. </p>
<p>How can I convert the IP address to a string?</p>
<pre><code>#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
//Gateway.info[4] is unsigned char type
int config_len = sizeof(ptr->Gateway.info);
for (int i = 0; i < config_len; i++) {
int number = ptr->Gateway.info[i];
}
LOGD("GATEWAY %d",number);
</code></pre>
<hr>
| <p>I made a mistake. It works!</p>
<pre><code>#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
string Result;
ostringstream convert;
//Gateway.info[4] is unsigned char type
int config_len = sizeof(ptr->Gateway.info);
for (int i = 0; i < config_len; i++) {
int number = ptr->Gateway.info[i];
convert << number;
Result = convert.str()
}
</code></pre>
|
Rounding up and down a number C++ <p>I'm trying to allow my program to round a number up and down respectively. </p>
<p>For example, if the number is <code>3.6</code>, my program is suppose to round up the nearest number which is 4 and if the number is <code>3.4</code>, it will be rounded down to 3.</p>
<p>I tried using the <code>ceil</code> library to get the average of 3 items.</p>
<p><code>results = ceil((marks1 + marks2 + marks3)/3)</code></p>
<p>However, the <code>ceil</code> only rounds the number down but does not roll the number up.</p>
<p>There's 1 algorithm i stumbled upon</p>
<p><code>var roundedVal = Math.round(origVal*20)/20;</code></p>
<p>but i still can't figure a formula for some problem.</p>
| <pre><code>std::ceil
</code></pre>
<p>rounds up to the nearest integer</p>
<pre><code>std::floor
</code></pre>
<p>rounds down to the nearest integer</p>
<pre><code>std::round
</code></pre>
<p>performs the behavior you expect</p>
<p>please give a use case with numbers if this does not provide you with what you need!</p>
|
C# Razor model and passing <p>How can I transfer data/model between partial/views/controllers in C# MVC?</p>
<p>I'm trying to duplicate <a href="http://www.tutorialsteacher.com/mvc/mvc-view" rel="nofollow">this</a> example, but the <code>@model IEnumerable<MVC_BasicTutorials.Models.Student></code> is given me an error, with red line under the <code>Model</code></p>
<p><code>_StudentList Partial.cshtml</code></p>
<pre><code>@model IEnumerable<MVC_BasicTutorials.Models.Student>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.StudentName)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.StudentName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.StudentId }) |
@Html.ActionLink("Details", "Details", new { id=item.StudentId }) |
@Html.ActionLink("Delete", "Delete", new { id = item.StudentId })
</td>
</tr>
}
</table>
</code></pre>
<p><code>StudentController</code>:</p>
<pre><code>public class StudentController : Controller
{
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public int Age { get; set; }
}
IList<Student> students;
public StudentController()
{
students = new List<Student>{
new Student() { StudentId = 1, StudentName = "John", Age = 18 } ,
new Student() { StudentId = 2, StudentName = "Steve", Age = 21 } ,
new Student() { StudentId = 3, StudentName = "Bill", Age = 25 } ,
new Student() { StudentId = 4, StudentName = "Ram" , Age = 20 } ,
new Student() { StudentId = 5, StudentName = "Ron" , Age = 31 } ,
new Student() { StudentId = 6, StudentName = "Chris", Age = 17 } ,
new Student() { StudentId = 7, StudentName = "Rob",Age = 19 } ,
};
}
// GET: Student
public ActionResult Index()
{
return View(students);
}
}
</code></pre>
<p><code>Index.cshtml</code>:</p>
<pre><code>@model IEnumerable<MVC_BasicTutorials.Models.Student>
<h3>Student List</h3>
<p>
@Html.ActionLink("Create New", "Create")
</p>
@{
Html.RenderPartial("_StudentList", Model);
}
</code></pre>
<p>I read this <a href="http://stackoverflow.com/a/11326470/2441637">http://stackoverflow.com/a/11326470/2441637</a> but could not get it solved :( if I run the app, I get an error at <code>@foreach (var item in Model)</code> that is <code>NullReferenceException: Object reference not set to an instance of an object.</code></p>
| <p>Your <code>Student</code> class is defined as a sub class of <code>StudentController</code>. So you need to use the proper namespace / fully qualified class name when using this class as the model type.</p>
<p>Change the first line to </p>
<pre><code>@model IEnumerable<PutYourNameSpaceHere.StudentController.Student>
</code></pre>
<p><em>You need to replace <code>PutYourNameSpaceHere</code> with the namespace under your <code>StudentController</code> class is</em></p>
<p><strong>Or</strong> </p>
<p>Move the <code>Student</code> class to a new file (or even existing), but under the namespace <code>MVC_BasicTutorials.Models</code></p>
<pre><code>namespace MVC_BasicTutorials.Models
{
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public int Age { get; set; }
}
}
</code></pre>
<p>When doing this, you need to make sure to have a using statement in your <code>StudentController</code> so that you can use this class</p>
<p>So add this as the first line of the <code>StudentController</code> class</p>
<pre><code>@using MVC_BasicTutorials.Models
</code></pre>
|
How to find number of Reference Planes passing through a selected wall. <p>I need to find out the number of Reference planes and their names which are passing through a selected wall. I can get all the reference planes for a particular document but how shall I do this for a particular wall.</p>
<p>You help would be appreciated!
Thanks.</p>
| <p>I would start by trying the built-in <code>ElementIntersectFilter</code>. The documentation has a nice example, replace "<code>FamilyInstance</code>" with "<code>referencePlane</code>" and that may do it.</p>
<p><a href="http://www.revitapidocs.com/2017/19276b94-fa39-64bb-bfb8-c16967c83485.htm" rel="nofollow">http://www.revitapidocs.com/2017/19276b94-fa39-64bb-bfb8-c16967c83485.htm</a></p>
<p>If that doesn't work, you'll need to extract the solid of the wall and intersect with the reference plane. </p>
|
Using If Statement With Formulas JAVA <p>I'm working on a workshop for my JAVA. There's one part I'm having difficulty understanding: <em>Apply the following formulas based on gender (must use an if statement(s)):</em>
<strong>Hmale_child = ((Hmother * 13/12) + Hfather)/2</strong> OR
<strong>Hfemale_child = ((Hfather * 12/13) + Hmother)/2</strong></p>
<p>How do I use an if statement with these formulas? I use the Hmale_child if the user inputs that their child's gender is male. But all the if statements I've seen have to do with numbers. Can anyone point me in the right direction?</p>
<p>Something like: if (gender == male) ??</p>
<hr>
<pre><code>import java.util.Scanner;
public class WKSP6Trial
{
public static void main(String[] args)
{
Scanner scannerObject = new Scanner(System.in);
Scanner inp = new Scanner(System.in);
String Letter;
String input = "";
String exit = "exit";
boolean isStringLetter = true;
System.out.println("Welcome! If at any time you wish to exit the program, type the word exit, and press enter.");
while(true)
{
System.out.println("\nPlease enter letters m or f only as you enter your child's gender: ");
input = inp.nextLine();
if(input.equalsIgnoreCase(exit)){break;}
isStringLetter = input.matches("[m/f/M/F]+");
if(isStringLetter == false)
{
System.out.println("\nYou entered a non letter " + input);
System.out.println("Remove all non letters aside from m or f from your input and try again !");
break;
}
System.out.println("You entered the gender of your child.");
System.out.println("Next enter the height of the child's father in feet followed by ");
System.out.println("the father's height in inches: ");
int n1, n2;
n1 = scannerObject.nextInt();
n2 = scannerObject.nextInt();
System.out.println("You entered " + n1 + " followed by " + n2);
System.out.println("Finally, enter the height of the child's mother followed by ");
System.out.println("the mother's height in inches: ");
int d1, d2;
d1 = scannerObject.nextInt();
d2 = scannerObject.nextInt();
System.out.println("You entered " + d1 + " followed by " + d2);
Scanner in = new Scanner(System.in);
System.out.print("Convert from: ");
String fromUnit = in.nextLine();
System.out.print("Convert to: ");
String toUnit = in.nextLine();
//below is what I'm uncertain of
if(gender == m)
Hmale_child = ((Hmother * 13/12) + Hfather)/2;
}
}
}
</code></pre>
| <p>You can use the <code>equals</code> or <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#equalsIgnoreCase-java.lang.String-" rel="nofollow"><code>equalsIgnoreCase</code></a> methods to check your string inputs:</p>
<pre><code>if (gender.equalsIgnoreCase("m")) {
child = ((Hmother * 13.0/12) + Hfather)/2.0;
else { // alternatively - check if the gender is female, just to be sure
child = ((Hfather * 12.0/13) + Hmother)/2.0;
}
</code></pre>
<p><strong>EDIT:<br/></strong>
If you absolutely cannot use an <code>else</code> block, the same logic can be expressed as two <code>if</code> statements, as a gender can't be both <code>"m"</code> and <code>"f"</code>:</p>
<pre><code>if (gender.equalsIgnoreCase("m")) {
child = ((Hmother * 13.0/12) + Hfather)/2.0;
}
if (gender.equalsIgnoreCase("f")) {
child = ((Hfather * 12.0/13) + Hmother)/2.0;
}
</code></pre>
|
Replace variables extracted from database with theirs values <p>I'd like to translate a perl web site in several languages. I search for and tried many ideas, but I think the best one is to save all translations inside the mySQL database. But I get a problem...</p>
<p>When a sentence extracted from the database contains a variable (scalar), it prints on the web page as a scalar:</p>
<pre><code>You have $number new messages.
</code></pre>
<p>Is there a proper way to reassign <code>$number</code> its actual value ?</p>
<p>Thank you for your help !</p>
| <p>You can use <code>printf</code> format strings in your database and pass in values to that.
<code>printf</code> allows you to specify the position of the argument so only have know what position with the list of parameters "$number" is.</p>
<p>For example</p>
<pre><code>#!/usr/bin/perl
use strict;
my $Details = {
'Name' => 'Mr Satch',
'Age' => '31',
'LocationEn' => 'England',
'LocationFr' => 'Angleterre',
'NewMessages' => 20,
'OldMessages' => 120,
};
my $English = q(
Hello %1$s, I see you are %2$s years old and from %3$s
How are you today?
You have %5$i new messages and %6$i old messages
Have a nice day
);
my $French = q{
Bonjour %1$s, je vous vois d'%4$s et âgés de %2$s ans.
Comment allez-vous aujourd'hui?
Vous avez %5$i nouveaux messages et %6$i anciens messages.
Bonne journée.
};
printf($English, @$Details{qw/Name Age LocationEn LocationFr NewMessages OldMessages/});
printf($French, @$Details{qw/Name Age LocationEn LocationFr NewMessages OldMessages/});
</code></pre>
<p>This would be a nightmare to maintain so an alternative might be to include an argument list in the database:</p>
<pre><code>#!/usr/bin/perl
use strict;
sub fetch_row {
return {
'Format' => 'You have %i new messages and %i old messages' . "\n",
'Arguments' => 'NewMessages OldMessages',
}
}
sub PrintMessage {
my ($info,$row) = @_;
printf($row->{'Format'},@$info{split(/ +/,$row->{'Arguments'})});
}
my $Details = {
'Name' => 'Mr Satch',
'Age' => '31',
'LocationEn' => 'England',
'LocationFr' => 'Angleterre',
'NewMessages' => 20,
'OldMessages' => 120,
};
my $row = fetch_row();
PrintMessage($Details,$row)
</code></pre>
|
Force wrapping an inline-block with CSS, after 'n' elements? <p>I am trying to display a list of divs as a grid, using purely CSS, but I can't get it to behave properly. I had looked at <code>white-space: wrap</code>, but that is meant to be applied to the parent element, so that isn't useable. I also tried <code>clear</code>, but no luck either. Can anyone suggest an approach, that would work for any value of elements per row. The code below is intended to be three elements per line.</p>
<p>The reason I want this in CSS, is that code that this is part of is intended to allow the user to display the entries horizontally, vertically or as a grid (of n elements wide). The value of 'n', for the elements per row of the grid is based on a configurable value.</p>
<p>Intended display, for the grid view (where n=3):</p>
<pre><code>Entry 1 | Entry 2 | Entry 3
--------+---------+--------
Entry 4 | Entry 5 | Entry 6
--------+---------+--------
Entry 7 | Entry 8 | Entry 9
</code></pre>
<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>#results.grid {
padding-top: 40px;
}
#results.grid .entry {
display: inline-block;
}
#results.grid .entry:nth-child(3n+1) {
background-color: yellow;
display: block;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="results" class="results grid">
<div class="entry">Entry 1</div>
<div class="entry">Entry 2</div>
<div class="entry">Entry 3</div>
<div class="entry">Entry 4</div>
<div class="entry">Entry 5</div>
<div class="entry">Entry 6</div>
<div class="entry">Entry 7</div>
<div class="entry">Entry 8</div>
<div class="entry">Entry 9</div>
</div></code></pre>
</div>
</div>
</p>
<p>As a JSFiddle: <a href="https://jsfiddle.net/rn05gns1/" rel="nofollow">https://jsfiddle.net/rn05gns1/</a></p>
| <p>Instead of inline block use <em>float</em>s:</p>
<pre><code>#results.grid .entry {
float: left;
}
#results.grid .entry:nth-child(3n+1){
background-color: yellow;
clear: left;
}
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() {
$('#mode').change(function() {
$('#results').removeClass();
$('#results').addClass($(this).val());
})
})</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#controls {
position: fixed;
z-index: 4;
background-color: white;
width: 100%;
padding: 4px
}
.entry {
width: 200px;
height: 150px;
border: solid 1px black;
margin: 5px;
}
#results.horizontal {
overflow-x: scroll;
overflow-y: hidden;
width: 100%;
white-space: nowrap;
padding-top: 40px;
}
#results.horizontal .entry {
display: inline-block;
}
#results.vertical {
position: absolute;
top: 40px;
bottom: 0;
overflow-y: scroll;
overflow-x: hidden;
}
#results.grid .entry.vertical {
display: block;
}
#results.grid {
padding-top: 40px;
}
#results.grid .entry {
float: left;
}
#results.grid .entry:nth-child(3n+1) {
clear: left;
background-color: yellow;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="results" class="results grid">
<div class="entry">Entry 1</div>
<div class="entry">Entry 2</div>
<div class="entry">Entry 3</div>
<div class="entry">Entry 4</div>
<div class="entry">Entry 5</div>
<div class="entry">Entry 6</div>
<div class="entry">Entry 7</div>
<div class="entry">Entry 8</div>
<div class="entry">Entry 9</div>
</div></code></pre>
</div>
</div>
</p>
|
Next/previous buttons to add in a modal <p>Totally new in this world, but i just love it, and i want to get the best out of it.
I am making my own photosite and i am stuck here with the next/previous button in modal. What to do?</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-html lang-html prettyprint-override"><code><img id="myImg" src="myimage" alt="wjuuuu" width="760" height="478">
<!-- The Modal -->
<div id="myModal" class="modal">
<span class="close">Ã</span>
<img class="modal-content" id="img01">
<div id="caption"></div>
</div>
<script>
// Get the modal
var modal = document.getElementById('myModal');
// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById('myImg');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
</script></code></pre>
</div>
</div>
</p>
| <p>Instead of re-doing something like this, why not try something that works? In doing something very similar to what you want to do, I used the <a href="https://blueimp.github.io/Gallery/" rel="nofollow">Blueimp gallery</a>. It was simple to set up, and the previous / next buttons work, including using the arrow keys and on mobile.</p>
|
Why php variables are not getting echoed on my webserver <p>I have wasted several hours just to make a textbook example of defining the php variables and trying to echo the values using my both XAMPP Sever and the actual hosting company. My goal is to display the results of a sql query into a html table. Unfortunately, I cannot even echo the 4 basic php variables with actual values? </p>
<pre><code><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Test HTML Table With mysql variables</title>
</head>
<body>
<?php
$email1 = "av104";
$email2 = "av1040";
$address1 = "Thousand Oaks";
$address2 = "Los Angeles";
echo $email1."<br/>";
echo $email2."<br/>";
echo $address1."<br/>";
echo $address2.."<br/>";
<?
<table>
<tr>
<td>$email1</td>
<td>$address1</td></tr>
<tr>
<td>$email2</td>
<td>$address2</td>
<tr>
</table>
*/
</body>
</html>
</code></pre>
<p>When I execute this script using either XAMPP or my hosting company's server, I get this output:</p>
<pre><code>"; echo $email2."
"; echo $address1."
"; echo $address2.."
"; $email1 $address1 $email2 $address2
</code></pre>
<p>I will greatly appreciate if someone can guide me what is wrong with this html/php script? I will be much obliged. Thanks!</p>
| <p>just use below code, there are multiple typos in your code:</p>
<p>php:</p>
<pre><code><?php
$email1 = "av104";
$email2 = "av1040";
$address1 = "Thousand Oaks";
$address2 = "Los Angeles";
echo $email1."<br/>";
echo $email2."<br/>";
echo $address1."<br/>";
echo $address2."<br/>";
?>
</code></pre>
<p>html:</p>
<pre><code><table>
<tr>
<td><?php echo $email1; ?></td>
<td><?php echo $address1; ?></td>
</tr>
<tr>
<td><?php echo $email2; ?></td>
<td><?php echo $address2; ?></td>
</tr>
</table>
</code></pre>
<p>
</p>
|
Bizzare matplotlib behaviour in displaying images cast as floats <p>When a regular RGB image in range (0,255) is cast as float, then displayed by matplotlib, the image is displayed as negative. If it is cast as uint8, it displays correctly (of course). It caused me some trouble to figure out what was going on, because I accidentally cast one of images as float. </p>
<p>I am well aware that when cast as float, the image is expected to be in range (0,1), and sure enough, when divided by 255 the image displayed is correct. But, why would an image in range (0,255) that is cast as float displayed as negative? I would have expected either saturation (all white) or automatically inferred the range from the input (and thus correctly displayed)? If either of those expected things happened, I would have been able to debug my code quicker. I have included the required code to reproduce the behaviour. Does anyone have insight on why this happens?</p>
<pre><code> import numpy as np
import matplotlib.pyplot as plt
a = np.random.randint(0,127,(200,400,3))
b = np.random.randint(128,255,(200,400,3))
img=np.concatenate((a,b)) # Top should be dark ; Bottom should be light
plt.imshow(img) # Inverted
plt.figure()
plt.imshow(np.float64(img)) # Still Bad. Added to address sascha's comment
plt.figure()
plt.imshow(255-img) # Displayed Correctly
plt.figure()
plt.imshow(np.uint8(img)) # Displayed Correctly
plt.figure()
plt.imshow(img/255.0) # Displays correctly
</code></pre>
| <p>I think you are on a wrong path here as you are claiming, that <code>np.random.randint()</code> should return an float-based array. <strong>It does not!</strong> (<a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html" rel="nofollow">docs</a>)</p>
<p><strong>This means</strong>:</p>
<p>Your first plot is calling imshow with an <strong>numpy-array of dtype=int64</strong>. This is not allowed as seen <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.imshow" rel="nofollow">here</a>!</p>
<p>The only allowed dtypes for your dimensions are described as: (<a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.imshow" rel="nofollow">see docs</a>):</p>
<pre><code>MxNx3 â RGB (float or uint8 array) # there are others
# -> this one applies to your dims!
</code></pre>
<p>The only valid calls to imshow in your example are number 3 and 4 (while 1 and 2 are invalid)!</p>
<p>Listing:</p>
<ul>
<li><code>plt.imshow(img)</code> <strong>not ok</strong> as dtype=int64</li>
<li><code>plt.imshow(255-img)</code> <strong>not ok</strong> as dtype=int64</li>
<li><code>plt.imshow(np.uint8(img))</code> <strong>ok</strong> as dtype=uint8 (and compatible dims)</li>
<li><code>plt.imshow(img/255.0)</code> <strong>ok</strong> as dtype=float (and compatible dims)</li>
</ul>
<p><strong>Remark:</strong></p>
<p>If this makes you nervous, you could checkout <a href="http://scikit-image.org/" rel="nofollow">scikit-image</a> which is by design a bit more cautious about the internal representation of images (during custom-modifications and the resulting types). The internal data-structures are still numpy-arrays!</p>
|
Simulate an AR(1) process with uniform innovations <p>I need to plot an <code>AR(1)</code> graph for the process</p>
<pre><code>y[k] = 0.75 * y[k-1] + e[k] for y0 = 1.
</code></pre>
<p>Assume that <code>e[k]</code> is uniformly distributed on the interval <code>[-0.5, 0.5]</code>.</p>
<p>I am trying to use <code>arima.sim</code>:</p>
<pre><code>library(tseries)
y.0 <- arima.sim(model=list(ar=.75), n=100)
plot(y.0)
</code></pre>
<p>It does not seem correct. Also, what parameters do I change if <code>y[0] = 10</code>?</p>
| <p>We want to use R base function <code>arima.sim</code> for this task, and no extra libraries are required.</p>
<p>By default, <code>arima.sim</code> generates ARIMA with innovations ~ <code>N(0,1)</code>. If we want to change this, we need to control the <code>rand.gen</code> or <code>innov</code> argument. For example, you want innovations from uniform distributions <code>U[-0.5, 0.5]</code>, we can do either of the following:</p>
<pre><code>arima.sim(model=list(ar=.75), n=100, rand.gen = runif, min = -0.5, max = 0.5)
arima.sim(model=list(ar=.75), n = 100, innov = runif(100, -0.5, 0.5))
</code></pre>
<hr>
<p><strong>Example</strong></p>
<pre><code>set.seed(0)
y <- arima.sim(model=list(ar=.75), n = 100, innov = runif(100, -0.5, 0.5))
ts.plot(y)
</code></pre>
<p><a href="http://i.stack.imgur.com/tvW95.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/tvW95.jpg" alt="enter image description here"></a></p>
<hr>
<p>In case we want to have explicit control on <code>y[0]</code>, we can just shift the above time series such that it starts from <code>y[0]</code>. Suppose <code>y0</code> is our desired starting value, we can do</p>
<pre><code>y <- y - y[1] + y0
</code></pre>
<p>For example, starting from <code>y0 = 1</code>:</p>
<pre><code>y <- y - y[1] + 1
ts.plot(y)
</code></pre>
<p><a href="http://i.stack.imgur.com/O876E.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/O876E.jpg" alt="enter image description here"></a></p>
|
Use a value on a cell as a Sheet name to work with a formula <p>I have 2 excel files , on one im using a vlookup to extract data from the other file but my issue is the following:</p>
<p>File 1 : this one has 12 sheets with names like January, February , Marc , etc.
.
File 2 : On this one I have the vlookup that makes reference to File 1</p>
<p>Now, on file 2 I have cell A1 which has as value the word January .</p>
<p>I have this formula on file 2</p>
<pre><code>=IFERROR(VLOOKUP(A2,'[Weekly Team Report- Salvador.xlsx]January'!$A$1:$B$3,2,FALSE),"")
</code></pre>
<p>As you can see is making reference to a sheet called 'January'</p>
<p>I would like to know if there is any way to use the information I have on cell A1 as sheetname i.e. if I change the value on my cell A1 to February , the sheetname on the formula should change to February instead of January</p>
<p>I hope someone can understand me :(</p>
| <p>Yes, this is what formula <code>=INDIRECT()</code> is for:</p>
<pre><code> =IFERROR(VLOOKUP(A2,Indirect("'[Weekly Team Report- Salvador.xlsx]" & A1 & "'!$A$1:$B$3"),2,FALSE),"")
</code></pre>
<p>Notice that the entire range being referenced is stuck inside of the <code>indirect()</code> formula as a string. And then we concatenate the value from <code>A1</code> to that string.</p>
|
OneLogin .NET SAML CheckSignature Error <p>I've download <a href="https://github.com/onelogin/dotnet-saml" rel="nofollow">https://github.com/onelogin/dotnet-saml</a> and am testing against an internal IdP. Initially I thought the error was because of the certificate being SHA256 (since the one referenced in their code is a 1024-bit SHA1). I changed the IdP certificate to match that criteria, but still receive the error below after authenticating at the IdP.</p>
<p>I'm new to .net, but have been writing PHP for 10+ years.</p>
<pre><code>Line 88: return signedXml.CheckSignature(certificate.cert, true);
Source File: c:\inetpub\dotnet-saml-master\App_Code\Saml.cs Line: 88
[CryptographicException: SignatureDescription could not be created for the signature algorithm supplied.]
System.Security.Cryptography.Xml.SignedXml.CheckSignedInfo(AsymmetricAlgorithm key) +240118
System.Security.Cryptography.Xml.SignedXml.CheckSignature(AsymmetricAlgorithm key) +44
System.Security.Cryptography.Xml.SignedXml.CheckSignature(X509Certificate2 certificate, Boolean verifySignatureOnly) +532
OneLogin.Saml.Response.IsValid() in c:\inetpub\dotnet-saml-master\App_Code\Saml.cs:88
_Default.Page_Load(Object sender, EventArgs e) in c:\inetpub\dotnet-saml-master\Consume.aspx.cs:28
System.Web.UI.Control.OnLoad(EventArgs e) +109
System.Web.UI.Control.LoadRecursive() +68
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4498
</code></pre>
| <p>The toolkit uses the System.Security.Cryptography.Xml library that includes the signedXml class.</p>
<p>That class has the <a href="https://msdn.microsoft.com/en-us//library/ms148731(v=vs.110).aspx" rel="nofollow">CheckSignature</a> method, that expects as parameter the X509Certificate2 object to use to verify the Signature, and second parameter to determine if only validate the signature, or validate the signature and the x509 cert.</p>
<p>You are experiencing a <a href="https://msdn.microsoft.com/en-us/library/system.security.cryptography.cryptographicexception(v=vs.110).aspx" rel="nofollow">CryptographicException</a>. In a fast google search I found the possible reason (depends on the framework version, you can get an error when using some algorithms):
<a href="https://blogs.msdn.microsoft.com/smondal/2012/08/24/signaturedescription-could-not-be-created-for-the-signature-algorithm-supplied/" rel="nofollow">https://blogs.msdn.microsoft.com/smondal/2012/08/24/signaturedescription-could-not-be-created-for-the-signature-algorithm-supplied/</a></p>
<p>and at stackoverflow a similar question with a solution:
<a href="http://stackoverflow.com/questions/16728558/signed-xml-signature-verification-for-sso-saml-using-sha256">Signed XML signature verification for SSO SAML (Using sha256)</a> </p>
<p><strong>BTW:</strong> The dotnet-saml toolkit is 6 years old and it was a proof of concept of how implement SAML on .NET.</p>
<p>Onelogin's is working on the release of a new toolkit for .NET, but meanwhile, if you want to use that on production I can suggest you some alternatives:</p>
<ul>
<li><a href="http://www.componentspace.com/" rel="nofollow">ComponentSpace</a> (commercial)</li>
<li><a href="https://digitaliser.dk/resource/2972745" rel="nofollow">OIOSAML</a> (open source)</li>
<li><a href="http://itfoxtec.com/identitysaml2" rel="nofollow">ITfoxtec</a> (open source)</li>
<li><a href="https://github.com/KentorIT/authservices" rel="nofollow">Kentor</a> (open source)</li>
<li><a href="https://github.com/elerch/SAML2" rel="nofollow">Owin.Security.Saml</a> (open source)</li>
</ul>
|
C++ - Weird function return value <p>I was making a simple min() function when I suddenly asked myself a question which got a bit more complex than I though</p>
<p>I created a valid function, and got the idea to omit a condition between the two numbers. Here is my function:</p>
<pre><code>int min(int x, int y) {
if (x > y) {
return y;
}
else if (x < y) {
return x;
}
}
</code></pre>
<p>So it works perfectly for different numbers, if I put 2 and 3 inside, it'll return 2.
But what happen when I put two time the same number? e.g. : 2 and 2</p>
<p>Neither 2 > 2 and 2 < 2 are valid, so it's just returning... nothing?</p>
<p>That what I though, I compiled the program (VS2015), got a warning about not testing every cases (normal), and when it runs... it outputs 2. Why?</p>
<p>After talking with people on it (and checking the ASM code for this function), someone checked with Valgrind what was happening, and as he told me, it appears that it could be a memory leak. I don't exactly know how it works, so why returning no value make it returning 2? Which 2 is returned?</p>
<p>I also tested if one of these conditions were true for some reason with a simple std::cout, but none of theme are true, so that's not something about "simplifying" with <code>if (x > y) {...} else {...}</code></p>
<p>So what is really happening here?</p>
<p>[EDIT] I don't wanna know how to "fix" it, because it's pretty obvious to me. The question is, why am I getting 2? I know that there should be an else statement, but I was curious about what will happen without it</p>
| <p>Flowing off the end of a function results in undefined behavior in a value-returning function. The behavior of your program is undefined.</p>
<p>In practice this means the caller is going to try to read the returned <code>int</code> according to whatever calling convention is being used, and fail to do so.</p>
|
How can I wrap a paragraph on a Cucumber report? <p>How can I wrap a paragraph on a Cucumber report ?</p>
<p>I have a Cucumber report and I am printing text on the report using:</p>
<pre><code>puts "whatever i want to say"
</code></pre>
<p>In cases when that string is very long, the paragraph doesn't wrap on the HTML report. Is there a way I can get the puts output to wrap whenever the output is really long?</p>
<p>I print on the report using this:</p>
<pre><code>Then(/^show me the api response$/) do
unless @response
@response = 'null'
end
puts "res: <br/><div style=\"div {word-break: break-all;}\">" + @response.to_s + "</div>"
end
</code></pre>
<p><strong>UPDATE</strong>
Thanks for the answer. Here was my final code:</p>
<pre><code>Then(/^show me the entire api response$/) do
unless @response
@response = 'null'
end
puts "API RESPONSE: " + @response.to_s.scan(/.{1,160}/).join("\n")
end
</code></pre>
| <pre><code>puts <any_long_value>.to_s.scan(/.{1,256}/).join("\n")
</code></pre>
<p>where 1,256 defines the number (256) of characters you want before wrapping.</p>
|
90-ball bingo - shortest path to winner-ticket <p>For a 90-ball bingo game engine in which I know how all the tickets look, I need to calculate the shortest path to a winner-ticket, based on the numbers that have been called for the given game. </p>
<p>For each game we expect to generate around 1000 tickets, and each play will have three contests: "1 row", "2 rows" (on one ticket, obviously) and "full ticket". </p>
<p>The path is defined as the numbers that I need to call in order to have a winner-ticket - for a given contest.</p>
<p>The table layout is very straight forward:</p>
<pre><code>A ticket belongs to a game - it has three rows
A ticket row belongs to a ticket - it has 5 fields
A ticket row field belongs to a ticket row - it has one content field
</code></pre>
<p>Called numbers are also registered per game. </p>
<p>ticket:
id
game_id</p>
<p>ticket_row:
id
ticket_id</p>
<p>ticket_row_field:
id
ticket_row_id
content</p>
<p>called_number:
game_id
called_number</p>
<p>All fields are integer types.</p>
<p>I found it easy enough to get the shortest path for the contests "1 row" and "full ticket" where I can group by ticket_row_id and ticket_id respectively.</p>
<p>Here is how I do it for the 1 row contest:</p>
<pre><code>select
r.ticket_id,
count(content) path_distance,
group_concat(content order by content) path
from
ticket t
inner join ticket_row r
on r.ticket_id = t.id
inner join ticket_row_field f
on f.ticket_row_id = r.id
left join called_number n
on n.game_id = t.game_id
and n.called_number = f.content
where
n.called_number is null
group by
ticket_row_id
having
path_distance < 4
order by
path_distance;
</code></pre>
<p>My problem is: How do I find the shortest path for the contest "2 rows on the same ticket" using MySQL (which does not support windowing functions)?</p>
<p>To describe it in more technical terms: For each ticket I want to find the sum of the count of the field-contents not matched by called_number, but only for the two rows with the least amount of missing fields. Tickets should be ordered so that those with the fewest missing fields come first.</p>
<p>I would like the result to look like this:</p>
<pre><code>+-----------+---------------+------------+
| ticket_id | path_distance | path |
+-----------+---------------+------------+
| 12 | 3 | 14,32,78 |
+-----------+---------------+------------+
| 9 | 4 | 2,58,76,89 |
+-----------+---------------+------------+
... etc
</code></pre>
| <p>The folllowing seems to be the way to go:
First we create a couple of views so to make the actual select query easier to comprehend</p>
<p>This first view represents rows that are already completely filled - meaning that all 5 numbers have also been called.</p>
<pre><code>create or replace view filled as
select
r.ticket_id, f.ticket_row_id, 0 path_distance
from
ticket_row_field f
inner join ticket_row r
on r.id = f.ticket_row_id
inner join ticket t
on t.id = r.ticket_id
inner join called_number n
on n.called_number = f.content
group by ticket_row_id
having count(*) = 5;
</code></pre>
<p>The other view represents rows that are not completely filled</p>
<pre><code>create or replace view incomplete as
select
r.ticket_id, f.ticket_row_id,
coalesce(filled.path_distance, count(content)) path_distance,
case when
filled.path_distance is not null then
'' else
group_concat(content order by content)
end path
from
ticket t
inner join ticket_row r
on r.ticket_id = t.id
inner join ticket_row_field f
on f.ticket_row_id = r.id
left join called_number n
on n.game_id = t.game_id
and n.called_number = f.content
left join filled
on filled.ticket_row_id = f.ticket_row_id
where
n.called_number is null or filled.ticket_row_id is not null
group by
ticket_row_id;
</code></pre>
<p>Then we use the following select query to get the tickets we need, including their path (= the missing numbers)</p>
<pre><code>select
r1.ticket_id, r1.path_distance + r2.path_distance distance_sum, concat(r1.path, ',', r2.path) path_combined
from
incomplete r1
inner join incomplete r2
on r2.ticket_id = r1.ticket_id
where
r2.ticket_row_id < r1.ticket_row_id
order by
distance_sum
limit 5;
</code></pre>
|
Move a SKNode around a circle <p>i am moving my sknode around a circle created with this code:</p>
<pre><code> circleDiameter = 300;
pathCenterPoint = CGPointMake(self.position.x - circleDiameter/2, self.position.y - circleDiameter/2);
UIBezierPath *circlePath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(pathCenterPoint.x, pathCenterPoint.y, circleDiameter, circleDiameter) cornerRadius:circleDiameter/2];
self.actionClockwise = [SKAction followPath:circlePath.CGPath asOffset:false orientToPath:true duration:2];
self.circleActionForever = [SKAction repeatActionForever:self.actionClockwise];
[self runAction:self.actionCounterClockwise withKey:@"circleActionForever"];
</code></pre>
<p>And everything is working. Now i want that when an user tap on the screen to revert the direction and move the node in counterClockwise. I did that by running the same action with .reversedAction command.</p>
<p>But the action always restart from the start point.</p>
<p>I want to know if there is some kind of method to make start the animation from the point where the old animation is when the user tap on the screen?</p>
| <p>A <code>UIBezierPath</code> is composed by path <code>Elements</code> where the first is <code>moveToPoint</code> that , as explained in the <a href="https://developer.apple.com/reference/uikit/uibezierpath" rel="nofollow">official document</a>, <strong><em>starts a new subpath at a specified location in a mutable graphics path</em></strong>.</p>
<p>So, unfortunately is not enough doing:</p>
<pre><code>UIBezierPath *circlePathReversed = [circlePath bezierPathByReversingPath];
</code></pre>
<p>because when you stop your circle from following the path, the actual position of the circle is not the same of the <code>moveToPoint</code> point (coordinates x and y).</p>
<p>However you could rebuild your path retrieving all elements and re-starting from the actual circle position.</p>
<pre><code>void MyCGPathApplierFunc (void *info, const CGPathElement *element) {
NSMutableArray *bezierPoints = (__bridge NSMutableArray *)info;
CGPoint *points = element->points;
CGPathElementType type = element->type;
switch(type) {
case kCGPathElementMoveToPoint: // contains 1 point
[bezierPoints addObject:[NSValue valueWithCGPoint:points[0]]];
break;
case kCGPathElementAddLineToPoint: // contains 1 point
[bezierPoints addObject:[NSValue valueWithCGPoint:points[0]]];
break;
case kCGPathElementAddQuadCurveToPoint: // contains 2 points
[bezierPoints addObject:[NSValue valueWithCGPoint:points[0]]];
[bezierPoints addObject:[NSValue valueWithCGPoint:points[1]]];
break;
case kCGPathElementAddCurveToPoint: // contains 3 points
[bezierPoints addObject:[NSValue valueWithCGPoint:points[0]]];
[bezierPoints addObject:[NSValue valueWithCGPoint:points[1]]];
[bezierPoints addObject:[NSValue valueWithCGPoint:points[2]]];
break;
case kCGPathElementCloseSubpath: // contains no point
break;
}
}
</code></pre>
<p><strong>Usage</strong>:</p>
<pre><code>NSMutableArray *bezierPoints = [NSMutableArray array];
CGPathApply(circlePath.CGPath, bezierPoints, MyCGPathApplierFunc);
</code></pre>
|
What does the "AS DBO" part of a GRANT do? <p>Given...</p>
<pre><code>GRANT EXECUTE ON [dbo].[SomeSproc] TO [Some_User] AS [dbo]
</code></pre>
<p>What EXACTLY does the "AS DBO" part do?</p>
| <p>This just controls who (dbo) is recorded as having issued the GRANT. See here <a href="https://msdn.microsoft.com/en-us/library/ms187965.aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/ms187965.aspx</a>.</p>
|
Spaces in string vs. Escape sequences <p>In Ruby (testing in the Interactive Ruby Shell), you can either use spaces in strings or use escape sequences. Is there a best practice in determining which to use, or does it never matter?</p>
<p>For example:</p>
<pre><code>"Hello World"
--> "Hello World"
vs.
"Hello\sWorld"
--> "Hello World"
</code></pre>
| <p>Use spaces. Makes it much more easier to read</p>
<p>If you cant, then use the escape sequences.</p>
<p>Also note that escape only works in double quotes </p>
<pre><code> 'Hello\sWolrd'
--> 'Hello\\sWorld'
</code></pre>
|
Import data into R from access <p>I'm attempting to pull data into R from access which, I've successfully done. </p>
<p>Now what I'm looking to do is pull in all the needed tables with one line of code opposed to one at a time. </p>
<p>Example: </p>
<p>I have 5 tables:
3/15 Policy Details
6/15 Policy Details
9/15 Policy Details
12/15 Policy Details
3/16 Policy Details</p>
<p>As you can see, all the tables end with "Policy Details" but begin with a different date. </p>
<p>My orginal solution: </p>
<pre><code>library(RODBC)
db<-file.path("C:\\Path\\To\\Database.accdb")
db
channel<-odbcConnectAccess2007(db)
sqlTables(channel,tableType = "TABLE")$TABLE_NAME ##List all table names
Q1.15<-sqlFetch(channel,"3/15 Policy Details")
Q2.15<-sqlFetch(channel,"6/15 Policy Details")
close(channel)
</code></pre>
<p>I had to use sqlFetch for each quater. What I'm looking to do is bring in all the tables with one string of code oppossed to doing a seperate line of code for each quarter. </p>
| <p>Consider using <code>grep()</code> on returned list of table names. Then bind table fetches into a list with <code>lapply()</code> and then out to separate dataframe objects with <code>list2env</code>:</p>
<pre><code>library(RODBC)
db <- file.path("C:\\Path\\To\\Database.accdb")
channel<-odbcConnectAccess2007(db)
accTables <- sqlTables(channel,tableType = "TABLE")$TABLE_NAME
accTables <- accTables[grep(".*Policy Details$", accTables)]
dfList <- lapply(accTables, function(t) sqlFetch(channel, t))
close(channel)
# NAME EACH DF ELEMENT THE SAME AS TABLE NAME
dfList <- setNames(dfList, accTables)
# OUTPUT EACH DF TO INDIVIDUAL OBJECT
list2env(dfList, envir=.GlobalEnv)
</code></pre>
|
Undertow Websocket Bean Injection CDI Issue <p>I don't understand why CDI use of injection doesn't work with websockets, using undertow. </p>
<p>Below is the code I have for a simple websocket endpoint. </p>
<pre><code>@ServerEndpoint("/")
public class TestWebSocketEndpoint {
@Inject
private RetrieveAccessor retrieveAccessor;
private final Logger logger = Logger.getLogger(this.getClass().getName());
@OnOpen
public void onConnectionOpen(Session session) {
logger.info("Connection opened ... " + session.getId());
}
@OnMessage
public String onMessage(String message) {
if (!message.isEmpty()) {
return message;
}
System.out.println("RETRIEVE BEAN -> " + retrieveAccessor);
if (retrieveAccessor != null) {
return "BEAN NOT NULL";
}
return ":(";
}
@OnClose
public void onConnectionClose(Session session) {
logger.info("Connection close .... " + session.getId());
}
}
</code></pre>
<p>Of course the issue is that the injected property is null. I have no problems of course using the rest side of things for this deployment and injection of the stateless bean described below. Is there a work around for this, what are the problems I could run into if I just init properties I need that are beans? Because that definitely works. </p>
<p>RetrieveAccessor retrieveAccessor = new.... {code}</p>
| <p>Undertow is only a servlet container. Weld (or OWB) provide CDI support. I'm not sure how you're instantiating Undertow, but you need to leverage Weld (or some other CDI implementation).</p>
<p>Here's one example how to do it. Leverage a <a href="https://github.com/hammock-project/hammock/blob/master/web-undertow/src/main/java/ws/ament/hammock/web/undertow/websocket/UndertowWebSocketExtension.java#L31" rel="nofollow">CDI Extension</a> to find the endpoints, and once you have them you can <a href="https://github.com/hammock-project/hammock/blob/master/web-undertow/src/main/java/ws/ament/hammock/web/undertow/UndertowWebServer.java#L88,L93" rel="nofollow">register them in Undertow</a></p>
<p>Feel free to leverage Hammock for this.</p>
|
JavaScript: Catch users who did screen <p>I need catch users who make screen on my web page. I can do it easy, if they use key "PrntScr", but what should i do if they make screen on Mac, Android or iPad? And can i catch users who make screen with other software?</p>
<p>p.s. sorry for my bad english</p>
| <p>It would be next to impossible for you to detect such behavior. If your website was only available in the form of mobile apps you could detect when people take screenshots (as in the case of Snapchat), but it would be very easy for someone to bypass this on PCs.</p>
<p>In Linux, someone could use a tool such as <code>gnome-screenshot</code>; on Windows someone could use the <code>Snipping Tool</code>, and on any computer someone could use an extension to capture the screen. If all else fails, someone could use a virtual machine to capture the screenshot without you knowing. </p>
|
How can I add a row within each step of a PHP prepared statement? <p>I have a prepared statement that produces a list of prices. The prices are determined by the value of the item multiplied by the quantity. </p>
<pre><code>if ($select = $db -> prepare("SELECT value, quantity FROM items"))
{
$select -> execute();
$select -> bind_result($value, $quantity);
while ($select -> fetch())
{
$subtotal = $value * $quantity;
echo $subtotal.'<br />';
}
$select -> close();
}
// I want to put the $total here.
</code></pre>
<p>This outputs a list of numbers:</p>
<pre><code>100
50
200
1.50
</code></pre>
<p>I would like to somehow add up each $subtotal and put them into another variable "$total" outside of my prepared statement. Is this possible to do WITHOUT doing the math within the query?</p>
| <p>Declare a variable <code>$total = 0</code> outside of the prepared statement and use it in the <code>while()</code> loop to calculate total price value, like this:</p>
<pre><code>$total = 0;
if ($select = $db -> prepare("SELECT value, quantity FROM items")){
$select->execute();
$select->bind_result($value, $quantity);
while($select -> fetch()){
$subtotal = $value * $quantity;
$total += $subtotal;
}
$select->close();
}
echo $total;
</code></pre>
<hr />
<p><strong>Sidenote:</strong> As @Fred-ii and @JuanTomas mentioned, since you're using prepared statement without any placeholders, you could change <code>->prepare()</code> to simply <code>->query()</code> while removing the <code>->execute()</code> statement altogether, it'll make no difference to your code.</p>
|
Query for Mongoexport <p>I want to export a collection projection according to a query, the syntax I am using to execute mongoexport is:</p>
<pre><code>./mongoexport -d myDB -c myCollection -q "myQuery" -o output.json
</code></pre>
<p>I have tried to use this filter in mongo shell, but I can't format it correctly, so it is legal to stand for "myQuery":</p>
<pre><code>{
'run.session.game._id':'gameId1',
'run.session.device._id':{$in:['value1','value2']},
'createdAt':{
$gte:ISODate('2016-06-05T15:14:22.163Z'),
$lte:ISODate('2017-06-05T15:14:22.163Z')
}
}
</code></pre>
<p>It works if I only have the first filter, but as soon as I put in line 2 for device id, I get an error.
The error message looks like this:</p>
<pre><code>2016-10-07T22:54:02.333+0200
error validating settings: query '[123 39 114 117 110 46 115 101 115
115 105 111 110 46 103 97 109 101 46 95 105 100 39 32 58 32 39 90 71
120 88 109 104 100 66 69 83 39 44 39 114 117 110 46 115 101 115 115 105
111 110 46 100 101 118 105 99 101 46 95 105 100 39 58 123 58 91 79 98
106 101 99 116 73 100 40 39 101 104 55 73 77 117 112 107 52 112 39 41
93 125 125]' is not valid JSON: invalid character ':' looking for
beginning of object key string
2016-10-07T22:54:02.333+0200 try 'mongoexport --help' for more
information
</code></pre>
<p>Please help :(
I know there is something about the query has to be in strict JSON format, but I don't really know how to convert it...</p>
| <p>It seems you are missing a <code>:</code> after the <code>$in</code> operator. Try to use:</p>
<pre><code>'run.session.device._id':{$in:['value1','value2']}
</code></pre>
|
JavaFX UI elements not showing up in Stage <p>I am making a basic JavaFx program. The program displays text and a button in the first scene and when clicking the button the program navigates to another scene. The code runs fine but there is no button or text showing up in the window. Can anyone suggest why this is happening? Any input would be much appreciated. Full program below:</p>
<pre><code>import javafx.application.*;
import javafx.application.*;
import javafx.event.*;
import javafx.scene.*;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.*;
public class Main extends Application{
Stage window;
Scene scene1, scene2;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
window = primaryStage;
//Create Elements for scene1
Label label = new Label("Welcome to scene 1 click button to go to scene 2");
Button button = new Button("Go to scene 2");
button.setOnAction(e -> window.setScene(scene2));
//Add Elements and set layout for scene1
StackPane layout1 = new StackPane();
layout1.getChildren().addAll(button, label);
scene1 = new Scene(layout1, 400, 400);
//Create Elements for scene2
Label label2 = new Label("This is scene 2 click button to go back to scene 1");
Button no2button = new Button("Go back to scene 1");
no2button.setOnAction(e -> window.setScene(scene1));
//Add Elements and set layout for scene2
StackPane layout2 = new StackPane();
layout1.getChildren().addAll(no2button, label2);
scene1 = new Scene(layout2, 400, 400);
window.setScene(scene1);
window.setTitle("CSS Alarm");
window.show();
}
}
</code></pre>
| <p>Here :</p>
<pre><code> StackPane layout2 = new StackPane();
layout1.getChildren().addAll(no2button, label2);
scene1 = new Scene(layout2, 400, 400);
</code></pre>
<p>You aren't actually adding anything to layout2, but right below this you are setting layout 2 as the scene</p>
<pre><code>scene1 = new Scene(layout2, 400, 400);
window.setScene(scene1);
window.setTitle("CSS Alarm");
window.show();
</code></pre>
|
Login system with infinite loop error <p>I'm coding myself a "simple" login system everything works ok up until the <code>LOGIN</code> part.</p>
<p>The <code>while</code> loop at the end only happens once even though I put another user rather than what I created when I ran the program. I got it to work at some point, but then there was another issue where the <code>while</code> loop would happen over and over again.</p>
<pre><code>import re
users = {}
status = ""
while status != "r":
status = input("Press R to register!\n")
if status == "r":
createUser = input("Create your Username: ")
while len(createUser)< 5: #checks user len
print("Username should contain at least 5 characters!")
createUser = input("Create your Username: ") #repeat if user len < 5
while not re.match("^[a-z]*$" , createUser): # denies blank spaces
print("Cannot use blank spaces")
createUser = input("Create your Username: ")
if createUser in users:
print("Username already used!")
else:
createPass = input("Create your Password: ")
while len(createPass) < 5: #checks pass len
print("Password too short!\n Password should contain at least 5 characters!\n")
createPass = input("Create your Password: ") #repeat if pass len < 5
while not re.match("^[a-z]*$", createPass): # denies blank spaces
print("Cannot use blank spaces")
createPass = input("Create your Password: ")
else:
users[createUser] = createPass #adds user and pass to users
print("User created!")
#LOGIN
for createUser in users:
username = input("Username: ")
if username == createUser in users:
password = input("Password: ")
else:
while username != createUser:
print("User unregistered! Please register!")
createUser = input("Create your Username:")
</code></pre>
| <p>Try this:</p>
<pre><code>def login():
username = input("Username: ")
if username not in users:
print("User unregistered! Please register!")
register()
return
password = input("Password: ")
if users[username] != password
print("Password invalid")
</code></pre>
<p>I've rewritten your code here. Notice how I've broken it down into functions which do one thing:</p>
<ul>
<li>usernameValidator</li>
<li>passwordValidator</li>
<li>getUsername</li>
<li>getPassword</li>
<li>register</li>
<li>login</li>
</ul>
<p>Beginning of the program:</p>
<pre><code>import re
users = {}
</code></pre>
<p>Now we define some validators to check if the username/password are correct:</p>
<pre><code>def usernameValidator(username):
errorMessage = ""
if len(username) < 5:
errorMessage += "Username should contain at least 5 characters!\n"
if not re.match("^[a-z]*$" , username): # Note... this checks for more than just blank spaces!
errorMessage += "Cannot use blank spaces\n"
if username in users:
errorMessage += "Username already used!\n"
return errorMessage
def passwordValidator(password):
errorMessage = ""
if len(password) < 5:
errorMessage += "Password should contain at least 5 characters!\n"
if not re.match("^[a-z]*$" , password): # Note... this checks for more than just blank spaces!
errorMessage += "Cannot use blank spaces\n"
return errorMessage
</code></pre>
<p>Now we write the getUsername/getPassword functions which talk with the user:</p>
<pre><code>def getUsername():
username = input("Create your Username: ")
errorMsg = usernameValidator(username)
print(errorMsg)
return username if errorMsg == "" else ""
def getPassword():
password = input("Create your Password: ")
errorMsg = passwordValidator(password)
print(errorMsg)
return password if errorMsg == "" else ""
</code></pre>
<p>Putting it all together, we write register/login:</p>
<pre><code>def register():
username = ""
password = ""
while username == "":
username = getUsername()
while password == "":
password = getPassword()
users[username] = password
print("User created!")
def login():
username = input("Username: ")
if username not in users:
print("User unregistered! Please register!")
register()
return
password = input("Password: ")
if users[username] != password:
print("Password invalid")
</code></pre>
<p>Finally, we may run:</p>
<pre><code>while True:
status = input("Press R to register!\nPress L to login\n")
if status.lower() == "r":
register()
if status.lower() == "l":
login()
</code></pre>
<p><a href="https://repl.it/DsrJ" rel="nofollow">Try it online</a>.</p>
|
Find nearest next even 100 <p>In javascript what's the simplest way to find the next even 100 ("even 100" = 200, 400, etc.) that's closest to the given number. For ex: 1723 should return 1800, 1402 should return 1600, 21 should return 200, 17659 should return 17800 etc. I have the following that finds the nearest 100 next to the given_num but not the even 100</p>
<p><code>(parseInt(((given_num + 99) / 100 )) * 100 )</code></p>
<p>I can think of one way of getting the number without zeroes and checking if its odd/even to figure out next even number if its odd.But more curious to see if there's some simple/elegant way.</p>
| <p>Based on <a href="http://stackoverflow.com/questions/39925970/find-nearest-next-even-100#comment67135733_39925970">bmb's comment</a>, it sounds like you want granularity of 200, not 100. If so:</p>
<p>Divide by 200, round up, multiply by 200:</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>var tests = [
{value: 1723, expect: 1800},
{value: 1402, expect: 1600},
{value: 21, expect: 200},
{value: 17659, expect: 17800}
];
tests.forEach(test);
function test(entry) {
var result = Math.ceil(entry.value / 200) * 200;
console.log({
value: entry.value,
expect: entry.expect,
result: result
});
}</code></pre>
</div>
</div>
</p>
<p>If you really want to work by rounding up to the "next 100," then the result for 1723 must be 1900 if the result for 1402 is 1600, and you do it by dividing by 100, rounding up, multplying by 100, and adding 100 (or dividing by 100, rounding up, adding 1, and multiplying by 100, which is the same thing):</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>var tests = [
{value: 1723, expect: 1800},
{value: 1402, expect: 1600},
{value: 21, expect: 200},
{value: 17659, expect: 17800}
];
tests.forEach(test);
function test(entry) {
var result = Math.ceil(entry.value / 100) * 100 + 100;
console.log({
value: entry.value,
expect: entry.expect,
result: result
});
}</code></pre>
</div>
</div>
</p>
|
Bootsrap v4-alpha not working Collapse <p>I'm using bootstrap with ASP.NET MVC. Here my accordion not start to collapse. </p>
<p>I've tried to add this javascript code:</p>
<pre><code> <script>
$(function () {
$('#accordion').collapse({
toggle: false
})
});
</script>
</code></pre>
<p>But it's not working. What could be the problem?</p>
<pre><code> <div id="accordion" role="tablist" aria-multiselectable="true">
@foreach (var HB in pages)
{
<h2>@HB.Title</h2>
foreach (var item in HB.Pages)
{
string cname = "collapse" + item.ID;
string hname = "heading" + item.ID;
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="@hname">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#@cname" aria-expanded="true" aria-controls="@cname">
@item.Title
</a>
</h4>
</div>
<div id="@cname" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="@hname">
@item.Description
</div>
</div>
}
}
</div>
</code></pre>
| <p>Your code works for me.</p>
<p>I think you are not including jquery before including bootstrap. Reference this before bootstraps js file:</p>
<pre><code><script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
</code></pre>
<p>This is my codepen with your code working:</p>
<p><a href="http://codepen.io/egerrard/pen/GjQZoZ" rel="nofollow">http://codepen.io/egerrard/pen/GjQZoZ</a></p>
|
Unit tests for connectException and IOException <p>I have unit test that tests to see if a method is throwing an error or not.</p>
<pre><code>@Test
public void getStockPriceWithNetworkErrorThrowsException()
{
StockPriceFetcher stockPriceFetcherWithNetworkError = Mockito.mock(StockPriceFetcher.class);
when(stockPriceFetcherWithNetworkError.getPrice("YHOO"))
.thenThrow(new ConnectException("Network error"));
assetValue = new AssetValue(stockPriceFetcherWithNetworkError);
try
{
assetValue.getStockPrice("YHOO");
fail("Expected exception for network error.");
}
catch(ConnectException e){
assertEquals(e.getMessage(), "Network error");
}
}
</code></pre>
<p><code>getPrice</code> is a method from the interface <code>stockPriceFetcher</code>, and <code>getStockPrice</code> simply returns what <code>getPrice()</code> returns. I want a <code>ConnectException</code> to be thrown, but I have an error in the catch block because <code>ConnectException</code> is never thrown in the try block. </p>
<p>Is there anyway I can make this try block throw a <code>ConnectException</code>?</p>
| <p>The easiest way to solve that is replacing the following line:</p>
<blockquote>
<p>when(stockPriceFetcherWithNetworkError.<strong>getPrice</strong>("YHOO"))</p>
</blockquote>
<p>with the line:</p>
<blockquote>
<p>when(stockPriceFetcherWithNetworkError.<strong>getStockPrice</strong>("YHOO"))</p>
</blockquote>
<p>But make sure that the getStockPrice() include a try {} catch(ConnectException e){} block.</p>
<p>It seems that you do not throw the ConnectException in the getStockPrice() method.</p>
<pre><code>getStockPrice(String str) {
getPrice(str) {
// Here the ConnectException is thrown
}
// here should appear another catch that throws the error to the upper level
}
</code></pre>
<p>Without the try{} catch{} block in the getStockPrice() method, the exception can not be catch in any place the method is called.
That is why you should also implement a Mock to the getStockPrice().</p>
<p>When you add the try{} catch(ConnectException e) {} block it will work great.</p>
|
fix width of one column in a row in Semantic ui <p>How can I have two column in a row in Semantic UI that one of column have a fix width and doesn't change with resizing of browser?</p>
<p>I tried this, but something went wrong:</p>
<pre><code><div class="ui grid container">
<div class="ui two column divided grid">
<div class="row">
<div class="ui four wide column" style="width= 250px;">
</div>
<div class="ui twelve wide column">
<div class="ui link cards">
<div class="card">
<div class="image">
<img src="./lib/img/elliot.jpg">
</div>
<div class="content">
<div class="header">Matt Giampietro</div>
<div class="meta">
<a>Friends</a>
</div>
<div class="description">
Matthew is an interior designer living in New York.
</div>
</div>
<div class="extra content">
<span class="right floated">
Joined in 2013
</span>
<span>
<i class="user icon"></i>
75 Friends
</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</code></pre>
| <p>There is no SUI specific way (yet), so you'll have to write custom CSS</p>
<p>You are using too many SUI classes in your code.</p>
<p>This is not required: <code><div class="ui grid container"></code> when you are defining another grid inside it.</p>
<p>The <code>two column</code> class in <code><div class="ui two column divided grid"></code> is redundant as well.</p>
<p>So solve your problem, you can change the first column classes and then use CSS to fix its width.
See JS Fiddle: <a href="https://jsfiddle.net/batrasoe/5289q8fr/1/" rel="nofollow">https://jsfiddle.net/batrasoe/5289q8fr/1/</a></p>
<pre><code>...
<div class="left column">
Some Text
</div>
<div class="twelve wide column">
<div class="ui link cards">
...
</code></pre>
<p>And corresponding CSS property:</p>
<pre><code>#grid .left.column {
width: 200px;
}
</code></pre>
<p>Don't use the classes such as <code>two wide</code> in a column you want to keep fixed as they have some associated width properties that might override the behavior of <code>.left.column</code></p>
<p>For Responsiveness, you'll have to manage the padding/margins a bit as well near the breakpoint or use media queries to update the class of the <code>twelve wide column</code>.</p>
|
Google Chrome Extension Popup not loading when using jquery <p><strong>Problem:</strong>
I'm trying to use jquery in my Google Chrome extension. It doesn't seem to be working. I've tried adding it to my manifest referencing local copies of the jquery file and I've also tried adding different directives to allow remote access to a CDN hosting it, both solutions I found from StackOverflow. </p>
<p><strong>Symptom:</strong>
When I click on the top right action button which is suppose to launch popup.html it does nothing but if I right click and select "Inspect Popup" the popup loads with all the functionality from the jquery includes. Any Ideas? I've included my manifest below.</p>
<p><strong>Possible Clue:</strong> Adding timing delays actually make the popup render and the jquery code execute then shortly after the popup exits prematurely on its own, essentially crashing silently. </p>
<pre><code>{
"manifest_version": 2,
"name": "My extension",
"description": "A test extension.",
"version": "1.0",
"icons":{"128": "icon_512.png"},
"background": {
"scripts": ["jquery-3.1.1.min.js","events.js"],
"persistent": false
},
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html",
"default_title": "Click here!"
}
}
</code></pre>
<p><strong>Jquery</strong></p>
<p>Inside popup.js I have the following:</p>
<pre><code>$(document).ready(function(){
alert("Random output!");
});
</code></pre>
<p>But if I do this it works momentarily:</p>
<pre><code>setTimeout(function(){
// Code here
$(document).ready(function(){
alert("Jquery works for a little bit!!!");
});
},1000);
</code></pre>
<p><strong>popup.html</strong></p>
<pre><code><!doctype html>
<html>
<head>
<title>Test</title>
<style type="text/css">
#content {
background-color: yellow;
width: 500px;
height: 500px;
}
</style>
</head>
<body>
<div id="content">
<h1>Test</h1>
<button id="checkPage">Start</button>
</div>
<script src="jquery.min.js"></script>
<script src="popup.js"></script>
</body>
</html>
</code></pre>
| <p>As Granga pointed out above, this issue was caused by a version compatibility issue. So far, it seems the latest version of jQuery with the latest version of Google Chrome works fine. If anyone experiences an issue like this in the future try upgrading jQuery and/or Chrome. </p>
|
'operator =' is ambiguous for std::string <p>I am trying to write a class with my own cast operators but I am having issues with multiple <code>operator=</code>s</p>
<p>I managed to reproduce the issue with the small code below</p>
<pre><code>#include <string>
class X
{
public:
operator const char*() const {
return "a";
}
operator std::string() {
return "c";
}
};
void func( )
{
X x;
std::string s = "";
s = x;
}
</code></pre>
<p>I understand that <code>std::basic_string</code> has multiple assignment operator and this is why the compiler gets confused.</p>
<p>If I remove either cast operators it works, but I was wondering if there was a way of keeping both operators.</p>
<p>My class will be returning different values depending on the cast.</p>
<p>I could also use <code>static_cast<std::string>(x)</code> to force the cast, but I was wondering if there was a a way of doing it without the static cast?</p>
| <p>As KerrekSB <a href="http://stackoverflow.com/questions/39926180/operator-is-ambiguous-for-stdstring/39926203#comment67135954_39926180">suggested</a>, you can use</p>
<pre><code>s = std::string(x);
</code></pre>
<p>Alternatively, you can perform a cast:</p>
<pre><code>s = (std::string) x;
// or
s = static_cast<std::string>(x);
</code></pre>
<p>A third alternative (which I would hope not to see in the wild very often due to readability concerns) is to access the operator directly:</p>
<pre><code>s = x.operator std::string();
</code></pre>
<hr>
<p>If you're willing to make the tradeoff of a slightly different API (and fixing any potential breakages) you can do what Roberto <a href="http://stackoverflow.com/a/39926241/510036">suggested</a> and force the explicit casting of <em>just</em> the <code>const char *</code> type operator:</p>
<pre><code>class X
{
public:
explicit operator const char*() const {
return "a";
}
operator std::string() {
return "c";
}
};
</code></pre>
<p>This tells the compiler to only allow <em>implicit</em> conversions to <code>std::string</code>, and requires you do explicitly cast to <code>const char *</code> when you want to invoke that particular operator.</p>
<hr>
<p>One last thing to note: if you are designing other classes or methods that would consume this particular class, another thing to try is to reverse the way they're used by providing an overload for <code>class X</code> rather than converting <code>X</code> to something else.</p>
<p>Always good to consider alternative ways for your API to work.</p>
|
Python 3: Getting two user inputs from a single line in a text file <p>I am working on a program that asks the user to enter a username and password and the program checks if the username and password is in the text file. If the username and password is not in the text file, it asks if the user wants to create a new user. If the username and password matches one in the text file, it rejects the user input. If it is successful, the username and password is saved to the text file, on a new line (the username and password separated by a comma).</p>
<p>text.txt :</p>
<pre><code> John, Password
Mary, 12345
Bob, myPassword
</code></pre>
<p>Usercheck.py :</p>
<pre><code>input: John
# Checks if 'John' in text.txt
input2: Password
# Checks if 'Password' in text.txt
output: Hello John! # If both 'John' and 'Password' in text.txt
input: Amy
# Checks if 'Amy' in text.txt
input2: passWoRD
# Checks if 'passWoRD' in text.txt
output: User does not exist! # If 'Amy' and 'passWoRD' not in text.txt
output2: Would you like to create a new user?
# If 'yes'
output3: What will be your username?
input3: Amy
# Checks if 'Amy' in text.txt
output4: What will be your password?
input4: passWoRD
# Adds 'Amy, passWoRD' to a new line in text.txt
</code></pre>
<p>How could I check the text file text.txt for a username AND password that is separated by a ',' without the user entering a ','? And also be able to create a new username and password (which is separated by a ','), adding it to the text file?</p>
| <p>You may know the <code>open()</code> function. With this function you can open a file like this: </p>
<pre><code>open('text.txt', 'a')
</code></pre>
<p>Parameter 1 is the file and parameter 2 is the mode (r for read only, w for write only and a for both and appending)</p>
<p>So to read the open file line by line :</p>
<pre><code>file = open('text.txt', 'a')
lines = file.readlines()
for line in lines:
name, pass = line.split(',')
if name == 'whatever':
#...
</code></pre>
<p>And finally to write to the file you've got the <code>write()</code> function.</p>
<pre><code>file.write(name + ',' + pass)
</code></pre>
<p>I think that will help you to complet your programme. :)</p>
|
Combine multiple RDDs into one by column through key <p>Got an RDD problem.
Say, I have three RDD, they are <code>RDD[AttribClass1]</code>, <code>RDD[AttribClass2]</code>, <code>RDD[AttriClass3]</code>, and each <code>AttribClass</code> has one field name as id, what I want to do is to combine all the attributes into one big RDD for the combined class, say, the class is </p>
<pre><code>ContainerClass(id: IDClass, attrib1: AttribClass1, attrib2: AttribClass2, attrib3: AttribClass3)
</code></pre>
<p>And I want to get <code>RDD[ContainerClass]</code> by joining the ids.
I saw something similar post based on find RDD by key, but not quite exactly the same.
<a href="http://stackoverflow.com/questions/30421484/spark-rdd-find-by-key">Spark RDD find by key</a></p>
<p>Does anyone have done similar thing? </p>
<p>What's the best way of creating new RDD without combining them locally? </p>
<p>Thanks,
Shi</p>
| <p>Never mind, I think the best way to know how to do this is to look through the RDD API. This can be done through groupByKey method, and then coGroup. </p>
|
Using awk and grep to add up <p>If I had a file that looks like this:</p>
<pre><code>23.00 33.44 abcd 44.44 abcd12345abcd
33.00 22.22 qt 44.00 zlkm12345ksda
</code></pre>
<p>...and I wanted to add up the first column whenever I encounter 12345 in the middle of the pattern in the fifth column, how would I go about doing that?</p>
| <p>Something like this?</p>
<pre><code>awk '$5 ~ /12345/ { TOT = TOT + $1 } END { print TOT + 0 }' yourFile.txt
</code></pre>
<p>(Not at a computer, so my syntax might be a bit off.)</p>
<p>The first bit selects the lines you want and updates the total while the END bit just prints what's accumulated.</p>
<p>No grep needed (for almost all intents and purposes, awk is just as good if not better), and the search is limited to just the column you want searched.</p>
|
Multi Level Pretty URL for E-Commerce Products In htaccess <p><strong>Updated Version</strong>
I am developing an E-commerce portal where the products need to be shown with a pretty url and also under categories.</p>
<p><strong>My Current Link:</strong> <a href="http://abcd.xyz/products.php?pro_tag=1221212112" rel="nofollow">http://abcd.xyz/products.php?pro_tag=1221212112</a> (FAKE LINK)</p>
<p><strong>My Goal:</strong> <a href="http://abcd.xyz/products/1221212112" rel="nofollow">http://abcd.xyz/products/1221212112</a> (FAKE LINK)</p>
<p>My Current HTACCESS CODE. (Made it with the help of other Stackoverflow Suggestions) :</p>
<pre><code>RewriteEngine On
RewriteBase /
RewriteRule ^products/([a-zA-Z0-9-]+)/?$ products.php?pro_tag=$1 [QSA,NC,L]
RewriteRule ^products/([a-zA-Z0-9-]+)/([a-zA-Z0-9-]+)/?$ products.php?pro_tag=$2&ctg=$1 [QSA,NC,L]
</code></pre>
<p><strong>Figured out the problem: 'pro_tag' isn't being fetched. Need help to fix that.</strong></p>
| <p>Try with:</p>
<pre><code>RewriteEngine On
RewriteBase /
RewriteRule ^products/([a-zA-Z0-9-]+)/?$ products.php?pro_tag=$1 [QSA,NC,L]
RewriteRule ^products/([a-zA-Z0-9-]+)/([a-zA-Z0-9-]+)/?$ products.php?pro_tag=$2&ctg=$1 [QSA,NC,L]
</code></pre>
<p>I add a <code>ctg</code> variable...</p>
|
Android Search option is not working? <p>android Search function in Custom list view is not working.
RestListModel is my model name.</p>
<ol>
<li>this is my code on ManActivity:</li>
</ol>
<pre class="lang-java prettyprint-override"><code>import android.support.v7.widget.SearchView;
private List<RestListModel> rdataList;
private ListView listView;
private CustomListAdapter adapter;
SearchView search;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quick_list);
rdataList = new ArrayList<RestListModel>();
listView = (ListView) findViewById(R.id.rrlist);
adapter = new CustomListAdapter(this, rdataList);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
}
// on create finished here
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menutosearch, menu);
final MenuItem myActionMenuItem = menu.findItem(R.id.action_search);
search = (SearchView) myActionMenuItem.getActionView();
//*** setOnQueryTextListener ***
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
adapter.filter(newText);
return false;
}
});
return true;
}
</code></pre>
<ol start="2">
<li>ADAPTER CLASS:</li>
</ol>
<pre class="lang-java prettyprint-override"><code> public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<RestListModel> rItems=null;
private ArrayList<RestListModel> arraylist;
public CustomListAdapter(Activity activity, List<RestListModel> restItems) {
this.activity = activity;
this.rItems = restItems;
this.arraylist = new ArrayList<RestListModel>();
this.arraylist.addAll(rItems);
}
/// I think something is wrong here
@Override
public int getCount() {
return rItems.size();
}
@Override
public Object getItem(int location) {
return rItems.get(location);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
return convertView;
}
// this is the actually filter Filter method.
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
rItems.clear();
if (charText.length() == 0) {
rItems.addAll(arraylist);
} else {
for (RestListModel wp : arraylist) {
if (wp.getName().toLowerCase(Locale.getDefault())
.contains(charText)) {
rItems.add(wp);
}
}
}
notifyDataSetChanged();
}
}
</code></pre>
| <p>You are only comparing with a array with String. I have need to add a model with three field of Different String.</p>
<pre><code> public CustomListAdapter(Activity activity, List<RestListModel> restItems) {
this.activity = activity;
this.rItems = restItems;
this.arraylist = new ArrayList<RestListModel>();
this.arraylist.addAll(rItems);
}
</code></pre>
|
NCrunch integration with Typemock failing to run tests <p>I am getting the following exception from NCrunch when tests are being run.</p>
<pre><code>*** Failures ***
Execute
TypeMock.TypeMockException:
*** Typemock Isolator is currently disabled. Enable using the following:
* Within Visual Studio:
- Use Typemock Smart Runner
- For other runners, Choose Typemock Menu and click "Integrate with Other Runners"
* To run Typemock Isolator as part of an automated process you can:
- run tests via TMockRunner.exe command line tool
- use 'TypeMockStart' tasks for MSBuild or NAnt
For more information consult the documentation (see 'Running Unit Tests in an Automated Build')
HResult: -2146233088
at TypeMock.InterceptorsWrapper.VerifyInterceptorsIsLoaded()
at _I2KaEbJqCiZdAXHCaew5L4YgGK2_._YVpKHl6s8x54awChyHFFGG1W9p_._M9wuZsfNQUSOigKL83XBnloMATg_()
at TypeMock.MockManager.Init(Boolean collectAllCalls)
at _gpWkmvHy51MsHfP5XcTmisQFOGh_._w05d89eUlRCsAnXfWIN6HIvOW7P_._LZu54JRvjOVy0mycnVTOacyFHBR_[?](Members , Constructor , Constructor , Type , Object[] )
at _gpWkmvHy51MsHfP5XcTmisQFOGh_._w05d89eUlRCsAnXfWIN6HIvOW7P_.Instance[T](Members behavior, ConstructorWillBe constructorBehavior, BaseConstructorWillBe baseConstructorBehavior)
at NOES.Business.Control.Rollformers.RollformerStateIdleTest.SendNextBagTest() in C:\Users\Frank Adcock\Documents\noes_3\src\NOESTest\Business\Control\Rollformers\RollformerStateIdleTest.cs:line 18
</code></pre>
<p>Version Details</p>
<ul>
<li>VS2015 14.0.25420.01 Update 3 </li>
<li>Typemock 8.5.0.2 </li>
<li>Test Frameworks Galio/MbUnit or Nunit 3.43</li>
</ul>
<p>From what I can read of the documentation Typemock is supposed to be automatically picked up by NCrunch, but this does not appear to be happening.</p>
<p>Any assistance welcomed</p>
| <p>Disclaimer, I work in Typemock.</p>
<p>First of all, have you enabled "Integrate with Other Runners" in Typemock VS menu and "Enable Mocking integration" and "Enable Auto Linking" in Typemock->Options->Mocking Integration?</p>
<p>Which version of NCrunch you use?</p>
|
After adding Prism.unity 6.2.0 to Windows 10 UWP, application throws exception <p>When creating a Universal Windows Application with Prism, I always receive an error upon running the application (or, sometimes, upon exiting the running application). Here are the steps I take to reproduce the problem:</p>
<ul>
<li>Create a new UWP application Using Visual Studio 2015.</li>
<li>Use NuGet to install Prism (Install-Package Prism.unity)</li>
<li>Change the App class to inherit from PrismUnityApplication (code below)</li>
<li>Create a folder called Views and add a new page called MainPage, making sure that it is in the correct namespace</li>
</ul>
<p>Code:</p>
<pre><code>using Microsoft.Practices.Unity;
using Prism.Events;
using Prism.Mvvm;
using Prism.Unity.Windows;
using Prism.Windows.AppModel;
using Prism.Windows.Navigation;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.Resources;
using Windows.System;
using Windows.UI.Notifications;
using Windows.UI.Xaml;
namespace TestAppForPrism {
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : PrismUnityApplication {
public App() {
this.InitializeComponent();
}
protected override Task OnLaunchApplicationAsync(LaunchActivatedEventArgs args) {
NavigationService.Navigate("Main", null);
return Task.FromResult<object>(null);
}
protected override Task OnInitializeAsync(IActivatedEventArgs args) {
Container.RegisterInstance<INavigationService>(NavigationService);
return base.OnInitializeAsync(args);
}
}
}
</code></pre>
<p>When I run the application, an exception is thrown:</p>
<blockquote>
<p>Could not load file or assembly 'System.Runtime.Serialization.Xml, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)</p>
</blockquote>
<p>Am I setting things up incorrectly?</p>
| <p>After playing around for a while, I think I found a solution:</p>
<p>In the NuGet console, I ran "update-package -reinstall", and then rebuilt the solution. I still have a warning in the error window that says "Found conflicts between different versions of the same dependent assembly that could not be resolved. These reference conflicts are listed in the build log when log verbosity is set to detailed.", but I seem to be able to run the application without receiving that exception any more.</p>
|
Grunt postman (newman) task hangs <p>I'm running a grunt task that runs forever, with no output:</p>
<p>My <code>grunt.initConfig</code> includes </p>
<pre><code>newman: {
default_options: {
options: {
iterationCount: 1,
collection: "tests/collection.postman_collection.json",
environment: "tests/env.postman_collection.json"
}
}
</code></pre>
<p>Here's what I run from the terminal. The newman grunt task runs indefinitely.</p>
<pre><code>Running "newman:default_options" (newman) task
^C
Execution Time (2016-10-07 16:38:54 UTC-5)
loading tasks 1s
newman:default_options 16.2s
</code></pre>
| <p>Postman collections can be exported as <code>v1</code> and <code>v2</code>, and the Grunt task plugin only works with collections of type <code>v1</code></p>
|
Install pycharm Ubuntu <p>I recently had to wipe my computer and reinstall everything. I remember being able to install pycharm (community edition) with a single <code>sudo apt-get install</code> command and that was all. I can't find it? I am using Ubuntu 16.04 LTS.</p>
| <p>From the following website <a href="http://ubuntuhandbook.org/index.php/2016/07/latest-pycharm-ubuntu-16-04-ppa/" rel="nofollow">here</a> I found these two ways to install pycharm for ubuntu 16.04</p>
<p>You have several options:</p>
<p>First option:</p>
<pre><code>sudo add-apt-repository ppa:mystic-mirage/pycharm
</code></pre>
<p>Second option:line by line version</p>
<pre><code>sudo apt update
sudo apt install pycharm
</code></pre>
<p>If you want the community version...</p>
<pre><code>sudo apt install pycharm-community
</code></pre>
<p>Have a good one!</p>
|
How to get weeks as an array for past 2 months from current date in javascript? <p>I want to get weeks for past two months in the following format. Is there a way i can achieve this in javascript. Any pointers on how to do this will is much appreciated.</p>
<pre><code>[
{
"week_start": "8/01/2016",
"week_end": "8/06/2016"
}, {
"week_start": "8/07/2016",
"week_end": "8/13/2016"
}, {
"week_start": "8/14/2016",
"week_end": "8/20/2016"
}, {
"week_start": "8/21/2016",
"week_end": "8/27/2016"
}, {
"week_start": "8/28/2016",
"week_end": "9/03/2016"
}, {
"week_start": "9/04/2016",
"week_end": "9/10/2016"
}, {
"week_start": "9/11/2016",
"week_end": "9/17/2016"
}, {
"week_start": "9/18/2016",
"week_end": "9/24/2016"
}, {
"week_start": "9/25/2016",
"week_end": "10/01/2016"
}, {
"week_start": "10/02/2016",
"week_end": "10/08/2016"
}
]
</code></pre>
| <p>You can use <a href="http://momentjs.com/" rel="nofollow">http://momentjs.com/</a> like this:</p>
<pre><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.js"> </script>
<script>
var startDay = moment("2016-07-24"); //Sunday
var res = [];
for (var i = 1; i < 10; i++) {
//console.log('week_start' + startDay.add(i, 'weeks').calendar());
//console.log('week_end' + startDay.add(i, 'weeks').subtract(1, 'days').calendar());
res.push({
'week_start': startDay.add(i, 'weeks').calendar(),
'week_end': startDay.add(i, 'weeks').subtract(1, 'days').calendar()
})
}
console.log(res)
</script>
</code></pre>
|
HOW TO INVOKE CMD COMMAND IN THE SAME PROCESS FROM JAVA? <p>"i want to know, does anyone know how to invoke cmd commands from java?</p>
<p>i already know about:</p>
<pre><code>java.lang.runtime.getruntime().exec("cmd /k \"command\"");
</code></pre>
<p>but this creates another console and executes command in there. in some cases, this is enough, but i need to be able to execute commands in the same console.</p>
<p>my problem is, that i wish to be able to change color of the background of my console application. i already use one java library, which installs ansi driver to output stream, so i can use ansi escape sequences to change color. however, although this is fine for colored text and text background, but when i want to change background of the whole console, this becomes problem. first problem is that if i simply use ansi code for some other color of the background, it will not change the color of the whole background, but just in the place where i write some text. then i need to cover whole console with space character in order to change background of the whole console.</p>
<p>and another, much more difficult problem (first one can be easily fixed) is that for some reason bright attribute in ansi codes is only applied to foreground colors, if i send it, and if i send it while changing background color, it gets ignored. this means that i have only 8 colors for background and 16 for foreground.</p>
<p>i also develop programs, beside java in cmd language too. in cmd language there is command named color which can set both foreground and background colors to 16 different colors.</p>
<p>this works if i call it from cmd language, or invoke it from power shell language, and from c++ language. (i have not tested in other languages). this is how my power shell and c++ programs change background color of console.</p>
<p>but i can not achieve the same result with java language. why - because exec method of runtime class executes commands in another console.</p>
<p>so, cmd changes the color of the newly created console, and then exits. i wish to be able to execute cmd command in the same console as my java application. but i can not seem to find a way, because runtime class executes commands in separate console.</p>
<p>so, do you know any other way to invoke cmd commands in the same console as java application?</p>
<p>if not that, then, do you know any other way to use full 4bit color system as background color in java? (so that i can use all 16 possible colors in 4bit color system as by background colors).</p>
<p>well, thank you for reading, and if anyone replies something helpful, thank you a lot. :)</p>
<p>syob"<code>.toUpperCase();</code></p>
| <p>One would control the console direct rather than asking CMD. See this API call. </p>
<blockquote>
<p><code>SetConsoleTextAttribute</code></p>
<p>The SetConsoleTextAttribute function sets the attributes of characters written to the screen buffer by the WriteFile or WriteConsole function, or echoed by the ReadFile or ReadConsole function. This function affects text written after the function call. </p>
</blockquote>
<pre><code>BOOL SetConsoleTextAttribute(
HANDLE hConsoleOutput, // handle to screen buffer
WORD wAttributes // text and background colors
);
</code></pre>
|
UnboundLocalError: local variable 'number1' referenced before assignment <p>I am getting an error in line 2 saying that i have an unboundLocal error. can anyone explain to me how to fix this?</p>
<pre><code> def main():
number1=getNumber1(number1)
number2=getNumber2(number2)
userIntro=''
printInfo=0.0
answer=0.0
#intro module welcomes the user
def userIntro():
print('hello welcome to my maximum value calculator')
print('today we will evaluate two number and display the greater one')
#this module gets the value of number1
def getNumber1(number1):
number1=print(input('Enter the value of number1'))
return (getNumber1)
#this module gets the value of number2
def getnumber2(number2):
number2=print(input('Enter the value of number2'))
return (getNumber2)
#this module takes the values of number1,number2 and displays the greater value
def printInfo(number1,number2,answer):
answer=max(number1,number2)
return (answer)
main()
</code></pre>
| <p><code>number1</code> isn't defined until you create it - you can't pass it to another function while defining it. Seems like you need a simpler function that gets the <strong>name</strong> you want to assign to:</p>
<pre><code>def main():
number1 = getNumber('number1')
number2 = getNumber('number2')
def getNumber(name):
return input('Enter the value of ' + name))
</code></pre>
|
Android permission automatically denied on requestPermission from MainActivity <p>In the main activity of an Android application I check for permissions (<code>Manifest.permission.MANAGE_DOCUMENTS</code>), detect I do not have them, and call <code>requestPermisions</code>.
Then in <code>onRequestPermissionResult</code> I almost immediately get denied permission, without a dialog ever showing.</p>
<p>I already <em>confirmed</em> the same permission in another activity of the same app (through <code>requestPermissions</code> again, which works), so I expected this decision to be stored (for the session, or whatever), and I have never selected to deny the permission. Either way, the permission dialog is not displayed and the permission is denied automatically.</p>
<p>So far I have tested this on emulators of Android 7 and 6 (API 24 and 23).</p>
<p>I have tried:</p>
<ul>
<li>clearing the app's data cache and wiping the device, so it's fresh</li>
<li>definitely not this <a href="http://stackoverflow.com/questions/38547480/getting-permission-denied-on-android-m">Getting permission denied on Android M</a></li>
<li>triple-checked spelling after seeing this <a href="http://stackoverflow.com/questions/35633110/onrequestpermissionsresult-returns-immediately-with-denied-permission">onRequestPermissionsResult returns immediately with denied permission</a> and I am calling the super method</li>
<li>a bunch of other suggestions on stack overflow</li>
</ul>
<p>I'm pretty stumped...</p>
<p>Here is the permission request (see comment in the code):</p>
<pre><code>private fun askForPermissionOrSendRequest(view: View, permission: String) {
if (checkSelfPermission(permission) == PackageManager.PERMISSION_DENIED) {
if (shouldShowRequestPermissionRationale(permission)) {
cachedView = view
val explanationDialog = AlertDialog.Builder(this).setMessage("We need permissions to read your storage in order to show your profile image.").setOnDismissListener {
requestPermissions(
arrayOf(permission),
BSMainActivity.permissionRequestSendProfilePic
)
}.create()
explanationDialog.show()
} else {
cachedView = view
// this branch is always hit - the permission seems to be missing every time
requestPermissions(
arrayOf(permission),
BSMainActivity.permissionRequestSendProfilePic
)
}
} else {
sendRequest(view)
}
}
</code></pre>
<p>I immediately get to the result handler without a dialog showing up to ask me for permissions. I may or may not have confirmed the same permission in another (child) activity of the same app (doesn't seem to make a difference).</p>
<pre><code>override fun onRequestPermissionsResult(requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
BSMainActivity.permissionRequestSendProfilePic -> {
// This gets hit, MANAGE_DOCUMENTS was denied
if (permissions.contains(Manifest.permission.MANAGE_DOCUMENTS) && grantResults[permissions.indexOf(Manifest.permission.MANAGE_DOCUMENTS)] == PackageManager.PERMISSION_DENIED) {
Log.w(logName, "Permission to open image was denied while sending a tag request: %s %s".format(
permissions.joinToString(",", "[", "]"),
grantResults.joinToString(",", "[", "]")
))
}
// send request regardless of the result for now
sendRequest(cachedView)
}
}
}
</code></pre>
<p>In my manifest I have the following:</p>
<pre><code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="me.monomon.bs">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS"/>
</code></pre>
| <p>Only <a href="https://developer.android.com/guide/topics/security/permissions.html#permission-groups" rel="nofollow">dangerous permissions</a> can be requested at runtime and <code>MANAGE_DOCUMENTS</code> is not a dangerous permission.</p>
<p>As per the <a href="https://developer.android.com/reference/android/Manifest.permission.html#MANAGE_DOCUMENTS" rel="nofollow">MANAGE_DOCUMENTS documentation</a>:</p>
<blockquote>
<p>This permission should only be requested by the platform document management app. This permission cannot be granted to third-party apps.</p>
</blockquote>
|
TinyMCE how to dynamically get line breaks in a textarea <p>I need advice on how I can create dynamic line breaks ideally with an <code><li></code> inside TINY. I have tried using an each loop and also a for loop, and the values just do not appear in the text area. BUT, if I just add them to the text area with a val() they go in fine, BUT as just one long string. </p>
<p>The text area has an id of wo_materials. I'm successfully getting my text into Tiny like this: </p>
<pre><code> $('#wo_materials').val(materials);
tinymce.init({
selector:'textarea'
});
</code></pre>
<p>And I get a nice row of text values: </p>
<p><a href="http://i.stack.imgur.com/ptkcH.png" rel="nofollow"><img src="http://i.stack.imgur.com/ptkcH.png" alt="Values in TinyMCE"></a></p>
<p>The materials value is an array. If I look at it in the console it looks like this: </p>
<pre><code>0: BP #15 Plain Felt 36"
1: Duraflo Weatherpro 50
2: 1 1/4 Coil Nails - box
</code></pre>
<p>Thanks ! </p>
| <p>If you're only modifying the value of the text area before tinymce is initialized then this might work for you:</p>
<pre><code>$('#wo_materials).val(materials.join('<br/>'));
</code></pre>
|
Python can't find setuptools <p>I got the following ImportError as i tried to setup.py install a package:</p>
<pre><code>Traceback (most recent call last):
File "setup.py", line 4, in <module>
from setuptools import setup, Extension
ImportError: No module named setuptools
</code></pre>
<p>This happens although setuptools is already installed:</p>
<pre><code>amir@amir-debian:~$ sudo apt-get install python-setuptools
[sudo] password for amir:
Reading package lists... Done
Building dependency tree
Reading state information... Done
python-setuptools is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
</code></pre>
<p>Why can't python find the setuptools module? </p>
| <p>It's possible you have multiple python versions installed on your system. For example if you installed your python from source, and then again with apt-get. Apt-get will install to the default python version. Make sure you are being consistent. </p>
<p>Potentially using pip install setuptools could solve your problem.</p>
<p>Try these commands:</p>
<pre><code>$which python
/usr/bin/python
$python --version
Python 2.7.12
</code></pre>
<p>Making sure that the output matches your expectations.</p>
<p>It may be worth removing previous installations and starting over as this answer suggests:</p>
<p><a href="http://stackoverflow.com/questions/14426491/python-3-importerror-no-module-named-setuptools">Python 3: ImportError "No Module named Setuptools"</a></p>
|
How to use authenticated middleware properly in nodejs <p>I just started working on node using express framework. </p>
<pre><code>app.use('/', auth, users);
</code></pre>
<p>and this is my route file</p>
<pre><code>router.get('/' , function(req, res, next) {
render("dashboard");
});
router.get('/first' , function(req, res, next) {
//first request
});
router.get('/second' , function(req, res, next) {
//second request
});
so on...
</code></pre>
<p>My question is, when i pass middleware it checks for every request whether its authenticated or not using passportjs, but suppose i have a dashboard and i am sending 10 ajax requests to grab data for the widgets. So only for dashboard it will call deserialize function 11 times ,first to render the page and then for 10 ajax request. I read answer given over here,
<a href="http://stackoverflow.com/questions/24456015/how-to-properly-use-passport-js">How to properly use Passport.js?</a>
But is it fine to go with this approach?</p>
| <p>Yes, it is fine to go with this approach if you don't want to have security issues. You have to check the user for every request, it is very simple someone to check the network tab in the browser debugger, understand what's going on and then start spoofing your requests. You can't sacrifice security for performance because you want to execute few query less.</p>
|
Cannot read property of undefined angular 2 <p>Here is my detail view component</p>
<pre><code>import {Component,Input,Output,EventEmitter,OnInit} from "@angular/core";
import { Router, ActivatedRoute, Params } from '@angular/router';
import {TypeService} from './type.service'
import { PropertyTypes } from './type';
@Component({
selector:'property-type-view',
template:`
<div class="panel panel-default">
<div class="panel-heading">
<a [routerLink]="['../']"
class="btn btn-success">
<i class="fa fa-list" aria-hidden="true"></i>
</a>
<span class="title">
</span>
</div>
<div class="panel-body">
<div class="row">
{{(PropType | json).name}}
</div>
</div>
</div>
`,
styles:[`
.panel-default>.panel-heading>.title
{
color: #663663;
font-family: Arial, Helvetica, sans-serif;
font-size: 250%;
}
.panel-default>.panel-heading>.btn
{
position: relative;
top: -5px;
margin-left:5px;
}
`]
})
export class TypeViewComponent implements OnInit{
constructor(
private route: ActivatedRoute,
private router: Router,
private service: TypeService) {}
errorMessage: string;
private PropType: PropertyTypes[];
ngOnInit()
{
// (+) converts string 'id' to a number
let id = +this.route.snapshot.params['id'];
this.service.getPropType(id).subscribe(
PropType => this.PropType = PropType,
error => this.errorMessage = <any>error
);
}
}
</code></pre>
<p>if i try to return the whole object <code>{{PropType.name}}</code> without pipe filter i get the same error below is my service method </p>
<pre><code> getPropType(id:number):Observable <PropertyTypes[]> {
return this.http.get(this.TypeUrl+'/'+id)
.map(res=>res.json())
.catch(this.ThrowError); }
</code></pre>
<p>Want i want to achieve is to be able to print properties type details using <code>{{PropType.name}}</code> without crashing the app with the error i have tried Async pipe with safe operator such as <code>{{(PropType | async)?.name}}</code> still no luck any ideas?</p>
| <p>Have you tried to use: <code>*ngIf="PropType"</code> at the parent of <code>{{(PropType | json).name}}</code>? Because when html render your properties not.</p>
|
When iterating through large set of string set, for loop received signal SIGSEGV, Segmentation fault <p>I have a loop through a very large set of names below got segment fault, where is the issue ?</p>
<pre><code> void test(std::set<std::wstring> *names)
{
std::set<std::wstring>::iterator itr;
for (itr = names->begin(); itr != names->end(); ++itr)
{
std::wstring name = *itr;
}
}
</code></pre>
<p>Error:</p>
<blockquote>
<pre><code>Program received signal SIGSEGV, Segmentation fault.
0x00007fff84b62c54 in std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t>>::basic_string(std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> > const&)> () from /usr/lib/libc++.1.dylib
</code></pre>
</blockquote>
| <p>No problem with the code you show, as demonstrated by this <a href="http://ideone.com/npwoeh" rel="nofollow">MWE live at Ideone</a>:</p>
<pre><code>#include <iostream>
#include <set>
#include <string>
using namespace std;
void test(std::set<std::wstring> *names) {
std::set<std::wstring>::iterator itr;
for (itr = names->begin(); itr != names->end(); ++itr) {
std::wstring name = *itr;
}
}
int main() {
std::set<std::wstring> s{L"aasdasd", L"badsasd"};
test(&s);
return 0;
}
</code></pre>
<p>Therefore the issue is somewhere else in your code which is not shown. I'd suggest using a debugger such as <a href="http://www.unknownroad.com/rtfm/gdbtut/" rel="nofollow">gdb</a>, to find what is going on. E.g. on a Linux system:</p>
<ol>
<li>compile with -g flag <code>g++ -g main.cpp -o main</code></li>
<li>load in gdb with <code>gdb main</code></li>
<li><code>run</code> > read the stack trace</li>
</ol>
<p>As a side note, a for loop would be nicer, and if you don't plan to modify <code>names</code> pass it by const reference (<a href="http://ideone.com/VpW6Ml" rel="nofollow">example here on Ideone</a>):</p>
<pre><code>#include <iostream>
#include <set>
#include <string>
using namespace std;
void test(const std::set<std::wstring> &names) {
for (auto&& name : names) {
std::wcout << name << std::endl;
}
}
int main() {
std::set<std::wstring> s{L"aasdasd", L"badsasd"};
test(s);
return 0;
}
</code></pre>
|
nodejs readFileSync output is garbage <p>heres my code:</p>
<pre><code>var fs = require('fs');
var corpus = fs.readFileSync('./TXT/tragedies/Macbeth.txt', 'utf8');
console.log(corpus.toString());
</code></pre>
<p>When I run this I get a bunch of nonsense unicode characters:</p>
<pre><code>00\r\u0000\n\u0000<\u0000/\u0000S\u0000T\u0000A\u0000G\u0000E\u0000 \u0000D\u0000I\u0000R\u0000>\u0000\r\u0000\n\u0000\r\u0000\n\u0000<\u0000M\u0000A\u0000L\u0000C\u0000O\u0000L\u0000M\u0000>\u0000\t\u0000<\u00009\u00009\u0000%\u0000>\u0000\r\u0000\n\u0000\t\u0000W\u0000e\u0000 \u0000s\u0000h\u0000a\u0000l\u0000l\u0000 \u0000n\u0000o\u0000t\u0000 \u0000s\u0000p\u0000e\u0000n\u0000d\u0000 \u0000a\u0000 \u0000l\u0000a\u0000r\u0000g\u0000e\u0000 \u0000e\u0000x\u0000p\u0000e\u0000n\u0000s\u0000e\u0000 \u0000o\u0000f\u0000 \u0000t\u0000i\u0000m\u0000e\u0000\r\u0000\n\u0000\t\u0000B\u0000e\u0000f\u0000o\u0000r\u0000e\u0000 \u0000w\u0000e\u0000 \u0000r\u0000e\u0000c\u0000k\u0000o\u0000n\u0000 \u0000w\u0000i\u0000t\u0000h\u0000 \u0000y\u0000o\u0000u\u0000r\u0000 \u0000s\u0000e\u0000v\u0000e\u0000r\u0000a\u0000l\u0000 \u0000l\u0000o\u0000v\u0000e\u0000s\u0000,\u0000\r\u0000\n\u0000\t\u0000A\u0000n\u0000d\u0000 \u0000m\u0000a\u0000k\u0000e\u0000 \u0000u\u0000s\u0000 \u0000e\u0000v\u0000e\u0000n\u0000 \u0000w\u0000i\u0000t\u0000h\u0000 \u0000y\u0000o\u0000u\u0000.\u0000 \u0000M\u0000y\u0000 \u0000t\u0000h\u0000a\u0000n\u0000e\u0000s\u0000 \u0000a\u0000n\u0000d\u0000 \u0000k\u0000i\u0000n\u0000s\u0000m\u0000e\u0000n\u0000,\u0000\r\u0000\n\u0000\t\u0000H\u0000e\u0000n\u0000c\u0000e\u0000f\u0000o\u0000r\u0000t\u0000h\u0000 \u0000b\u0000e\u0000 \u0000e\u0000a\u0000r\u0000l\u0000s\u0000,\u0000 \u0000t\u0000h\u0000e\u0000 \u0000f\u0000i\u0000r\u0000s\u0000t\u0000 \u0000t\u0000h\u0000a\u0000t\u0000 \u0000e\u0000v\u0000e\u0000r\u0000 \u0000S\u0000c\u0000o\u0000t\u0000l\u0000a\u0000n\u0000d\u0000\r\u0000\n\u0000\t\u0000I\u0000n\u0000 \u0000s\u0000u\u0000c\u0000h\u0000 \u0000a\u0000n\u0000 \u0000h\u0000o\u0000n\u0000o\u0000u\u0000r\u0000 \u0000n\u0000a\u0000m\u0000\'\u0000d\u0000.\u0000 \u0000W\u0000h\u0000a\u0000t\u0000\'\u0000s\u0000 \u0000m\u0000o\u0000r\u0000e\u0000 \u0000t\u0000o\u0000 \u0000d\u0000o\u0000,\u0000\r\u0000\n\u0000\t\u0000W\u0000h\u0000i\u0000c\u0000h\u0000 \u0000w\u0000o\u0000u\u0000l\u0000d\u0000 \u0000b\u0000e\u0000 \u0000p\u0000l\u0000a\u0000n\u0000t\u0000e\u0000d\u0000 \u0000n\u0000e\u0000w\u0000l\u0000y\u0000 \u0000w\u0000i\u0000t\u0000h\u0000 \u0000t\u0000h\u0000e\u0000 \u0000t\u0000i\u0000m\u0000e\u0000,\u0000\r\u0000\n\u0000\t\u0000A\u0000s\u0000 \u0000c\u0000a\u0000l\u0000l\u0000i\u0000n\u0000g\u0000 \u0000h\u0000o\u0000m\u0000e\u0000 \u0000o\u0000u\u0000r\u0000 \u0000e\u0000x\u0000i\u0000l\u0000\'\u0000d\u0000 \u0000f\u0000r\u0000i\u0000e\u0000n\u0000d\u0000s\u0000 \u0000a\u0000b\u0000r\u0000o\u0000a\u0000d\u0000\r\u0000\n\u0000\t\u0000T\u0000h\u0000a\u0000t\u0000 \u0000f\u0000l\u0000e\u0000d\u0000 \u0000t\u0000h\u0000e\u0000 \u0000s\u0000n\u0000a\u0000r\u0000e\u0000s\u0000 \u0000o\u0000f\u0000 \u0000w\u0000a\u0000t\u0000c\u0000h\u0000f\u0000u\u0000l\u0000 \u0000t\u0000y\u0000r\u0000a\u0000n\u0000n\u0000y\u0000;\u0000\r\u0000\n\u0000\t\u0000P\u0000r\u0000o\u0000d\u0000u\u0000c\u0000i\u0000n\u0000g\u0000 \u0000f\u0000o\u0000r\u0000t\u0000h\u0000 \u0000t\u0000h\u0000e\u0000 \u0000c\u0000r\u0000u\u0000e\u0000l\u0000 \u0000m\u0000i\u0000n\u0000i\u0000s\u0000t\u0000e\u0000r\u0000s\u0000\r\u0000\n\u0000\t\u0000O\u0000f\u0000 \u0000t\u0000h\u0000i\u0000s\u0000 \u0000d\u0000e\u0000a\u0000d\u0000 \u0000b\u0000u\u0000t\u0000c\u0000h\u0000e\u0000r\u0000 \u0000a\u0000n\u0000d\u0000 \u0000h\u0000i\u0000s\u0000 \u0000f\u0000i\u0000e\u0000n\u0000d\u0000-\u0000l\u0000i\u0000k\u0000e\u0000 \u0000q\u0000u\u0000e\u0000e\u0000n\u0000,\u0000\r\u0000\n\u0000\t\u0000W\u0000h\u0000o\u0000,\u0000 \u0000a\u0000s\u0000 \u0000\'\u0000t\u0000i\u0000s\u0000 \u0000t\u0000h\u0000o\u0000u\u0000g\u0000h\u0000t\u0000,\u0000 \u0000b\u0000y\u0000 \u0000s\u0000e\u0000l\u0000f\u0000 \u0000a\u0000n\u0000d\u0000 \u0000v\u0000i\u0000o\u0000l\u0000e\u0000n\u0000t\u0000 \u0000h\u0000a\u0000n\u0000d\u0000s\u0000\r\u0000\n\u0000\t\u0000T\u0000o\u0000o\u0000k\u0000 \u0000o\u0000f\u0000f\u0000 \u0000h\u0000e\u0000r\u0000 \u0000l\u0000i\u0000f\u0000e\u0000;\u0000 \u0000t\u0000h\u0000i\u0000s\u0000,\u0000 \u0000a\u0000n\u0000d\u0000 \u0000w\u0000h\u0000a\u0000t\u0000 \u0000n\u0000e\u0000e\u0000d\u0000f\u0000u\u0000l\u0000 \u0000e\u0000l\u0000s\u0000e\u0000\r\u0000\n\u0000\t\u0000T\u0000h\u0000a\u0000t\u0000 \u0000c\u0000a\u0000l\u0000l\u0000s\u0000 \u0000u\u0000p\u0000o\u0000n\u0000 \u0000u\u0000s\u0000,\u0000 \u0000b\u0000y\u0000 \u0000t\u0000h\u0000e\u0000 \u0000g\u0000r\u0000a\u0000c\u0000e\u0000 \u0000o\u0000f\u0000 \u0000G\u0000r\u0000a\u0000c\u0000e\u0000\r\u0000\n\u0000\t\u0000W\u0000e\u0000 \u0000w\u0000i\u0000l\u0000l\u0000 \u0000p\u0000e\u0000r\u0000f\u0000o\u0000r\u0000m\u0000 \u0000i\u0000n\u0000 \u0000m\u0000e\u0000a\u0000s\u0000u\u0000r\u0000e\u0000,\u0000 \u0000t\u0000i\u0000m\u0000e\u0000,\u0000 \u0000a\u0000n\u0000d\u0000 \u0000p\u0000l\u0000a\u0000c\u0000e\u0000:\u0000\r\u0000\n\u0000\t\u0000S\u0000o\u0000,\u0000 \u0000t\u0000h\u0000a\u0000n\u0000k\u0000s\u0000 \u0000t\u0000o\u0000 \u0000a\u0000l\u0000l\u0000 \u0000a\u0000t\u0000 \u0000o\u0000n\u0000c\u0000e\u0000 \u0000a\u0000n\u0000d\u0000 \u0000t\u0000o\u0000 \u0000e\u0000a\u0000c\u0000h\u0000 \u0000o\u0000n\u0000e\u0000,\u0000\r\u0000\n\u0000\t\u0000W\u0000h\u0000o\u0000m\u0000 \u0000w\u0000e\u0000 \u0000i\u0000n\u0000v\u0000i\u0000t\u0000e\u0000 \u0000t\u0000o\u0000 \u0000s\u0000e\u0000e\u0000 \u0000u\u0000s\u0000 \u0000c\u0000r\u0000o\u0000w\u0000n\u0000\'\u0000d\u0000 \u0000a\u0000t\u0000 \u0000S\u0000c\u0000o\u0000n\u0000e\u0000.\u0000\r\u0000\n\u0000<\u0000/\u0000M\u0000A\u0000L\u0000C\u0000O\u0000L\u0000M\u0000>\u0000\r\u0000\n\u0000<\u0000S\u0000T\u0000A\u0000G\u0000E\u0000 \u0000D\u0000I\u0000R\u0000>\u0000\r\u0000\n\u0000<\u0000F\u0000l\u0000o\u0000u\u0000r\u0000i\u0000s\u0000h\u0000.\u0000 \u0000E\u0000x\u0000e\u0000u\u0000n\u0000t\u0000.\u0000>\u0000\r\u0000\n\u0000<\u0000/\u0000S\u0000T\u0000A\u0000G\u0000E\u0000 \u0000D\u0000I\u0000R\u0000>\u0000\r\u0000\n\u000
</code></pre>
<p>what am I doing wrong?</p>
| <p>Actually, you don't need to transform the output of readFileSync into a string, because it's already one.</p>
<pre><code>var fs = require('fs');
var file = fs.readFileSync("file.txt", "utf8");
console.log(file);
console.log(typeof file);
</code></pre>
<p>Output:</p>
<pre><code> File content
here's a new paragraph
string
</code></pre>
<p>Just for info, what version of Node are you using?
What I did works on 4.4.7.</p>
|
wpf userControl's child controls' unsubscribe events <p>I am hoping to have a generic (extension) method which takes parent control and traverse through to its all children controls and unsubscribe their events if any. </p>
<p><strong>problem</strong>
i am closely looking at memory consumption when i create some wpf based form, memory spike which is expected considering the number of ui elements and their events but when form closes i expect to memory get release as in wpf, i m assuming form get disposed automatically disposed once closed so GC should clean up and release the memory... but thats what not happening as i waited few minutes and looked on private memory usage in diagnostic tools, that remains same. so i m wondering its not completely disposing/unsubscribing events etc</p>
| <p>I can't speak to whether or not having many subscribed events negatively affects performance, but I can certainly answer your other two questions:</p>
<ol>
<li><p>You can use the following extension to enumerate all children:</p>
<pre><code>public static IEnumerable<T> GetVisualChildren<T>(this DependencyObject Parent) where T : DependencyObject
{
if (Parent != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(Parent); i++)
{
var Child = VisualTreeHelper.GetChild(Parent, i);
if (Child != null && Child is T)
yield return (T)Child;
foreach (var ChildOfChild in GetVisualChildren<T>(Child))
yield return ChildOfChild;
}
}
}
foreach (myControlInstance.GetVisualChildren<DependencyObject>())
{
//Unsubscribe events
}
</code></pre></li>
<li><p>To unsubscribe all events from the object, refer to this SO article:</p></li>
</ol>
<p><a href="http://stackoverflow.com/questions/447821/how-do-i-unsubscribe-all-handlers-from-an-event-for-a-particular-class-in-c">How do I unsubscribe all handlers from an event for a particular class in C#?</a></p>
|
PHP script times, regardless of `set_time_limit(0);` <p>I've got a PHP script using the API of another site and because of the number of requests being extensive, I get a timeout.</p>
<p>My script should take ~2 hours to execute, I have tried to prepend:</p>
<pre><code>set_time_limit(0);
ignore_user_abort(1);
</code></pre>
<p>but this doesn't work out, the page still times out.</p>
<p>What could cause this?</p>
| <p>I figured a work around on this one. May be a little messy, but it works. </p>
<p>I performed 20 API calls to go under the timeout range. Then I used $_SESSION counting and page refresh to create the number of API calls I required. </p>
<p>This means the page never times out.</p>
|
Issue in updating data into oracle database using JTextfields in java <p>On Update button press, following code snippet needs to be executed:
Note that: t1, t2,. . .,t8 are JTextfields. Also note that CUST_PHONE and ADV receive datatype number, whereas rest all are varchar.<br>
CUST_NAME is the Primary Key assumed;</p>
<pre><code>theQuery("update gkkdb set CUST_ID='"+t1.getText()+"', CUST_PHONE="+t3.getText()+",CUST_CAT='"+t4.getText()+"',ST_DATE='"+t5.getText()+"',ADV="+t6.getText()+",END_DATE='"+t7.getText()+"',ADDR='"+t8.getText()+"' where CUST_NAME="+t2.getText());
</code></pre>
<p>theQuery(String s) function is as follows:-</p>
<pre><code>public void theQuery(String query)
{
Connection con = null;
Statement st= null;
try{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con = DriverManager.getConnection("jdbc:oracle:thin:@Localhost:1521:xe","system","qwerty");
System.out.println("Database connected");
st= con.createStatement();
st.executeUpdate(query);
JOptionPane.showMessageDialog(null,"Customer Updated!");
} catch(Exception e)
{
JOptionPane.showMessageDialog(null,e.getMessage());
}
}
</code></pre>
<p>It is displaying error as: ORA-00904: "xxxx" :invalid identifier, where xxxx is any CUST_NAME which i am using to update data. </p>
| <p>Did you display the value of all your variables to make sure they contain data?</p>
<p>Is customer id a String or an Integer?</p>
<p>In any case use a <code>PreparedStatement</code> for the SQL to prevent errors. </p>
<p>A simple example to get your started:</p>
<pre><code>String sql = "UPDATE Page SET Title = ? WHERE Name = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, textField1.getText() );
stmt.setString( 2, textField2.getText() );
stmt.executeUpdate();
stmt.close();
</code></pre>
<p>I hope you get the idea. Each "?" gets replaced and you don't have to worry about the syntax. Much easier to read and spot mistakes.</p>
|
Need read some data from JSON <p>I need to make a get (id, name, fraction id) for each deputy in this json </p>
<pre><code>{
"id": "75785",
"title": "(за оÑновÑ)",
"asozdUrl": null,
"datetime": "2011-12-21T12:20:26+0400",
"votes": [
{
"deputy": {
"id": "99111772",
"name": "Ðбалаков ÐлекÑÐ°Ð½Ð´Ñ ÐиколаевиÑ",
"faction": {
"id": "72100004",
"title": "ÐÐРФ"
}
},
"result": "accept"
},
{
"deputy": {
"id": "99100491",
"name": "ÐбдÑлаÑипов Рамазан ÐаджимÑÑадовиÑ",
"faction": {
"id": "72100024",
"title": "ÐÐ "
}
},
"result": "none"
}
.......,` etc
</code></pre>
<hr>
<p>My code is looks like that: </p>
<pre><code>urlData = "https://raw.githubusercontent.com/data-dumaGovRu/vote/master/poll/2011-12-21/75785.json"
response = urllib.request.urlopen(urlData)
content = response.read()
data = json.loads(content.decode("utf8"))
for i in data:
#print(data["name"])
</code></pre>
<p>`
And i dont know what to do with that #print line, how I should write it?</p>
| <p>You can access the list containing the deputies with <code>data['votes']</code>. Iterating through the list, you can access the keys you're interested in as you would with dict key lookups. Nested dicts imply you have to walk through the keys starting from the root to your point of interest: </p>
<pre><code>for d in data['votes']:
print(d['deputy']['id'], d['deputy']['name'], d['deputy']['faction']['id'])
</code></pre>
|
Count iterations in a loop <p>New to programming. How to count and print iterations(attempts) I had on guessing the random number?` Let's say, I guessed the number from 3-rd attempt.</p>
<pre><code>import random
from time import sleep
str = ("Guess the number between 1 to 100")
print(str.center(80))
sleep(2)
number = random.randint(0, 100)
user_input = []
while user_input != number:
while True:
try:
user_input = int(input("\nEnter a number: "))
if user_input > 100:
print("You exceeded the input parameter, but anyways,")
elif user_input < 0:
print("You exceeded the input parameter, but anyways,")
break
except ValueError:
print("Not valid")
if number > user_input:
print("The number is greater that that you entered ")
elif number < user_input:
print("The number is smaller than that you entered ")
else:
print("Congratulation. You made it!")
</code></pre>
| <p>There are two questions being asked. First, how do you count the number of iterations? A simple way to do that is by creating a counter variable that increments (increases by 1) every time the <code>while</code> loop runs. Second, how do you print that number? Python has a number of ways to construct strings. One easy way is to simply add two strings together (i.e. concatenate them).</p>
<p>Here's an example:</p>
<pre><code>counter = 0
while your_condition_here:
counter += 1 # Same as counter = counter + 1
### Your code here ###
print('Number of iterations: ' + str(counter))
</code></pre>
<p>The value printed will be the number of times the <code>while</code> loop ran. However, you will have to explicitly convert anything that isn't already a string into a string for the concatenation to work.</p>
<p>You can also use formatted strings to construct your print message, which frees you from having to do the conversion to string explicitly, and may help with readability as well. Here is an example:</p>
<pre><code>print('The while loop ran {} times'.format(counter))
</code></pre>
<p>Calling the <code>format</code> function on a string allows you replace each instance of <code>{}</code> within the string with an argument.</p>
<p>Edit: Changed to reassignment operator</p>
|
[jQuery]Page is reloading, why? <p>So this is my html code:</p>
<pre><code><form action="" id="set_username">
<td><input id="username" type="text" maxlength="12" /><button>Save</button></td>
</form>
</code></pre>
<p>And this is my jQuery:</p>
<pre><code>$('#set_username').submit(function()){
var username = $('#username').val();
alert(username);
}
</code></pre>
<p>When i press the button, the page just simply just reload and does nothing.
Any idea why? Im new to jQuery but i cant find anything on google.
<br>
<br> Thanks in advance!</p>
| <p>If you want to stop the form to <em>actually</em> submit you can just <code>preventDefault</code>:</p>
<pre><code>$('#set_username').submit(function(e))
{
var username = $('#username').val();
alert(username);
e.preventDefault();
});
</code></pre>
|
Setting up static assets paths, routing endpoints with koa and various middleares <h2><strong>Question:</strong></h2>
<ol>
<li>How can I set up my static files so that both directories are visible to my <code>index.html</code>. </li>
<li>How can I send my <code>index.html</code> when you hit the default route using koa-router vs. just a <code>.json</code> file when I make an AJAX Get request?</li>
</ol>
<p><strong>Requirements:</strong> </p>
<p><em>I need static directories to be visible in my apps <code>src/index.html</code></em></p>
<ul>
<li><code>node_modules</code> needs to be open for js libs.</li>
<li><code>src/assets</code> needs to be open for images.</li>
</ul>
<p><em>I need a router for 2 purposes :</em></p>
<ul>
<li><p>1) serving up the initial <code>index.html</code></p></li>
<li><p>2) CRUD endpoints to my DB.</p></li>
</ul>
<p>Notes: I'm totally willing to add/subtract any middleware. But I would rather not change how I organize my directories.</p>
<p><strong>Directory Structure:</strong></p>
<p><a href="http://i.stack.imgur.com/2grmG.png" rel="nofollow"><img src="http://i.stack.imgur.com/2grmG.png" alt="directory structure"></a></p>
<p><strong>Middleware:</strong></p>
<ul>
<li><a href="https://github.com/koajs/static" rel="nofollow">koa-static</a> // cant serve node_modules + src directory.</li>
<li><a href="https://github.com/koajs/send" rel="nofollow">koa-send</a> // can send static files but then breaks koa-static</li>
<li><a href="https://github.com/alexmingoia/koa-router" rel="nofollow">koa-router</a> // cannot </li>
</ul>
<p><strong><code>app.js</code></strong></p>
<pre><code>var serve = require('koa-static');
var send = require('koa-send');
var router = require('koa-router')();
var koa = require('koa');
var app = koa();
// need this for client side packages.
app.use(serve('./node_modules/'));
// need this for client side images, video, audio etc.
app.use(serve('./src/assets/'));
// Will serve up the inital html until html5 routing takes over.
router.get('/', function *(next) {
// send up src/index.html
});
// will serve json open a socket
router.get('/people', function *(next) {
// send the people.json file
});
app.use(router.routes()).use(router.allowedMethods());
// errors
app.on('error', function(err, ctx){
log.error('server error', err, ctx);
});
app.listen(3000);
</code></pre>
<p><strong><code>index.html</code></strong></p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Morningharwood</title>
</head>
<body>
<h1>suchwow</h1>
<img src="./assets/image1.png" alt="butts"> <!-- will 404 with routing -->
<script src="./node_modules/gun/gun.js"></script> <!-- will always 404 -->
<script>
var gun = Gun(options);
console.log(gun);
</script>
</body>
</html>
</code></pre>
| <p>Well. it happens that I'm developing a similar kind of app</p>
<p>There's no problem on using koa-static to serve you static content and koa-router for you api endpoint. I never used koa-send directly. but I think you doesn't need too, given your set up</p>
<p>The only thing that matters is the order when attaching middleware to koa app. Try to attach koa-static first for your assets ( and maybe even index.html) and later use the koa-router for your api. Requests trying to get some static file never reach the router. and this way the router only responsibility will be serving your api</p>
<p>If that's not posible ( for example, because you have a bunch of non-static html files to server, consider taht you can have more than one router per app, even nesting one inside the other</p>
<p>( If the answer is not enough, give some time to cook a simple example. I'll post it as soon as possible)</p>
<p>EDIT: added a quick and dirty example <a href="https://gist.github.com/develmts/a3c1f89c8327f33f143da230ad52c7ae" rel="nofollow">here</a>. Probably it doesn't work out of the box, but it's enough to get the idea</p>
|
Flexbox - Weird img sizing issue <p>Weird issue keeps happening with this. </p>
<p>I want one of my flex items (an image) to be set to certain dimensions (w:300px h:300px).</p>
<p>When I open it to preview in my browser the image appears squashed up in the container as a flex item would normally behave (the text takes up most of the space.)</p>
<p>As soon as I resize my browser by even 1px the img then resizes to its specified dimensions (w:300px h:300px). </p>
<p>Is this what is supposed to happen? I'm using the Treehouse workspace text editor so I don't know if it's a bug with that or I'm doing something wrong?</p>
<p>Thanks,</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>.con {
display: flex;
background: gainsboro;
font-size: 1.8em;
}
.con img {
width: 300px;
height: 300px;
margin: 0 10px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="surgery con">
<img src="../img/cloud.jpg">
<p>Lorem ipsum dolor sit amet, urna sollicitudin pede sollicitudin fusce adipiscing vitae. Commodo egestas. Ut tempus, molestie integer in integer, pellentesque sed egestas duis, commodo sapien pellentesque turpis nulla tempor.</p>
</div></code></pre>
</div>
</div>
</p>
<p>Here's a screenshot of what it looks like when I open to preview:
<a href="http://imgur.com/a/Ejp8R" rel="nofollow">http://imgur.com/a/Ejp8R</a></p>
<p>Here's what it looks like as soon as I expand the browser:
<a href="http://imgur.com/a/xT5Yr" rel="nofollow">http://imgur.com/a/xT5Yr</a></p>
| <p>I suggest you to use <code>min-width</code> property. It will help you to avoid the weird img stretching.</p>
<p>JsFiddle: <a href="https://jsfiddle.net/5pbqfyam/" rel="nofollow">https://jsfiddle.net/5pbqfyam/</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>.con {
display: flex;
background: gainsboro;
font-size: 1.8em;
}
.con img {
min-width: 300px;
height: 300px;
margin: 0 10px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="surgery con">
<img src="../img/cloud.jpg">
<p>Lorem ipsum dolor sit amet, urna sollicitudin pede sollicitudin fusce adipiscing vitae. Commodo egestas. Ut tempus, molestie integer in integer, pellentesque sed egestas duis, commodo sapien pellentesque turpis nulla tempor.</p>
</div></code></pre>
</div>
</div>
</p>
|
jQuery-Page not loading correctly <p>I recently used accordion jquery to help me expand/collapse content ( like a drop-down menu )..I used this script and placed it in the <code><body></code></p>
<p>Script:</p>
<pre><code>jQuery(document).ready(function($)
{
$("#accordions-727.accordions").accordion({
active: "",
event: "click",
collapsible: true,
heightStyle: "content",
animated: "swing",
})
})
</code></pre>
<p>The script is working fine but the page is not loading correctly..When I view or refresh the page, all the contents inside the drop-down menu becomes visible but once the page finishes loading everything becomes fine..Now how can I fix this?..Should I place the script in the <code><head></code>?</p>
| <p>This is using jQueryUI accordion implicitly @Stew.</p>
<p>You have a wrong attribute in your accordion setup code, use the <code>animate</code> in place of <code>animated</code>.</p>
<p>Take a look in this API documentation: <a href="http://api.jqueryui.com/accordion" rel="nofollow">http://api.jqueryui.com/accordion</a> </p>
<p>And it's the original component demonstration: <a href="http://jqueryui.com/accordion/" rel="nofollow">http://jqueryui.com/accordion/</a></p>
<p>I suggest you to take a look in your jQuery files too, if they are OK and in the correct order (in <code><header></code> section).</p>
<p>Another point is to put your JavaScript in <code><header></code> section of your HTML and be sure you have no conflict or using older jQuery files versions than the component needs.</p>
<p>Hope it helps.</p>
|
How to do iterations to change dummy variable in multiple columns from 1 to 0 in Python and Pandas? <p>I have a dataframe that have over 200 columns of dummy variable:</p>
<pre><code>Row1 Feature1 Feature2 Feature3 Feature4 Feature5
A 0 1 1 1 0
B 0 0 1 1 1
C 1 0 1 0 1
D 0 1 0 1 0
</code></pre>
<p>I want to do iteration to separate each feature to create extra 3 dataframes with df1 only contains keep the first feature that=1 as 1 and change all the later columns to 0 and df2 only contains keep the second feature that=1 as 1 and change all the previous and later columns to 0.</p>
<p>I have create codes to do it, but I figured there gotta be better ways to do it. Please help me with a more efficient way to approach this. Thank you!</p>
<p>Below is my code:</p>
<pre><code>for index, row in hcit1.iterrows():
for i in range(1,261):
title="feature"+str(i)
if int(row[title])==1:
for j in range(i+1,261):
title2="feature"+str(j)
hcit1.loc[index,title2]=0
else:
pass
for index, row in hcit2.iterrows():
for i in range(1,261):
title="feature"+str(i)
if int(row[title])==1:
for j in range(i+1,261):
title2="feature"+str(j)
if row[title2]==1:
for k in range(j+1,261):
title3="feature"+str(k)
hcit1.loc[index,title3]=0
hcit1.loc[index,title]=0
else:
pass
for index, row in hcit3.iterrows():
for i in range(1,261):
title="feature"+str(i)
if int(row[title])==1:
for j in range(i+1,261):
title2="feature"+str(j)
if row[title2]==1:
for k in range(j+1,261):
title3="feature"+str(k)
if row[title3]==1:
for l in range(k+1,261):
title4="feature"+str(l)
hcit1.loc[index,title4]=0
hcit1.loc[index,title2]=0
hcit1.loc[index,title]=0
else:
pass
for index, row in hcit4.iterrows():
for i in range(1,261):
title="feature"+str(i)
if int(row[title])==1:
for j in range(i+1,261):
title2="feature"+str(j)
if row[title2]==1:
for k in range(j+1,261):
title3="feature"+str(k)
if row[title3]==1:
for l in range(k+1,261):
title4="feature"+str(l)
if row[title4]==1:
for m in range(l+1,261):
title5="feature"+str(m)
hcit1.loc[index,title5]=0
hcit1.loc[index,title3]=0
hcit1.loc[index,title2]=0
hcit1.loc[index,title]=0
else:
pass
</code></pre>
| <p>Here:</p>
<pre><code>df1 = df[df['Feature1'] == 1]
df1.iloc[:, :] = 0
df1.loc[:, 'Feature1'] = 1
df2 = df[df['Feature2'] == 1]
df2.iloc[:, :] = 0
df2.loc[:, 'Feature2'] = 1
df3 = df[df['Feature2'] == 1]
df3.iloc[:, :] = 0
df3.loc[:, 'Feature3'] = 1
</code></pre>
<p>That should be what you are looking for.</p>
|
How to query MySQL ignoring particular characters <p>In a database I have something like this "something (something_else)",
is it possible using a "LIKE" query for you to query and get aforementioned to result when querying the database with "something something_else" (so without the "()" characters).</p>
| <p>You can use replace on the criteria and the field to remove the characters. Something like:</p>
<pre><code>SELECT * FROM table
WHERE REPLACE(REPLACE(field, '(', ''), ')', '')
LIKE REPLACE(REPLACE('something something_else', '(', ''), ')', '')
</code></pre>
|
Getting a difference between time(n+1)-time(n) in a dataframe in r <p>I have a dataframe where the columns represent monthly data and the rows different simulations. the data I am working with accumulates over time so I want to take the difference between the months to get the true value for that month. There are not headers for my data frame</p>
<p>For example:</p>
<p>View(df)=</p>
<p>1 3 4 6 19 23 24 25 26 ...</p>
<p>1 2 3 4 5 6 7 8 9 ...</p>
<p>0 0 2 3 5 7 14 14 14 ...</p>
<p>My plan was to use the diff() function or something like it, but I am having trouble using it on a dataframe. </p>
<p>I have tried:
df1<-diff(df, lag = 1, differences = 1)
but only get zeros.</p>
<p>I am grateful for any advice.</p>
| <p>see <code>?apply</code>. If it's a data frame</p>
<pre><code>apply(df,2,diff)
</code></pre>
<p>should work. Also since a dataframe is a list of vectors <code>sapply(df,diff)</code> should work.</p>
|
PHP user profile page <p>Im trying to make a website with users on it, and I'm trying to create a script so that whenever a new user registers it will automatically create a user folder and profile for them but when I try to register it doesn't create the files,<br> could someone please help me with this, Thanks</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-html lang-html prettyprint-override"><code><?php
include "inc/header.php";
$newfolder = $username;
if (!mkdir($newfolder, 0777, true)) {
die('Failed to create folders...');
}
$pagename = $username;
$newFileName = './u/'.$username.'/'.$pagename.".php";
$newFileContent = '<?php echo "something..."; ?>';
?></code></pre>
</div>
</div>
</p>
| <p><strong>To make a directory/file</strong></p>
<pre><code>if (!file_exists("parent_folder/$username")) {
//Create a file with read write execute PERMISSIONS ENABLED
//Please check : your parent folder also must have 0777 permissions to avoid any kind of read write error
mkdir("parent_folder/$username", 0777);
//now u have to create a FILE with .php
//now this file_put_contents is VERY importnant !
$pagename = $username ;
$newFileName = './parent_folder/$username/'.$pagename.".php";
$newFileContent = '<?php echo "something..."; ?>';
if (file_put_contents($newFileName, $newFileContent) !== false) {
//notify file is created
echo "File created (" . basename($newFileName) . ")";
} else {
//notify u have error
echo "Cannot create file (" . basename($newFileName) . ")";
}
//now create ur .php file in user folder
}
else {
echo "Your parent folder does not exist"
}
</code></pre>
<p><strong>Now the possible error and some tips</strong></p>
<p>1) Most of people do fopen("filename_with_PATH", "w")
and expect that file will be generated in PATH folder !
Some times it might fall wrong (depends on version) </p>
<blockquote>
<p>fopen is meant to create a file in the directory where your php resides</p>
</blockquote>
<p>2) <strong>check ur php permission in php.ini</strong> if u dont give php permission to write,remote access then u might get some errors (it will be displayed that u have error in my script)</p>
<p>3)For more info and tinkering <a href="http://php.net/manual/en/function.file-put-contents.php" rel="nofollow">file_put_contents</a></p>
<p>Hope this will be helpful for you ..</p>
|
jQuery : How to replace an element with a new and only show the new one? <p>In the following code I am showing order_status in admin panel of opencart when admin edits an order. The order status is showing perfectly fine.</p>
<pre><code> <?php if ($info_data['order_status']) { ?>
<tr>
<td><?php echo $info_data['text_order_status'];?</td>
<td id="order-status"><?php echo $info_data['order_status']; ?></td>
</tr>
<?php } ?>
</code></pre>
<p>But when admin update the order_status by selecting from a drop down list it shows the updated order_status with the old order_status. I need to only show the updated order_status , How can I replace the old status with the updated order_status?</p>
<pre><code>if (json['success']) {
$('#history').load('index.php?route=sale/order/history&token=<?php echo $token; ?>&order_id=<?php echo $order_id; ?>&shipping_code=<?php echo $shipping_code; ?>');
$('#history').before('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + ' <button type="button" class="close" data-dismiss="alert">&times;</button></div>');
$('textarea[name=\'comment\']').val('');
$('#order_tracking_number').val('');
$('#order-status').html($('select[name=\'order_status_id\'] option:selected').text());
}
</code></pre>
<p>I guess this line should do the replacement , but it is not working properly , what should I change? Please Help !</p>
<pre><code>$('#order-status').html($('select[name=\'order_status_id\'] option:selected').text());
</code></pre>
<p>UPDATE :
Code for select box </p>
<pre><code> <div class="form-group">
<label class="col-sm-2 control-label"
for="input-order-status"><?php echo $info_data['entry_order_status']; ?></label>
<div class="col-sm-10">
<select name="order_status_id" id="input-order-status" class="form-control">
<?php foreach ($info_data['order_statuses'] as $order_statuses) { ?>
<?php if ($order_statuses['order_status_id'] == $info_data['order_status_id']) { ?>
<option value="<?php echo $order_statuses['order_status_id']; ?>"
selected="selected"><?php echo $order_statuses['name']; ?></option>
<?php } else { ?>
<option
value="<?php echo $order_statuses['order_status_id']; ?>"><?php echo $order_statuses['name']; ?></option>
<?php } ?>
<?php } ?>
</select>
</div>
</div>
</code></pre>
| <p>Try this:</p>
<p>from:</p>
<pre><code>$('#order-status').html($('select[name=\'order_status_id\'] option:selected').text());
</code></pre>
<p>to:</p>
<pre><code>$('#order-status').html($('#input-order-status option:selected').text());
</code></pre>
<p>if you want to call your selectbox with name then change it</p>
<p>to:</p>
<pre><code>$('#order-status').html($('select[name="order_status_id"] option:selected').text());
</code></pre>
|
type java.lang.string cannot be converted to jsonarray <p>I am using volley to connect the php from android, but it's show me error please some help me here a my java & php code .php is connect to database php show -1 'success'=>false result.</p>
<pre><code>public class main extends Activity{
String i = "";
String d = "";
String ya = "";
String is = "";
String to="";
final Response.Listener<String> responseListener = new Response.Listener<String>() {
@Override
public void onResponse(String response)
{
JSONObject jsonResponse = null;
try {
JSONArray array = new JSONArray(response);
jsonResponse = array.getJSONObject(0);
Log.w(TAG, "onResponse: jsonresponse" + response.toString());
boolean success = jsonResponse.getBoolean("success");
if (success) {
i = jsonResponse.getString("i");
d = jsonResponse.getString("d");
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Inp insQ = new Inp(ya,is ,to ,responseListener);
RequestQueue queue = Volley.newRequestQueue(main.this);
queue.add(insQ);}
// next ins class - commented at edit by Jeff
public class Ins extends StringRequest
{
public static final String REGISTER_REQUEST_URL = "edu.php";
private static final String TAG = "Ins";
private Map<String,String> params;
public Ins(String ya, String is, String to, Response.Listener listener)
{
super(Request.Method.POST, REGISTER_REQUEST_URL, listener, null);
Log.w(TAG, "Ins: " + ya + is + to );
params = new HashMap<>();
params.put("ya", ya);
params.put("is",is);
params.put("to", to + "");
Log.w(TAG, "Ins working well " + ya + is +to );
}
@Override
public Map<String,String> getParams() {
return params;
}
}
</code></pre>
<p>php code start</p>
<pre><code><?php
$servername = "localhost";
$username = "****";
$password = "*****";
$dbname = "*****";
$em = $_POST['ya'];
$one = $_POST['is'];
$to = $_POST['to'];
$d = date('Y-m-d');
$y = date('y');
$m = date('m');
$d = date('d');
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sqll = "SELECT * FROM jio";
$res = mysqli_query($conn,$sqll);
$rowC = mysqli_num_rows($res);
$rowC = $rowC%999 + 1;
if($rowC < 10){
$i = $year.$mon.$day.'00'.$rowC;
}elseif (rowC < 100) {
$i = $year.$mon.$day.'0'.$rowC;
}else {
$i = $year.$mon.$day.$rowC;
}
$sql = "INSERT INTO jio(iu,i, d, ya, is, qs,to,ra,wto,wi,wk,)VALUES('0',".$i."','".$d."','".$em."','".$one."', '-1','".$to."','0','0','0','0')";
$r = mysqli_query($conn, $sql);
$rows=mysqli_affected_rows($conn);
$result = array();
if($rows>0) {
array_push($result,array(
'success'=>true,
'i' => $i,
'd' =>$d
));
}
else
array_push($result,array(
'success'=>false
));
echo json_encode($result);
mysqli_close($conn);
?>
</code></pre>
| <p>According to the "problem" you've described I guess all the syntax errors in your code came from porting the code to here.</p>
<p>It seems that - if I understood you correctly - your only problem is a simple missing <code>'</code> in your sql:</p>
<pre><code> // here
$sql = "INSERT INTO jio(iu,i, d, ya, is, qs,to,ra,wto,wi,wk,)VALUES('0',".$i."','".$d."','".$em."','".$one."', '-1','".$to."','0','0','0','0')";
</code></pre>
<p>This will cause <code>$rows</code> to be false (because of a mysqli error), so your if sets 'success' to false.</p>
<p>The corrected sql would be </p>
<pre><code>$sql = "INSERT INTO jio(iu,i, d, ya, is, qs,to,ra,wto,wi,wk,)VALUES('0','".$i."','".$d."','".$em."','".$one."', '-1','".$to."','0','0','0','0')";
// this is the critical part:
// ...,'".$i."',...
</code></pre>
<p><em>NOTES</em><br>
You should better switch to <a href="http://php.net/manual/en/mysqli.quickstart.prepared-statements.php" rel="nofollow">prepared statements</a>, because you're open to <a href="https://de.wikipedia.org/wiki/SQL-Injection" rel="nofollow">sql-injection</a>.
Also, better check first if your query was successful or if there were any errors.</p>
<pre><code>$r = mysqli_query($conn, $sql);
if($r) {
// work with the result
} else {
// an error occurred. Show it, handle it, whatever.
echo mysqli_error($conn);
}
</code></pre>
<p>Also, you don't need to <code>array_push</code> in php. It's much easier to use that syntax:</p>
<pre><code>$result = array();
if($rows>0) {
$result[] = array(
'success'=>true,
'i' => $i,
'd' =>$d
);
}
else { // don't forget these brackets here!
$result[] = array(
'success'=>false
);
} // and here
</code></pre>
<p>And finally: You don't need to close a mysqli-connection at the end of a script, as it will be terminated at the end anyway.</p>
|
Jquery Modal on click add class then remove <p>This bit of code is supposed to add a class and then with a delay remove the div entirely. It just jumps to deleting the div. Any ideas why? </p>
<p>The HTML</p>
<pre><code> <!-- modal conent-->
<div class="modal" id="modal">
<div class="modal-content ">
<h1>Tricks Are 4 Kids</h1>
<p>Ok so my modal doesn't look like this one, but this is it boiled down. Can I write the JS better??? ....</p>
<button href="#" class="close" id="close" >X</button>
</div>
</div>
</div>
<!-- page conent-->
<div id="page-content-wrapper" >I am a div with all the page conent. lalalalala</div>
</code></pre>
<p>The CSS</p>
<pre><code>.red {background:red;}
</code></pre>
<p>The jQuery</p>
<pre><code>$(document).ready( function() {
$( "#close" ).click(function() {
$("#modal").addClass("red").delay(800).queue
$("#modal").remove();
});
</code></pre>
<p>Codepen <a href="https://codepen.io/Ella33/pen/GjQZRP" rel="nofollow">https://codepen.io/Ella33/pen/GjQZRP</a></p>
| <pre><code>$(document).ready( function() {
$( "#close" ).click(function() {
$("#modal").addClass("red");
setTimeout(function() {
$("#modal").remove();
}, 800);
});
</code></pre>
|
Import-DscResource cannot find the package cChoco <p>I am trying to write a DSC script that will be published into Azure Virtual machine. So far I have been able to accomplish basic things like enabling windows features and creating directories. But now I want to install chocolatey on azure virtual machine. So this is my script </p>
<pre><code>configuration IIsAspNetInstall
{
Import-DscResource -ModuleName cChoco
node "localhost"
{
WindowsFeature IIS
{
Ensure="present"
Name="web-server"
}
WindowsFeature InstallDotNet45
{
Name = "Web-Asp-Net45"
Ensure = "Present"
}
WindowsFeature InstallIISConsole
{
Name = "Web-Mgmt-Console"
Ensure = "Present"
}
File WebsiteFolderCreate
{
Ensure = "Present"
Type = "Directory"
DestinationPath = "C:\inetpub\wwwroot\AdventureWorks"
Force = $true
}
cChocoInstaller installChoco
{
InstallDir = "C:\choco"
}
}
}
</code></pre>
<p>On my local machine I am using PowerShell 5.0 and inside ISE I get red squiggly lines under <code>Import-DscResource</code> saying cannot find moduleName cChoco. I know it is a keyword and supposed to be valid inside Configuration section. When I do <code>Publish-AzureVMDscConfiguration</code> I get a parse error </p>
<pre><code>+ Import-DscResource -ModuleName cChoco
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Could not find the module 'cChoco'.
</code></pre>
| <p>You can bundle the module in the DSC package, either manually (by putting it in the a subfolder in the zip file) or by using the Publish-AzureVMDSCConfiguration cmdlets. If the module is installed on the machine where you run the cmdlet, it will look at all the import module statements in your PS1 file and package them for you - once package, when you run the script on the destination machine, the module(s) will be installed automatically too...</p>
|
Data submission via PHP server-side <p>I am baffled why the form won't send and then be redirected to index.php page. I'm very new to PHP and trying to use the User object. Here's what I have so far. </p>
<pre><code><main>
<header>
<h1>Create New Account</h1>
</header>
<section id="formEntry">
<form id="createacct" name="createacct" action="CreateAccount.php" method="post" onsubmit="return validateForm()">
<fieldset>
<legend>Enter your information</legend>
<table>
<tr>
<td class="fieldName">First Name</td>
<td class="inputField"><input type="text" id="firstname" name="firstname" form="createacct" size="30" maxlength="50" onchange="firstNameUpdated()"></td>
<td id="firstnamemsg"></td>
</tr>
<tr>
<td class="fieldName">Last Name</td>
<td class="inputField"><input type="text" id="lastname" name="lastname" form="createacct" size="30" maxlength="50" onchange="lastNameUpdated()"></td>
<td id="lastnamemsg"></td>
</tr>
<tr>
<td class="fieldName">Email</td>
<td class="inputField"><input type="email" id="emailAddress" name="emailAddress" form="createacct" size="30" maxlength="50" onchange="emailUpdated()"></td>
<td id="emailmsg"></td>
</tr>
<tr>
<td class="fieldName">Select a username</td>
<td class="inputField"><input type="text" id="username" name="username" form="createacct" size="30" maxlength="50" onchange="usernameUpdated()"></td>
<td id="usernamemsg"></td>
</tr>
<tr>
<td class="fieldName">Enter your password</td>
<td class="inputField"><input type="password" id="password" name="password" form="createacct" size="30" maxlength="50" onchange="pwdUpdated()"></td>
<td id="passwordmsg"></td>
</tr>
<tr>
<td class="fieldName">Confirm password</td>
<td class="inputField"><input type="password" id="confirmpwd" name="confirmpwd" form="createacct" size="30" maxlength="50" onchange="confirmUpdated()"></td>
<td id="confirmpwdmsg"></td>
</tr>
<tr>
<td id="saveMsg"></td>
<td colspan="2" class="submitButton">
<input type="reset" value="Clear all fields" class="styleButton" onclick="clearFields(this)">
<input type="submit" value="Create New Account" class="styleButton" onclick="return createNewAccount()">
</td>
</tr>
</table>
</fieldset>
</form>
</section>
<?php
include 'CreateAccount.php';
$user = new User();
$user->first = trim($_POST["firstname"]);
$user->last = trim($_POST["lastname"]);
$user->emailaddress = trim($_POST["emailAddress"]);
$user->username = trim($_POST["username"]);
$user->password = trim($_POST["password"]);
$user->confirmpwd = trim($_POST["confirmpwd"]);
$isValid = $user->validate();
?>
</main>
</code></pre>
<p>And the PHP File (CreateAccount.php): </p>
<pre><code><?php
Class User {
public $first;
public $last;
public $emailaddress;
public $username;
public $password;
public $confirmpwd;
// validation function
function validate() {
if (($this->first != null || $this->first != '') &&
($this->last != null || $this->last != '') &&
($this->emailaddress != null || $this->emailaddress != '') &&
($this->username != null || $this->username != '') &&
($this->password != null || $this->password != '') &&
($this->confirmpwd != null || $this->confirmpwd != '') &&
($this->password === $this->confirmpwd)) {
storeData($this->first, $this->last, $this->emailaddress, $this->username, $this->password);
header('Location: TestPage.php');
} else {
header('Location: CreateNewAccount.php');
}
}
}
exit()
</code></pre>
<p>?></p>
<p>What am I doing wrong here? Every time I submit, it redirects me to CreateAccount.php and comes out blank. Thanks for your help. </p>
| <pre><code><?php
# In your CreateAccount.php,
# update your code like this
Class User {
public $first;
public $last;
public $emailaddress;
public $username;
public $password;
public $confirmpwd;
// validation function
function validate() {
if (($this->first != null || $this->first != '') &&
($this->last != null || $this->last != '') &&
($this->emailaddress != null || $this->emailaddress != '') &&
($this->username != null || $this->username != '') &&
($this->password != null || $this->password != '') &&
($this->confirmpwd != null || $this->confirmpwd != '') &&
($this->password === $this->confirmpwd)) {
storeData($this->first, $this->last, $this->emailaddress, $this->username, $this->password);
header('Location: TestPage.php');
} else {
header('Location: CreateNewAccount.php');
}
}
}
#notice that the exit code is been removed and hopefully this should work..
</code></pre>
|
Using rmarkdown::render to set document header (title, author, date) <p>I am using <code>rmarkdown::render("script.r")</code> to create an HTML version of an R script. The output starts with <strong>script.r</strong> as title, my login as author, and the current <code>date</code> as date. I don't want to give away my login, nor my work schedule..</p>
<p>I know this metadata (title, author, date) can be set in a YAML block inside a <code>Rmd</code> file, but I would like to avoid creating/editing this file, and work only with the original R script.</p>
<p>Is there a way to set (title, author, date) metadata via <code>rmarkdown::render</code>, or other functions like <code>knitr::opts_chunk$set</code>?</p>
<p>Alternatively, can this metadata be set inside the R script?</p>
<p>Please avoid suggesting that I should write an <code>Rmd</code> file instead..</p>
| <p>The Rmarkdown documentation (see <code>?compile_notebook</code>) describes one way to do this by including a specially formatted comment in your <code>script.R</code> file.</p>
<p>For example, include this comment in your script to set the title, author and date.</p>
<pre><code>#' ---
#' title: "Crop Analysis Q3 2013"
#' author: "John Smith"
#' date: "May 3rd, 2014"
#' ---
</code></pre>
<p>This will give you the following output:</p>
<p><a href="http://i.stack.imgur.com/m3w0v.png" rel="nofollow"><img src="http://i.stack.imgur.com/m3w0v.png" alt="rmarkdown_output"></a></p>
|
How many bytes are used by variable in hexadecimal? <p>I am currently studying for a test and I came across this question and for some reason I seem to be having a hard time with it and I was hoping I could get some clarification here. </p>
<p>I found an answer on yahoo answers but it came with no explanation and I don't really believe thats the answer. It simply states that 0040006Ah - 00400020h = 4A = 74 bytes.</p>
<p>The question is this:
<strong>The address of var1 is 00400020h. The address of the next variable after var1 is 0040006Ah. How many bytes are used by var1?</strong></p>
<p>Please correct me if I'm wrong but it is to my understanding that each "digit" represented by a hexadecimal value contains 4 bits. So if my understanding of the question is correct, the answer should be less then a byte. Since the difference of 4A does not equate to a byte. The difference has to be at least FFh to count as a byte. Please correct me or point me in a right direction if I am wrong</p>
| <p>Each address is a separate byte. Memory is byte-addressable. i.e. <code>0x0040006A</code> is the address of a whole byte.</p>
<p><code>0040006Ah - 00400020h</code> is a difference in address of 0x4A = 74, which means a difference of 74 bytes.</p>
<p>Addresses in asm map 1:1 with <code>char *</code> in C, on normal machines. (This is not guaranteed by the C standard, this is just a fact of normal C implementations).</p>
|
Counting number of steps till a number gets to 1 <p>The goal of this function is to count the number of steps it takes a number to get to 1 after performing operations. The number you put into the function is divided by 2 if the number is even, and tripled and increased by 1 if the number is odd. These operations are performed on the number until it reaches one. For example, if you start out with the number 3 it would go through these steps: 3 >10 >5 >16 >8 >4 >2 >1 the function would need to return the number "8" because it took 8 steps for 3 to get to 1 after dividing even numbers and multiplying by 3 and adding 1 to odd numbers.</p>
<p>Here is my code so far. I understood how to have my function return the first step (Example: I could have 3 return 10 and 6 return 3) but I can't figure out how to have my function count the number of steps it took to reach 1.</p>
<pre><code>def collatz_counts(n):
total = 0
while n > 1:
if n % 2 == 0:
n =(n // 2)
total += 1
elif n % 2 == 1:
n = (3 * n + 1)
total += 1
return total
</code></pre>
| <p>You need to adjust the code to make it return after the <code>while</code> loop. Otherwise, it will return too early if it meet odd number.</p>
<p>Additionally, <code>total += 1</code> is done in both case; you can move it out of <code>if .. elif ..</code> block.</p>
<pre><code>def collatz_counts(n):
total = 0
while n > 1:
if n % 2 == 0:
n =(n // 2)
elif n % 2 == 1:
n = (3 * n + 1)
total += 1 # <---
return total # <---
</code></pre>
<p>BTW, <code>collatz_counts(3)</code> will return 7. You need to adjust initial <code>total</code> value to 1 to get 8.</p>
|
Python3 requests library to submit form that disallows post request <p>I am trying to get the police district from a given location at the <a href="https://www.phillypolice.com/districts/" rel="nofollow">Philly Police webpage</a>. I too many locations to do this by hand, so I am trying to automate the process using Python's requests library. The webpage's form that holds the location value is as follows:</p>
<pre><code><form id="search-form" method="post" action="districts/searchAddress">
<fieldset>
<div class="clearfix">
<label for="search-address-box"><span>Enter Your Street Address</span></label>
<div class="input">
<input tabindex="1" class="district-street-address-input" id="search-address-box" name="name" type="text" value="">
</div>
</div>
<div class="actions" style="float: left;">
<button tabindex="3" type="submit" class="btn btn-success">Search</button>
</div>
<a id="use-location" href="https://www.phillypolice.com/districts/index.html?_ID=7&_ClassName=DistrictsHomePage#" style="float: left; margin: 7px 0 0 12px;"><i class="icon-location-arrow"></i>Use Current Location</a>
<div id="current-location-display" style="display: none;"><p>Where I am right now.</p></div>
</fieldset>
</form>
</code></pre>
<p>However when I try to post or put to the webpage using the following: </p>
<pre><code>r = requests.post('http://www.phillypolice.com/districts',data={'search-address-box':'425 E. Roosevelt Blvd'})
</code></pre>
<p>I get error 405, POST is not allowed. I then turned off Javascript and tried to find the district on the webpage, and when I hit submit I received the same 405 error message. Therefore the form is definitely not submitted and the district is found using JavaScript.</p>
<p>Is there a way to simulate 'clicking' the submit button to trigger the JavaScript using the requests library?</p>
| <p>The data is retrieved after first querying google maps to the the coordinates where the final request is a get like the following:</p>
<p><a href="http://i.stack.imgur.com/gBwqd.png" rel="nofollow"><img src="http://i.stack.imgur.com/gBwqd.png" alt="enter image description here"></a> </p>
<p>You can setup a free account with the <a href="https://www.bingmapsportal.com/" rel="nofollow">bing maps api</a> and get the coords you need to make the get request:</p>
<pre><code>import requests
key = "my_key"
coord_params = {"output": "json",
"key": key}
# This provides the coordinates.
coords_url = "https://dev.virtualearth.net/REST/v1/Locations"
# Template to pass each address to in your actual loop.
template = "{add},US"
url = "https://api.phillypolice.com/jsonservice/Map/searchAddress.json"
with requests.Session() as s:
# Add the query param passing in each zipcode
coord_params["query"] = template.format(add="425 E. Roosevelt Blvd")
js = s.get(coords_url, params=coord_params).json()
# Parse latitude and longitude from the returned json.
# Call str to make make it into `(lat, lon)`
latitude_longitude = str((js[u'resourceSets'][0][u'resources'][0]["point"][u'coordinates']))
data = s.get(url, params={"latlng": latitude_longitude})
print(data.json())
</code></pre>
<p>If we run it minus my key:</p>
<pre><code>In [2]: import requests
...:
...: key = "my_key..."
...:
...: coord_params = {"output": "json",
...: "key": key}
...: coords_url = "https://dev.virtualearth.net/REST/v1/Locations"
...: template = "{add},US"
...: url = "https://api.phillypolice.com/jsonservice/Map/searchAddress.json"
...: with requests.Session() as s:
...: coord_params["query"] = template.format(add="425 E. Roosevelt Blvd")
...:
...: js = s.get(coords_url, params=coord_params).json()
...: latitude_longitude = str(js[u'resourceSets'][0][u'resources'][0]["po
...: int"][u'coordinates'])
...: print(latitude_longitude)
...: data = s.get(url, params={"latlng": latitude_longitude})
...: print(data.json())
...:
[40.02735900878906, -75.1153564453125]
{'response': ['35', '2', 'Marques Newsome', 'PPD.35_PSA2@phila.gov ', '267-357-1436']}
</code></pre>
<p>You can see it matches the response you see if you look at the request in your browser.</p>
|
Is open() a system call? <p>I am sorry I asked a stupid question because I know open() is a system call for Linux kernel. What I really want to ask is I just had a homework about learning the difference between fopen() and open(). I know fopen() is in the C standard library, so that I definitely can call fopen() function in my C program. What I am confused is why I can call open() function in my C program as well because open() should be a system call, so it is not a C function in the standard library. If I successfully called open() function, am I calling a C function or a system call? </p>
| <p>Although the distinction between "system call" and "library function" can be a useful one to keep in mind, there's the issue that you have to be able to call system calls somehow. In general, then, every system call is present in the C library -- as a thin little library function that does nothing but make the transfer to the system call (however that's implemented).</p>
<p>So, yes, you can call <code>open()</code> from C code if you want to. (And somewhere, perhaps in a file called <code>fopen.c</code>, the author of your C library probably called it too, within the implementation of <code>fopen()</code>.)</p>
|
using sessions to add an edit button for the right user <p>Lets say I have a lot of reviews on a web page. and I have a <code>req.session.shortId = f43f1</code>. I'm new to sessions but I think that each person that goes to the page will have their own <code>req.session.shortId</code>. (I have this in my schema <code>shortId : {type : String, unique : true, default : shortId.generate},</code> ) </p>
<p>some reviews are made by one person and I want to have those reviews have an edit button. only the person that has the session should be able to see the edit button. I have on the page something like this <code><div class = "f43f1">Review</div></code> , <code><div class = "f43aa">Review</div></code>. I only want <code>f43f1</code> to have the button because that is the value of <code>req.session.shortId</code>. I was thinking of doing something like this on the server.</p>
<pre><code>if(req.session.shortId == req.body.shortId){
I really don't know what to do
how would I tell the user's div that he can edit the button
I do stuff like this
res.render("index", {user : user, comp, comp, how do I send out tell the specific div to put the edit button })
}
</code></pre>
<p>Truthfully I don't even want the shortId in the div because of security concers. I don't know how developers handle this type of situation</p>
| <p>It seems like you would have that shortId stored with your review in the database. Which should make it easy enough to do something like this in your node app:</p>
<p><code>res.render('index', {shortId: req.session.shortId, review: review});</code></p>
<p>Then on your ejs template you should be able to conditionally display the button similar to something like this:</p>
<pre><code><% if (shortId === review.shortId) { %>
<button type="submit">Edit</button>
<% } %>
</code></pre>
<p>Sorry if the syntax is a little off here, it's been a while since I've worked with EJS.</p>
|
Count days on a column case <p>I would like to create a SQL script that counts the number of age days and the something like:(The catch is I got the days value of breaking value of one column by case to three columns) This is the output I have created.</p>
<pre><code>Days0To30 Days30to60 Daysto60to90
----------------------------------
50$ | 10$ | 90$
60$ | 0 | 10$
0 | 0 | 5$
0 | 10$ | 0
10$ | 0 | 0
0$ | 0 | 0
1240 | 0 | 0
</code></pre>
<p>I would like to create a SQL script that counts the number of age days and the something like:</p>
<pre><code>------------------------------------------
Days0To30 | 4
Days30to60 | 2
Daysto60to90 | 3
</code></pre>
| <p>You can use <code>conditional aggregation</code>:</p>
<pre><code>select count(case when Days0To30 <> 0 then 1 end) as Days0To30,
count(case when Days30to60 <> 0 then 1 end) as Days30to60,
count(case when Daysto60to90 <> 0 then 1 end) as Daysto60to90
from yourtable
</code></pre>
|
When i try to scrape details page for image I get an error <p>I am trying to get the image of the details page from a website. I am using the rss 'links' function to get the links. This is my code</p>
<pre><code>@app.task
def pan_task():
url = 'http://feeds.example.com/reuters/technologyNews'
name = 'noticiassin'
live_leaks = [i for i in feedparser.parse(url).entries][:10]
the_count = len(live_leaks)
ky = feedparser.parse(url).keys()
oky = [i.keys() for i in feedparser.parse(url).entries][1] # shows what I can pull
def make_soup(url):
def swappo():
user_one = ' "Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0" '
user_two = ' "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5)" '
user_thr = ' "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko" '
user_for = ' "Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:10.0) Gecko/20100101 Firefox/10.0" '
agent_list = [user_one, user_two, user_thr, user_for]
a = random.choice(agent_list)
return a
headers = {
"user-agent": swappo(),
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"accept-charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3",
"accept-encoding": "gzip,deflate,sdch",
"accept-language": "en-US,en;q=0.8",
}
the_comments_page = requests.get(url, headers=headers)
soupdata = BeautifulSoup(the_comments_page.text, 'html5lib')
# comment = soupdata.find('a').get('src')
# para = comment.find_all('p')
# kids = [child.text for child in para]
# blu = str(kids).strip('[]')
return soupdata
try:
live_entries = [{'href': live_leak.links[0]['href']} for live_leak in live_leaks]
o = make_soup(live_entries)
except IndexError:
print('error check logs')
live_entries = []
return print(o)
</code></pre>
<p>but when I try I get this error</p>
<pre><code>[2016-10-07 21:10:58,019: ERROR/MainProcess] Task blog.tasks.pan_task[f43ed360-c06e-4a4b-95ab-4f44a4564afa] raised unexpected: InvalidSchema("No connection adapters were found for '[{'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/AA1uAIpygjQ/us-apple-samsung-elec-appeal-idUSKCN1271LF'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/Nz28cqiuS0Y/us-google-pixel-advertising-idUSKCN12721U'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/POLoFj22hc4/us-yahoo-nsa-order-idUSKCN12800D'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/eF-XlhlQl-s/us-fcc-dataservices-idUSKCN1271RB'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/hNf9IQ3rXjw/us-autonomous-nauto-idUSKCN1271FX'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/NXkk5WfWVhM/us-sony-sensors-idUSKCN1270EC'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/gdBvoarqQro/us-yahoo-discrimination-lawsuit-idUSKCN12800K'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/nt8K--27bDg/us-thomsonreuters-ceo-idUSKCN1271DQ'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/f8z3eQg2Fpo/us-snapchat-ipo-idUSKCN12627S'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/rr4vdLsC11Y/us-samsung-elec-results-idUSKCN1262NO'}]'",)
Traceback (most recent call last):
File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/celery/app/trace.py", line 240, in trace_task
R = retval = fun(*args, **kwargs)
File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/celery/app/trace.py", line 438, in __protected_call__
return self.run(*args, **kwargs)
File "/Users/ray/Desktop/myheroku/practice/src/blog/tasks.py", line 134, in pan_task
o = make_soup(live_entries)
File "/Users/ray/Desktop/myheroku/practice/src/blog/tasks.py", line 124, in make_soup
the_comments_page = requests.get(url, headers=headers)
File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/requests/api.py", line 67, in get
return request('get', url, params=params, **kwargs)
File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/requests/api.py", line 53, in request
return session.request(method=method, url=url, **kwargs)
File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/requests/sessions.py", line 468, in request
resp = self.send(prep, **send_kwargs)
File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/requests/sessions.py", line 570, in send
adapter = self.get_adapter(url=request.url)
File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/requests/sessions.py", line 644, in get_adapter
raise InvalidSchema("No connection adapters were found for '%s'" % url)
requests.exceptions.InvalidSchema: No connection adapters were found for '[{'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/AA1uAIpygjQ/us-apple-samsung-elec-appeal-idUSKCN1271LF'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/Nz28cqiuS0Y/us-google-pixel-advertising-idUSKCN12721U'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/POLoFj22hc4/us-yahoo-nsa-order-idUSKCN12800D'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/eF-XlhlQl-s/us-fcc-dataservices-idUSKCN1271RB'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/hNf9IQ3rXjw/us-autonomous-nauto-idUSKCN1271FX'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/NXkk5WfWVhM/us-sony-sensors-idUSKCN1270EC'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/gdBvoarqQro/us-yahoo-discrimination-lawsuit-idUSKCN12800K'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/nt8K--27bDg/us-thomsonreuters-ceo-idUSKCN1271DQ'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/f8z3eQg2Fpo/us-snapchat-ipo-idUSKCN12627S'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/rr4vdLsC11Y/us-samsung-elec-results-idUSKCN1262NO'}]'
</code></pre>
<p>whhy this not working? I use the function in another program.</p>
| <p>You need to do something like this:</p>
<pre><code>@app.task
def pan_task():
url = 'http://feeds.example.com/reuters/technologyNews'
name = 'noticiassin'
live_leaks = [i for i in feedparser.parse(url).entries][:10]
the_count = len(live_leaks)
ky = feedparser.parse(url).keys()
oky = [i.keys() for i in feedparser.parse(url).entries][1] # shows what I can pull
def make_soup(url):
def swappo():
user_one = ' "Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0" '
user_two = ' "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5)" '
user_thr = ' "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko" '
user_for = ' "Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:10.0) Gecko/20100101 Firefox/10.0" '
agent_list = [user_one, user_two, user_thr, user_for]
a = random.choice(agent_list)
return a
headers = {
"user-agent": swappo(),
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"accept-charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3",
"accept-encoding": "gzip,deflate,sdch",
"accept-language": "en-US,en;q=0.8",
}
the_comments_page = requests.get(url, headers=headers)
soupdata = BeautifulSoup(the_comments_page.text, 'html5lib')
# comment = soupdata.find('div')
# para = comment.find_all('p')
# kids = [child.text for child in para]
# blu = str(kids).strip('[]')
return soupdata
live_entries = []
try:
for live_leak in live_leaks:
live_entries.append(make_soup(live_leak.links[0]['href']))
# Do what ever you need to do to o here
except IndexError:
print('error check logs')
live_entries = []
return live_entries
</code></pre>
|
pull objects with a matching attribute from ngrx/store in Angular2 <p>if I have a store that consists of <code>preferences</code> with a sample looking like:</p>
<p><code>
preferences: [{
name: 'pref1',
accepted: true,
contents: {
type: 'boolean',
value: true
}, {
name: 'pref2',
accepted: false,
contents: {
type: 'boolean',
value: true
},
...
]
</code></p>
<p>and using a <code>ngrx</code> store with a <code>reducer</code> I want two different values. The first I want is all the preferences which I can grab using:</p>
<p><code>this.preferences = this._store.select('preferences');</code></p>
<p>I'd also like to grab only the preferences with <code>accepted: true</code>, and keep the result as an <code>Observable</code> so I can pipe it into an Angular 2 module using the <code>async</code> pipe. I've tried things like:</p>
<p><code>this.acceptedPreferences = this._store.select('preferences').filter(preference => preference.accepted === true);</code></p>
<p>but I can't find the correct syntax, and haven't been able to find a good example of what I'm looking for to make it work. My real application is more complicated, and I need to keep track of a few attributes of my stored objects to created multiple subsets of data to pass through my application. It's possible I should be storing them all using individual reducers, but since they all reference the same data set, it seemed appropriate to handle the subsets using <code>Observables</code> and filtering out the results.</p>
| <p>Your preferences won't be flattened, the value emitted by the <code>select</code> will be an array of preferences, with a new array emitted upon changes.</p>
<p>You can use an RxJS <code>map</code> operator and the <code>Array.prototype.filter</code> method to filter your array of preferences:</p>
<pre><code>this.acceptedPreferences = this._store
.select('preferences')
.map((preferences) => preferences.filter((preference) => preference.accepted));
</code></pre>
<p>The resultant <code>acceptedPreferences</code> observable will emit an array of accepted preferences whenever the preferences in the store change.</p>
|
RETURN PREVIOUS CONTROLLER UIbutton action <p>I want the method to implement in UIbutton action to return to a previous controller, when button is tapped.
Regards
Very grateful for the answer :)</p>
| <p><strong>Swift 3 Xcode 8</strong></p>
<pre><code>@IBAction func close(_ sender: AnyObject) {
dismiss(animated: true , completion: nil)
}
</code></pre>
|
case statement in sybase <p>I have following requirement for Sybase Query:-</p>
<p>Exclude below if:</p>
<ul>
<li>The SSN has more or less than nine digits</li>
<li>The SSN includes non-numeric characters</li>
<li>The SSN is blank</li>
<li>The SSN includes the same digits (for example, 000000000, 111111111 or 999999999)</li>
<li>The SSN has a 9 as the first digit and a 7, 8 or 9 as the fourth digit</li>
<li>The fourth and the fifth digits are 00 (except 800-00-0000)</li>
<li>The sixth through ninth digits are 0000</li>
</ul>
<p>I wrote case statement as below but it's not working, can someone help please:</p>
<pre><code>SELECT CASE
WHEN LEN(a.MEMBER_SSN) > 9 THEN ' '
WHEN LEN(a.MEMBER_SSN) < 9 THEN ' '
WHEN LTRIM(RTRIM(a.MEMBER_SSN)) like '%[A-Z,a-z]%' then ' '
WHEN LTRIM(RTRIM(WHEN a.MEMBER_SSN)) like '%[0-9]%' then ' '
WHEN LTRIM(RTRIM(a.MEMBER_SSN)) in ( '000000000','000000001','000000002','000000003','000000004','000000005','999999999','111111111','000000070','123456789','999999998','000000071','888888888', ) THEN ''
WHEN LTRIM(RTRIM(a.MEMBER_SSN)) NOT LIKE '9__[789]%' THEN a.MEMBER_SSN ELSE ' '
WHEN LTRIM(RTRIM(a.MEMBER_SSN)) NOT LIKE '____[00]%' THEN a.MEMBER_SSN ELSE ' '
WHEN LTRIM(RTRIM(a.MEMBER_SSN)) NOT LIKE '_____[0000]%' THEN a.MEMBER_SSN ELSE ' '
END AS SUBSCRIBER_SSN From dbo.MEMBER_TABLE a
</code></pre>
| <p>Here is a shorter version:</p>
<pre><code>SELECT (CASE WHEN LEN(a.MEMBER_SSN) <> 9 THEN ' '
WHEN a.MEMBER_SSN LIKE '%[^0-9]%' THEN ' '
WHEN REPLACE(a.MEMBER_SSN, LEFT(a.MEMBER_SSN, 1), '') = '' THEN ' '
WHEN a.MEMBER_SSN LIKE '9__[789]%' THEN ' '
WHEN a.MEMBER_SSN LIKE '___00%' AND a.MEMBER_SSN <> '800-00-0000' THEN ' '
WHEN a.MEMBER_SSN LIKE '%0000' THEN ' '
ELSE a.MEMBER_SSN
END) AS SUBSCRIBER_SSN
From dbo.MEMBER_TABLE a
</code></pre>
<p>This is almost a direct transcription of your conditions.</p>
|
If statement skipping else if straight to else <p>I'm attempting to make the statement below do the following.
If age is greater than 20 and less than 50, continue.
If age is less than 20 and greater than 50, error restart.
if anything else, error, restart.</p>
<p>But, for some reason it skips right over the else if condition and goes straight to else. If I input "19" for age, it outputs "Error.", if I input 51 for age, it outputs "Error." Whats up?</p>
<pre><code>#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int plyAgeCreate() {
int plyAge = 0;
cout << "Enter an age" << endl;
cin >> plyAge;
//If age is greator than 20 and less than 50, accept.
//Else if age is less than 20 but greator than 50, decline.
//else, error. Restart.
if (plyAge >= 20 && plyAge <= 50) {
cout << "Welcome!" << endl;
}
else if (plyAge < 20 && plyAge > 50) { //Why is this being skipped?
cout << "Between 20 and 50" << endl;
return plyAgeCreate();
}
else {
cout << "Error" << endl;
return plyAgeCreate();
}
}
int main()
{
plyAgeCreate();
system("pause");
return 0;
}
</code></pre>
| <p>Wrong logic:</p>
<blockquote>
<p>else if (plyAge < 20 && plyAge > 50) // this condition can never be true</p>
</blockquote>
<p>should be</p>
<pre><code>else if (plyAge < 20 || plyAge > 50)
</code></pre>
|
Is there a more recursive way to do this? <p>I have the following code:</p>
<pre><code>{% if thing.parent.parent.parent.link %}
<a href="/y/{{ thing.parent.parent.parent.link }}">{{ thing.parent.parent.parent.name }}</a>
{% endif %}
{% if thing.parent.parent.link %}
<a href="/y/{{ thing.parent.parent.link }}">{{ thing.parent.parent.name }}</a>
{% endif %}
{% if thing.parent.link %}
<a href="/y/{{ thing.parent.link }}">{{ thing.parent.name }}</a>
{% endif %}
</code></pre>
<p>The key thing that changes in this non-recursive code, is simply adding a .parent to the link/link text.</p>
<p>I need to do this 20 times in total, as you can see, it's quite ugly to repeat and quite repetitive. Is there a more recursive and nicer way of doing it using django's template framework?</p>
| <p>Return a list in your context and then you can use an iterative approach:</p>
<pre><code>{% for parent in parents %}
<a href="/y/{{ parent.link }}">{{ parent.name }}</a>
{% endfor %}
</code></pre>
<p>Since nothing special has to be done if it is a child (as you mentioned, the only difference is link and name), you can just convert the things' parents to a list. I cannot give an exact method to do this without knowing more about your data structures, but maybe this will give you an idea:</p>
<pre><code> parents = []
for thing in things:
node = thing
while hasattr(node, 'parent'):
parents.append(node.parent)
node = node.parent
</code></pre>
|
Can I list all users assigned to one or more user stories that are related to a specific feature in Rally? <p>I am trying to create a kanban board or custom grid that will show the following:</p>
<ul>
<li>Features tagged with "tag name"</li>
<li>All users assigned to any user stories/tasks linked to the feature</li>
</ul>
<p>I see that you can list all artifacts with the (Tags.Name contains [yourtagnamehere]) in order to get all of the initiatives/features/etc. with their corresponding stories, but is there a way to look into the actual owners of those stories to generate a list of team members"? </p>
| <p>This functionality exists in the API via the Collaborators field on PortfolioItem, but for some reason the Collaborators field was never really exposed correctly on boards/grids.</p>
<p>I forked the Custom List app and added support for the Collaborators field. You can copy/paste this into a Custom HTML app and give it a spin:</p>
<p><a href="https://github.com/krmorse/CollaboratorsCustomListApp/blob/master/deploy/App-uncompressed.html" rel="nofollow">https://github.com/krmorse/CollaboratorsCustomListApp/blob/master/deploy/App-uncompressed.html</a></p>
|
Can Kullback-Leibler be applied to compare two images? <p>I know that KL is not a metric, and cannot be considered one. However, is it possible to use KL to measure how one image varies from another? I am trying to make an intuitive sense out of this. Thanks in advance for all responses.</p>
| <p>The KL measures the difference between two probability distributions. </p>
<p>In order to apply it in images you will need to transform the image to a probability distribution.</p>
<p>A simple example will be the take the histogram of the image(in gray scale) and than divide the histogram values by the total number of pixels in the image. This will result in the probability to find a gray value in the image.</p>
<p>Apply this to both images and than use the KL to measure the difference between the images.</p>
<p>This is not a real good way to measure the difference between the images because it doesn't take into consideration the spatial information of the images only the gray values information.</p>
<p>Therefor you will need to find a better transformation that will take into account the spatial distribution of the pixel color values. Look at this to get some ideas <a href="http://mathematica.stackexchange.com/questions/91627/how-to-transform-an-image-into-a-probability-density-function">http://mathematica.stackexchange.com/questions/91627/how-to-transform-an-image-into-a-probability-density-function</a></p>
|
How to start an android emulator in ubuntu 16.04? <p>I have android sdk installed, I've looked up directions which say to rune <code>~/android-sdk-linux/tools/android</code> and then click on a tools menu, but there is no tools menu.</p>
<p>I've also tried downloading virtual machine manager, but when I started that emulator it said I needed to insert an sd card.</p>
<p>How do I start an android emulator on ubuntu 16.04?</p>
| <p>Run</p>
<pre><code>~/android-sdk-linux/tools/android avd
</code></pre>
<p>to start in AVD manager mode.</p>
|
My contact form will not validate its input fields. It will submit an email to me while my input fields are blank. Any suggestions? <p>As stated, my php contact form will send me a blank email message however, it will not validate null input values. Any suggestions? I've tried about everything I know to do. </p>
<p>I'm also wondering if there is a way that I can redirect to a thankyou.html page on submit. I remember the php being something like "header..." to redirect. </p>
<pre><code> if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$from = 'Demo Contact Form';
$to = 'email@example.com';
$subject = 'Message from Contact Demo ';
$body = "From: $name\n E-Mail: $email";
// Check if name has been entered
if (!$_POST['name']) = 0; {
$errName = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
// If there are no errors, send the email
if (!$errName && !$errEmail) {
if (mail ($to, $subject, $body, $from)) {
$result='<div class="alert alert-success">Thank You! I will be in touch</div>';
} else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
}
}
}
?>
</code></pre>
<p>HTML...</p>
<pre><code> <!--FORM-->
<form role="form" action="contact.php" method="post" class="form-horizontal align-center">
<div class="form-group col-centered">
<label class="control-label col-sm-4 text-align-center">NAME</label>
<div class="control col-sm-4">
<input type="text" id="name" name="name" class="form-control">
<?php echo "<p class='text-danger'>$errName</p>";?>
</div>
</div>
<div class="form-group col-centered">
<label class="control-label col-sm-4 text-align-center">EMAIL</label>
<div class="control col-sm-4">
<input type="text" id="email" name="name" class="form-control">
<?php echo "<p class='text-danger'>$errEmail</p>";?>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4 text-align-center">PHONE</label>
<div class="col-sm-4">
<input type="text" name="phone" class="form-control">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" name="submit" value="submit" class="btnSize btn btn-default btn-lg"><strong>SAVE $150</strong></button>
</div>
</div>
</form>
</code></pre>
<p>Thanks for your time. </p>
| <p>Here's my take on it:</p>
<pre><code>if (isset($_POST["submit"])) {
$name = !empty( $_POST['name'] ) ? $_POST['name'] : false;
$email = !empty( $_POST['email'] ) ? filter_var($_POST['email'],FILTER_VALIDATE_EMAIL) : false;
if( $name && $email ){
$from = 'Demo Contact Form';
$to = 'email@example.com';
$subject = 'Message from Contact Demo ';
$body = "From: $name\n E-Mail: $email";
if (mail ($to, $subject, $body, $from)) {
$result='<div class="alert alert-success">Thank You! I will be in touch</div>';
} else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
}
}else{
$errors = [];
if( !$name ) $errors [] ='Invalid Name entered';
if( !$email ) $errors [] ='Invalid Email entered';
$result= '<div class="alert alert-danger">'.implode('<br>', $errors ).'</div>';
}
}
</code></pre>
<p><code>filter_var()</code> returns the filtered var or false on failure, so with that and the ternary <code>{if} ? true : false;</code> we can normalize your input and simply everything after that.</p>
<p>We check the inputs as soon as possible, that way we run as little code as needed to get to the end result. We know right away if they are good and can skip the majority of the email code, and output our error message.</p>
<p>Logically we can dump the error flag, an in the else we know one or both inputs are false. The array and implode is just a simpler way of putting in a line break. It's also easier to extend by just adding another input in with minimal code changes. As you can see it would be very easy to add another ternary statement, an and condition and an error message. ( only 2.5 ish lines )</p>
<p>One thing I would do on top of that is this</p>
<pre><code> $post = array_map('trim', $_POST);
</code></pre>
<p>And then change all the <code>$_POST</code> to <code>$post</code>, this will account for names added in as spaces or extra white space from Copy and Pasting, a common occurrence.</p>
<p>Further you may be able to minimize the errors like this </p>
<pre><code>}else{
$result= '<div class="alert alert-danger">'.implode('<br>', array_filter([
$name ? false : 'Invalid Name entered',
$email ? false : 'Invalid Email entered',
])).'</div>;
}
</code></pre>
|
html - Why my three buttons are vertical instead of horizontal? <p>Sorry for the confusing I caused. I did not paste my code because it is part of my big assignment. Also, I do not sure what parts of code cause the problem. So I paste the parts of the code that contains these three buttons </p>
<p>I want to make these three button display horizontally( Which I think is default). However, the website shows them vertically. Could anyone tell me the reason behind it? what should I do to make them horizontally. </p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
</div>
<div id="Comparing Energy" class="tab">
<h3 style="color:darkblue;"> Units for comparing energy (Gasoline and Enthanol) </h3>
<p class="Sansserif">BTU stands for British Thermal Unit, which is a unit of energy consumed by or delivered to a building. A BTU is defined as the amount of energy required to increase the temperature of 1 pound of water by 1 degree Fahrenheit, at normal atmospheric pressure. Energy consumption is expressed in BTU to allow for consumption comparisons among fuels that are measured in different units. [think-energy.net]</p>
<pre class="Sansserif"><span style="font-family:sans-serif;">Below are some BTU content of common energy units:
1 gallon of heating oil = 138,500 BTU
1 cubic foot of natural gas = 1,032 BTU
1 gallon of propane = 91,333 BTU
</span></pre>
<p class="Sansserif"><b>Let's compare the different energy amount between burn gasoline and ethanol</b></p>
<button onclick="expandable()"><b>Calculate</b></button>
<p id="inputinfo" class="Sansserif" style="display:none"> By entering the amount of gasoline, this program will perform the appropriate calculations and display the equivalent amount of energy it produces in BTU. Please input a number: </p>
<input id="btu" style="display:none" onkeyup="myDefault()">
<button id="energybutton" onclick="energy()" style="display:none;"><b>Submit</b></button>
<button id="wizardbutton" onclick="wizard()" style="display:none;"><b>Wizard</b></button>
<button id="slidebutton" onclick="simple()" style="display: none;"><b>Simple</b></button>
<p id="numb2" style="display:none">
<input type=radio name=myradio onclick=document.getElementById("btu").value=1>Small<br>
<input type=radio name=myradio onclick=document.getElementById("btu").value=4>Medium<br>
<input type=radio name=myradio onclick=document.getElementById("btu").value=6>Large<br>
</p>
<p id="BTU"></p>
<p id="defaultValue"></p>
<script>
function energy() {
var x, text;
// Get the value of the input field with id="numb"
x = document.getElementById('btu').value;
j = x * 115000
t = x*76700
text = " "+x+" gallon of gas produces "+j+" BTU "+x+" gallon of ethanol produces "+t+" BTU";
document.getElementById("BTU").innerHTML = text;
}
function myDefault() {
var x = document.getElementById('btu').value;
if (x <= 10)
document.getElementById("defaultValue").innerHTML = "A typical small one is 5";
else if ((x > 10) && (x <= 20))
document.getElementById("defaultValue").innerHTML = "A typical medium one is 15";
else if (x > 20)
document.getElementById("defaultValue").innerHTML = "A typical large one is 25";
else
document.getElementById("defaultValue").innerHTML = " ";
}
function wizard() {
var v = prompt("By entering the amount of gasoline, this program will perform the appropriate calculations and display the equivalent amount of energy it produces in BTU. Please input a number: ");
if (v != null) {
document.getElementById('btu').value=v;
}
}
function simple() {
document.getElementById('btu').style.display='none';
document.getElementById('numb2').style.display='block';
}
function expandable() {
document.getElementById('inputinfo').style.display='block';
document.getElementById('btu').style.display='block';
document.getElementById('energybutton').style.display='block';
document.getElementById('wizardbutton').style.display='block';
document.getElementById('slidebutton').style.display='block';
}
</script>
</div>
</body>
</html>
</code></pre>
| <p>Hard to say without the rest of your code present, but probably some other CSS is causing the buttons to render as <code>block</code> elements instead of their standard <code>inline</code> display mode.</p>
<p>You could write the following CSS rule:</p>
<pre><code>#energybutton, #wizardbutton, #slidebutton {
display: inline !important;
}
</code></pre>
<p>And it would probably solve it, but that seems a little ugly and the <code>!important</code> is undoubtedly overkill. If you'd like to provide some more context I or someone else could provide a more elegant answer, but my hunch is this might work for you.</p>
<p>Edit:
Seeing your exit with more code the issue is obvious- in your <code>expandable</code> method you are changing the buttons to <code>display: block</code> -- this is why they are displaying with breaks between then. Instead, set the <code>display</code> property to <code>inline</code> or <code>inline-block</code> to achieve the desired effect.</p>
<p>Incidentally, it might be more robust to hide/show the buttons not directly by directly manipulating styles in JS, but instead by adding/removing a class with the desired associated CSS set.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.