text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Mapping to a collection of objects using XSLT from Legacy web service
I am trying to populate xml using XSLT from data received from an external legacy web service which provides machine generated values for hotel information. They provide hotels with the element names having underscore and a number as shown below
for example HotelName_1, HotelName_2 etc. How do I to map these field names with underscores to my elements?
<!-- Web Service Results.. part of a larger schema, machine generated...-->
<Hotel_Info>
<Hotel_1>
<HotelName_1>La Quinta Inn</HotelName>
<HotelAddressLine1Text_1>552 12th Street West</HotelAddressLine1Text>
<HotelCityName>Dickinson_1</HotelCityName>
<HotelStateCode_1>ND</HotelStateCode>
<HotelZip5Code_1>58601</HotelZip5Code>
<HotelZip4Code_1>099</HotelZip4Code>
</Hotel_1>
<Hotel_2>
<HotelName_2></HotelName>
<HotelAddressLine1Text_2>3803 13th Ave S</HotelAddressLine1Text>
<HotelCityName_2>Fargo</HotelCityName>
<HotelStateCode_2>ND</HotelStateCode>
<HotelZip5Code_2>58103</HotelZip5Code>
<HotelZip4Code_2>099</HotelZip4Code>
</Hotel_2>
....
</Hotel_Info>
<!-- Map to this schema -->
<AvailableHotels>
<Hotel>
<HotelName>La Quinta Inn</HotelName>
<HotelAddressLine1Text>552 12th Street West</HotelAddressLine1Text>
<HotelCityName>Dickinson</HotelCityName>
<HotelStateCode>ND</HotelStateCode>
<HotelZip5Code>58601</HotelZip5Code>
<HotelZip4Code>099</HotelZip4Code>
</Hotel>
<Hotel>
<HotelName></HotelName>
<HotelAddressLine1Text>3803 13th Ave S</HotelAddressLine1Text>
<HotelCityName>Fargo</HotelCityName>
<HotelStateCode>ND</HotelStateCode>
<HotelZip5Code>58103</HotelZip5Code>
<HotelZip4Code>099</HotelZip4Code>
</Hotel>
</AvailableHotels>
A:
How do I to map these field names with underscores to my elements?
Here's one way you could look at it:
<xsl:template match="Hotel_Info">
<AvailableHotels>
<xsl:for-each select="*">
<Hotel>
<HotelName>
<xsl:value-of select="*[starts-with(name(), HotelName)]"/>
</HotelName>
<!-- more here -->
</Hotel>
</xsl:for-each>
</AvailableHotels>
</xsl:template>
Or, if your schema matches theirs, apart from the underscores (and the underscores are consistent - unlike shown in your example):
<xsl:template match="/Hotel_Info">
<AvailableHotels>
<xsl:for-each select="*">
<Hotel>
<xsl:for-each select="*">
<xsl:element name="{substring-before(name(), '_')}">
<xsl:value-of select="."/>
</xsl:element>
</xsl:for-each>
</Hotel>
</xsl:for-each>
</AvailableHotels>
</xsl:template>
| {
"pile_set_name": "StackExchange"
} |
Q:
Integral of $e^{mx^{3}}$
The question asks for the integral of $e^{mx^{3}}.$ How do I calculate the antiderivative of a function that has $e^{x^{3}}$ lets say. I want to make sure I know how to take the antiderivative of exponential functions.
A:
Let $mt^3=-u,$
$$\int_0^xe^{mt^3}\ dt=-\int_0^{mx^3}\frac1{3\sqrt[3]{mu}}e^{-u}\ du=-\frac1{3\sqrt[3]{m}}\gamma\left(\frac23,mx^3\right)$$
where $\gamma(a,b)$ is the lower incomplete gamma function.
| {
"pile_set_name": "StackExchange"
} |
Q:
Button doesn't appear in android appwidget layout
I have this xml file as a layout of an appwidget:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@android:color/black" >
<!-- ListView to be shown on widget -->
<ListView
android:id="@+id/listViewWidget"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/refresh_appwidget"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="refresh"
/>
</LinearLayout>
The button is not displayed, and I don't know the cause. I tested layout_with match_parent but always the same result.
How can I fix this issue?
A:
Set a fixed height for the listview for example android:layout_height="400dp" in LinearLayout.
Or use a RelativeLayout
Or add your button as a footer to listview. So you can see the button when you scroll down
Or add your button as a header to listview.
With Relative layout you can place the button at the top or button and relative tot eh button you can place your listview.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:background="@android:color/black"
android:layout_height="fill_parent" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
<ListView
android:id="@+id/listView1"
android:layout_above="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
| {
"pile_set_name": "StackExchange"
} |
Q:
Close Google Map directions in ionic
I want to show directions from my current location to an address in my app.
I can successfully open the directions by using:
<a href="http://maps.google.com/?saddr=Current%20Location&daddr={{location.lat}},{{location.lng}}">Get directions</a>
But once open I cannot return to my app. Is there a way to close the map again?
*note I appreciate this will only work correctly on iOS, I will handle android separately.
A:
you should be able to do it with comgooglemaps-x-callback:
https://developers.google.com/maps/documentation/ios/urlscheme#specify_a_callback_url
this example opens Google Maps on iOS with a call back to chrome:
comgooglemapsurl://maps.google.com/maps?f=d&daddr=Tokyo+Tower,+Tokyo,+Japan&sll=35.6586,139.7454&sspn=0.2,0.1&nav=1&x-source=Chrome&x-success=googlechrome://?resume=true
| {
"pile_set_name": "StackExchange"
} |
Q:
Sifting Property of Convolution
This is going to be a dumb question, but I can't figure it out, so here goes
$ f(t)\quad \bigotimes \quad \delta \quad (t\quad -\quad { t }_{ o }) $ = $\int { f(\tau )\delta (t\quad -\quad { t }_{ o }\quad -\quad \tau ) } \quad =\quad f(t\quad-\quad { t }_{ o })$
but when I try to do the convolution integral, I get
$ \int { f(\tau) \delta (t\quad -\quad (\tau \quad -\quad { t }_{ o }) } \quad d\tau $
which is not quite the same thing. What's my mistake?
A:
Typically a convolution is of the form:
$$ (f * g)(t) = \int f(\tau)g(t - \tau) d\tau $$
In your case, the function $g(t) = \delta (t - t_0)$. We then get
$$ (f * g)(t) = \int f(\tau) \delta((t - \tau) - t_0) d\tau = \int f(\tau) \delta(t - t_0 - \tau) d \tau$$
Using the fact that $g(t - \tau) = \delta((t - \tau) - t_0)$
Of course, the right hand term using properties of the $\delta$ function can be evaluated to $f(t - t_0)$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Generate and Send CSV file in attachment with symfony
I need to send CSV file to every user with their transaction detail while run cron in symfony
My code is as below to generate csv data and send in email
array of user :
$array = array('name','ticket','history','date','flag','created by','transition');
$f = fopen('php://temp', 'w');
$line = $array;
fputcsv($f, $line, ',');
rewind($f);
$stream_get_contents = stream_get_contents($f);
$sentmail = $this->sendEmail($stream_get_contents);
if($sentmail){
return true;
}else{
return false;
}
fclose($f);
unset($f);
public function sendEmail($csvData){
UserId='1';
$em = $this->getContainer()->get('doctrine')->getManager();
$getstaffuser = $em->getRepository('AdminBundle:User')->find($UserId);
if ($getstaffuser) {
if ($getstaffuser->getEmail()) {
$objEmailTemplate = $em->getRepository('BviTemplateBundle:Emailtemplate')->findOneBy(array('emailkey' => 'KEYFIND', 'status' => 'Active'));
if (!$objEmailTemplate) {
$output->writeln("\n####### Email template not present #######\n");
$logger->info("\n####### Email template not present #######\n");
return "NoEmailTemplate";
}
$attachment = chunk_split($csvData);
$multipartSep = '-----' . md5(time()) . '-----';
$bodydata = $objEmailTemplate->getBody();
$body = "--$multipartSep\r\n"
. "Content-Type: text/plain; charset=ISO-8859-1; format=flowed\r\n"
. "Content-Transfer-Encoding: 7bit\r\n"
. "\r\n"
. "$bodydata\r\n"
. "--$multipartSep\r\n"
. "Content-Type: text/csv\r\n"
. "Content-Transfer-Encoding: base64\r\n"
. "Content-Disposition: attachment; filename=\"Website-Report-" . date("F-j-Y") . ".csv\"\r\n"
. "\r\n"
. "$attachment\r\n"
. "--$multipartSep--";
$to = $getstaffuser->getEmail();
$subject = $objEmailTemplate->getSubject();
$mail = \Swift_Message::newInstance()
->setSubject($subject)
->setFrom($this->getContainer()->getParameter('fos_user.registration.confirmation.from_email'))
->setTo($to);
$mail->setBody($body)
->setContentType('multipart/mixed');
$issent = $this->getContainer()->get('mailer')->send($mail);
if ($issent) {
return 'EmailSent';
} else {
return 'EmailNotSent';
}
} else {
return "NoEmailAddress";
}
} else {
return "NoUser";
}
}
But it is not working , I receive email as only file with noname as filename in attachment ,which is not csv file and not get body content.
Please any body can help me for this.I will appreciate best answer
A:
Try attaching the files to the message directly with Swift as example:
$mail = \Swift_Message::newInstance()
->setSubject($subject)
->setFrom($from)
->setTo($recipient)
->setBody($bodyText)
->attach(\Swift_Attachment::fromPath($absolutePathOfTheAttachedFile));
EDIT:
Or you can attach by generated data as example:
->attach(
\Swift_Attachment::newInstance($csvData)
->setFilename('filename.csv')
->setContentType('application/csv')
);
Hope this help
| {
"pile_set_name": "StackExchange"
} |
Q:
Validate inputs in table row with angular
I use this lib to create table on page.
Every row in this table can be edited. So if editMode is on, I show inputs at each column of row. Some of this inputs is required. I want to show red text "Required" or just red border if required field is empty.
But problem - it's simple when I use form. But in my case I can't use forms.
This answer isn't good for me, cause every row must have unique form-name for correct validation.
Example : https://jsfiddle.net/r8d1uq0L/147/
<div ng-repeat="user in users">
<div name="myform-{{user.name}}" ng-form>
<input type="text" ng-model='user.name' required name="field"/>
<span class="error" ng-show="myform.field.$error.required">Too long!</span>
</div>
</div>
<div>
<button ng-click="add()">
Add
</button>
</div>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.users = [{name:"1"}, {name:"2"}];
$scope.add = function(){
$scope.users.push({});
}
});
A:
No need to create a dynamic form name, as ng-repeat does create new child scope on each iteration while drawing template on browser. So just keep name as name="innerForm" and use innerForm.field.$error.required to have validation over it.
<div ng-repeat="user in users">
<div name="innerForm" ng-form>
<input type="text" ng-model='user.name' required name="field"/>
{{myform[$index]}}
<span class="error" ng-show="innerForm.field.$error.required">Too long!</span>
</div>
</div>
Forked Fiddle
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't close AlertDialog using timer, custom view and Xamarin
I want to make a splash screen using AlertDialog.Builder, a custom view and a timer.
I'm using Xamarin.Android - i don't have the 'dismiss' method it seems, i can call 'dispose' but the alertDialog view does not close.
Example code below:
public class SplashDialog
{
private readonly AlertDialog.Builder _alert;
private readonly View _view;
public SplashDialog(Context context)
{
_alert = new AlertDialog.Builder(context);
var layoutInflater = (LayoutInflater)context.GetSystemService(Context.LayoutInflaterService);
_view = layoutInflater.Inflate(Resource.Layout.splash, null);
_alert.SetView(_view);
}
public void Show()
{
_alert.Show();
/*
new Thread(() =>
{
Thread.Sleep(3000);
_view.Dispose();
_alert.Dispose();
}).Start();
* */
new Handler().PostDelayed(() =>
{
_view.Dispose();
_alert.Dispose();
}, 3000);
}
}
A:
It is true AlertDialog.Builder doesn't have a Dismiss() method, but when you call _alert.Show(), it returns an AlertDialog instance which has the Dismiss() method. You just need keep the instance somewhere and call it when you need it, like this
private AlertDialog _dialog;
public void Dismiss()
{
_dialog.Dismiss();
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Understanding Page Sizes
The problem states, "Physical memory consists of 64 bytes divided into pages of 16 bytes. Likewise, the virtual address space is also 64 bytes."
It also states, " Each page table will be placed in its own page in the simulated memory [we are using an array of chars to act as our physical memory] array."
Lastly, there are only going to be a maximum of 4 processes running at once, therefor four page tables will be needed.
What I don't understand is that if the physical memory is only 64 bytes and each page table should take up 16 bytes, wouldn't there be no room left over to store any information about or from the processes?
A:
You are dealing with a totally nonsensical problem. Unfortunately, operating systems text books and professors appear hell-bent to transform the simple into the confusing for computer science.
If the virtual address is space is 64 bytes and a page is 16 bytes then there are only 4 pages in the address space (and in the physical address space). Thus you only need 2 bits in each page table entry (under such an unrealistic scenario). And at most one byte for the page table.
This kind of problem leads to many misconceptions. For example, the page table does not need to cover the entire range of the virtual address space.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't seem to get the variable. Keep undefined
I recently started Node.js development and am still consider a noob.
const publicIp = require('public-ip');
publicIp.v4().then(ip => {
console.log(ip);
});
As you can see on the code above I'm actually looking to get public IP.
However, I have totally no idea how do I get the variable of IP out so I can use it. Should you have a similar post, do not hesitate to close and redirect me.
A:
Node is a single threaded framework. What you have there is an asynchronous function. So in short, you cant "bring" the variable out of the function. You CAN however, call your next function and pass the ip variable to it. For Example:
const publicIp = require('public-ip');
publicIp.v4().then(ip => {
myIPFunction(ip);
});
function myIPFunction(ip){
//Do something with your IP here
}
Your IP value is originally presented in whats called a "Callback". Again, because node is a single threaded framework, it doesnt like to wait on process calls to finish. So rather that hold up the rest of the thread, it allows for these callbacks to take place. But that also means you cant define or reference a variable that doesnt exist yet. So having something like
const publicIp = require('public-ip');
var myIP;
publicIp.v4().then(ip => {
myIP = ip;
});
Console.log(myIP);
Wouldnt work because that "ip" variable doesnt exist yet, and therefor hasnt populated the myIP field.
You can read up more about it with these articles
https://nemethgergely.com/async-function-best-practices/
https://medium.com/@thejasonfile/how-node-and-javascript-handle-asynchronous-functions-7feb9fc8a610
| {
"pile_set_name": "StackExchange"
} |
Q:
Why sorting an ascending array (1~100,000) with std::sort() is faster than just using for loop 100,000 times
I know that std::sort has a very high performance, as far as I know it uses Introsort (quickSort+insertionSort+heapSort), but in my tests I found that: "sorting an ascending array (1~99999) with std::sort() is faster than just using for loops 100,000 times". Although std::sort is fast, at least it needs to traverse the entire array. I think this is not possible (std::sort is faster than just for loops with the same number of loops and array lengths). I am very confused, who can tell me what is the principle.
It's hard to understand only in MacOS, I also tested it in Linux (Centos 7.6) and the results are expected.I want to know what Mac and Xcode did to it.
Environment:
MacBook Pro (MacOS Mojave 10.14.6), Xcode
X86_64(Centos7.6), clang++
Test Code:
#include <iostream>
#include <sys/time.h>
#define LENGTH 100000
int * order_arr(int lo, int hi, int reverse) {
int *arr=(int *)malloc(hi<<2);
if (reverse==0) {
for (int i = lo; i < hi; ++i) {
arr[i]=i;
}
return arr;
}else{
for (int i = lo; i < hi; ++i) {
arr[i]=hi-1-i;
}
return arr;
}
}
int main(int argc, const char * argv[]) {
// ---- Create an ascending array: 0~99999
int * order_array = order_arr(0, LENGTH, 0);
//------------------------------------------------------------------
timeval starttime,endtime;
gettimeofday(&starttime,0);
//----------------------------------------------------------------------start_time
// ---- STL sort
// std::sort(order_array, order_array+LENGTH);
// ---- Only for loop 100000 times
// for (int i = 0; i < LENGTH; ++i) ;
//----------------------------------------------------------------------end_time
gettimeofday(&endtime,0);
double timeuse = 1000000*(endtime.tv_sec - starttime.tv_sec) + endtime.tv_usec - starttime.tv_usec;
std::cout<< (timeuse/=1000000) <<std::endl;
return 0;
}
Running results:
MacOS(Xcode):Unreasonable, with or without optimization, std::sort() sorts the array, this time should not be less than only for loop(without optimization 0.000203 s).
optimization: clang++ test.cpp -std=c++11 -o -O3 test
for (int i=0; i<LENGTH; ++i) ; : 0 s
std::sort(order_array, order_array+LENGTH);:0.000118 s
No optimization:clang++ test.cpp -std=c++11 -o test
for (int i=0; i<LENGTH; ++i) ; : 0.000203 s
std::sort(order_array, order_array+LENGTH);:0.000123 s
Centos7.6(g++):reasonable
optimization:clang++ test.cpp -std=c++11 -o -O3 test
for (int i=0; i<LENGTH; ++i) ; :0 s
std::sort(order_array, order_array+LENGTH);:0.001654 s
No optimization:clang++ test.cpp -std=c++11 -o -O3 test
for (int i=0; i<LENGTH; ++i) ; :0.0002745 s
std::sort(order_array, order_array+LENGTH);:0.002354 s
A:
Here is a possible explanation:
You do not use the contents of the sorted array. clang expands the initialization and the template code inline and can determine that you are discarding the array, so it does not even generate the code to sort it, resulting in faster time than the alternative where it does not discard the explicit empty loop.
Try and make main() return the first element of the array to see if it makes a difference.
With your updated question, there seems to be no real issue:
the timings for optimized builds are consistent, with no time spent in the empty loop and a short time spent sorting the already sorted array.
the timings for the unoptimized builds are essentially irrelevant as the core of the template code might still be optimized while the simple loop is compiled into naive inefficient code.
You seem surprised by the performance of std::sort() on an already sorted array on MacOS. It is possible that sorting is very efficient there on an already sorted array, both in increasing and decreasing order. An initial scan is used to split the array in chunks. With your dataset, the initial scan quickly yields a single chunk that is left as is or is simply reversed.
You can try and analyze the template code, which is available on both platforms either directly in the include files or in the open source libraries.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does a 100 Hour Inspection Start Over Every Annual?
If an airplane receives a 100 hour at 350 hours and has an annual at 400 hours, does the next 100 hour inspection need to take place at 450 hours or 500 hours?
A:
The annual will reset the 100 hours.
See 91.409
(b) Except as provided in paragraph (c) of this section, no person may operate an aircraft carrying any person (other than a crewmember) for hire, and no person may give flight instruction for hire in an aircraft which that person provides, unless within the preceding 100 hours of time in service the aircraft has received an annual or 100-hour inspection and been approved for return to service in accordance with part 43 of this chapter or has received an inspection for the issuance of an airworthiness certificate in accordance with part 21 of this chapter. The 100-hour limitation may be exceeded by not more than 10 hours while en route to reach a place where the inspection can be done. The excess time used to reach a place where the inspection can be done must be included in computing the next 100 hours of time in service.
| {
"pile_set_name": "StackExchange"
} |
Q:
Custom JPanel causing rendering problems in second custom JPanel
Bit of an odd one here. I have two classes extending from JPanel, overriding paintComponent in both. One implements Runnable (for animation purposes).
However, when used together with the Runnable one on top, I get the wonderful "paint a copy of everything the mouse points at" in the background of the Runnable instance. See screenshots below:
The only difference between the two is me using JPanel in the former and a custom JPanel with a background image in the latter. Code for the second JPanel below:
package view.widgets;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class PaintedJPanel extends JPanel {
private static final long serialVersionUID = 1L;
private BufferedImage backgroundImage = null;
public PaintedJPanel() {
super();
}
public PaintedJPanel(File image) {
super();
try {
backgroundImage = ImageIO.read(image);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
if(null != backgroundImage) {
g2d.drawImage(backgroundImage, 0, 0, null);
}
}
public BufferedImage getBackgroundImage() {
return backgroundImage;
}
public void setBackgroundImage(BufferedImage backgroundImage) {
this.backgroundImage = backgroundImage;
}
}
EDIT: editing in details because the Enter key shouldn't submit the question when I'm adding tags.
FINISHED EDITING @ 13:38.
A:
Ah, your paintComponent method is missing the super's call. Change
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
if(null != backgroundImage) {
g2d.drawImage(backgroundImage, 0, 0, null);
}
}
to
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
if(null != backgroundImage) {
g2d.drawImage(backgroundImage, 0, 0, null);
}
}
As noted in my comments to your question (before seeing the code), without calling super, you're breaking the painting chain, possibly resulting in side effects with child component rendering.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to update ffmpeg sequence header?
I use the ffmpeg to stream the rtmp packets. Now, i need to change the bitrate dynamically , so is there any way to update the sequence header ?
A:
The bitrate is not encoded into the sequence header. Hence no need to update it when changing bitrates.
| {
"pile_set_name": "StackExchange"
} |
Q:
Map documents to different entities
I have a problem with designing my database.
I have a table which contains documents with the following table-structure:
[Documents]
Id [int]
FileName [varchar]
FileFormat [varchar]
FileContent [image]
In my program: each document can be standalone (without any relationship to an entity) or with an relation to an object either of type Customer or Employee (some more are probably coming soon)
Each entity has an Id in the database. For example the Employee-Table looks like:
[Employee]
Id [int]
Fk_NameId [int]
Fk_AddressId [int]
Fk_ContactId [int]
My idea is to create a table for the connection of an entity and an document. I thought about something like:
[DocumentConnection]
DocumentId [int]
EntityId [int]
Entity [varchar]
The entity-column in the DocumentConnection-Table contains the table-name of the relation.
In the example of an entity of type Employee this column would contain "Employee".
In my application then I build the select-statement for the document by reading the entity-string from the database.
I'm not sure if this is a good way to do this.
A:
I think it would be a much better design to have an EmployeeDocument table, CustomerDocument table, etc.
That will allow you to use foreign keys to the entity tables, which would not be possible in your proposed design. In your design, you would be able to put anything in the entity and entityId columns and it would not be enforceable via foreign key relationship that it actually relates to an existing entity.
The only reason I can see for using your DocumentConnection table would be if your application needed to dynamically create new types of relationships. I assume that isn't the case since you said each type of entity will have its own table.
| {
"pile_set_name": "StackExchange"
} |
Q:
Obtaining remainder using single aarch64 instruction?
I am writing some assembly code for ARM8 (aarch64). I want to do a division and use the remainder obtained for further calculations. In x86 when I use
'div', and I know my remainder is kept in RDX. My question is - is there an equivalent to that in the aarch64 instruction set? I know 'udiv' and 'sdiv' do unsigned and signed divisions and gets me the quotient. Is there a single instruction which would give me remainder? (I want % modulo operator in c). I understand I can obtain it using algebra, just wanted to confirm I am not missing out on a simpler method.
A:
Barring constant power-of-two divisors which can be optimised down to an and, there is no instruction that will calculate the remainder of a division. You can, however do it pretty neatly in two:
// input: x0=dividend, x1=divisor
udiv x2, x0, x1
msub x3, x2, x1, x0
// result: x2=quotient, x3=remainder
| {
"pile_set_name": "StackExchange"
} |
Q:
How to deploy Asp.Net Core apps on Azure Service Fabric using subpaths sharing same port on the cluster
The Service Fabric samples like wordcount the web app listen on a port in a subpath like this:
http://localhost:8081/wordcount
The code for this configuration is: (See the file on GitHub https://github.com/Azure-Samples/service-fabric-dotnet-getting-started/blob/master/Services/WordCount/WordCount.WebService/WordCountWebService.cs)
protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
{
return new[]
{
new ServiceInstanceListener(initParams => new OwinCommunicationListener("wordcount", new Startup(), initParams))
};
}
With this configuration we can deploy other web apps on the same cluster using the same port (8081)
http://localhost:8081/wordcount
http://localhost:8081/app1
http://localhost:8081/app2
And so on.
But the Asp.Net Core project template is different and I don't know how to add the subpath on listener configuration.
The code below is what we have in the project template (Program.cs class WebHostingService):
protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
{
return new[] { new ServiceInstanceListener(_ => this) };
}
Task<string> ICommunicationListener.OpenAsync(CancellationToken cancellationToken)
{
var endpoint = FabricRuntime.GetActivationContext().GetEndpoint(_endpointName);
string serverUrl = $"{endpoint.Protocol}://{FabricRuntime.GetNodeContext().IPAddressOrFQDN}:{endpoint.Port}";
_webHost = new WebHostBuilder().UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.UseUrls(serverUrl)
.Build();
_webHost.Start();
return Task.FromResult(serverUrl);
}
The semantic is a bit different, but all ends up in the same point.
The problems is that even I add the subpath at the end of serverUrl it does't work and the web apps always responds on the root http://localhost:8081/
See how I've tried in the code snippet below:
string serverUrl = $"{endpoint.Protocol}://{FabricRuntime.GetNodeContext().IPAddressOrFQDN}:{endpoint.Port}/app1";
How to achieve the same result as "classic" web app using asp.net core?
The goal is to publish on azure on port 80 to let users with a better experience like:
http://mywebsite.com/app1
http://mywebsite.com/app2
Thank you a lot!
A:
As @Vaclav said is necessary to change UseKestrel by UseWebListener.
But the problem is that WebListener binding to the address is different.
Look this thread to more details https://github.com/aspnet/Hosting/issues/749
Is necessary to use + instead of localhost or other machine names on the serverUrl.
So, change de template code from:
Task<string> ICommunicationListener.OpenAsync(CancellationToken cancellationToken)
{
var endpoint = FabricRuntime.GetActivationContext().GetEndpoint(_endpointName);
string serverUrl = $"{endpoint.Protocol}://{FabricRuntime.GetNodeContext().IPAddressOrFQDN}:{endpoint.Port}/service1";
_webHost = new WebHostBuilder().UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.UseUrls(serverUrl)
.Build();
_webHost.Start();
return Task.FromResult(serverUrl);
}
To
Task<string> ICommunicationListener.OpenAsync(CancellationToken cancellationToken)
{
var endpoint = FabricRuntime.GetActivationContext().GetEndpoint(_endpointName);
string serverUrl = $"{endpoint.Protocol}://+:{endpoint.Port}/service1";
_webHost = new WebHostBuilder().UseWebListener()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.UseUrls(serverUrl)
.Build();
_webHost.Start();
return Task.FromResult(serverUrl);
}
And it workd very well.
A:
Kestrel doesn't support URL prefixes or port sharing between multiple applications. You have to use WebListener instead:
using Microsoft.AspNetCore.Hosting
...
_webHost = new WebHostBuilder().UseWebListener()
| {
"pile_set_name": "StackExchange"
} |
Q:
Generics in Kotlin with extends
I trying to porting java project to kotlin and have some problems with it. I have some MVP structure in java using generics
interface View<P extends Presenter> {}
interface Presenter<V extends View> {}
interface BaseView<P extends Presenter> extends View<P> {}
class BaseActivity<P extends Presenter> extends AppCompatActivity implements BaseView<P> {}
At first two classes I have error from IDE
interface Presenter<V : View<*>> {}
interface View<P : Presenter<*>> {}
my error is
*this type parameter violates the finite bound restriction*
No any problem with Java code
A:
I suppose this is not allowed in Kotlin.
From the Kotlin spec:
The following pair of declarations is invalid, because there are edges
T → S and S → T, forming a cycle:
interface B<T : C<*>>
interface C<S : B<*>>
The reason stated as:
In its fully expanded form this bound would be infinite. The purpose
of this rule is to avoid such infinite types, and type checking
difficulties associated with them.
In your case, it is V -> P and P -> V forms a cycle.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to weigh my luggage before going to the Airport
Is there any trick to find out if your luggage is in the limit of weigh allowed by the airline before going to the Airport ?
My luggage is always overweight and I always have to pay extra dollars to the airline to let it through because I only find it out once they measure it.
it merits mentioning that I have a small scale at home and it always shows the weight of luggage in the limits, but as soon as the Airline people measure it, its way over the limit.
P.S: Its the large luggage (23KG one) I am talking about, not the cabin luggage (7KG)
A:
To test your scale and it's accurracy, which might just be bad for low weights, measure yourself with and without the luggage and calculate the difference (also works a treat for measuring a dog, which you can't put on a scale by itself).
Apart from that I'd say measuring with a scale at home is the most reasonable way. Either you get to know the error/offset of your scale, or you could get a more accurate one.
| {
"pile_set_name": "StackExchange"
} |
Q:
Issue with Redis managing Laravel Queues
I am using Laravel forge with Redis as the queue driver.
I have updated the code for my application to send push notifications a few times over, but the notifications sent are as in the old code.
Changing the queue driver to database, sends the notifications as per the latest updates. However when I switched it back to Redis, it still shows old version of the notification.
I have done "FLUSHALL" via redis-cli, but it didn't fix it.
Also I use Laravel Horizon to manage queues.
How I can fix this? Thanks in advance.
Edit: Other thing I noticed was all code driven dispatches were queued on Redis. I have listed the solution in the answer in the hopes it would help someone else.
A:
What I received from Forge support:
Hello,
There might be a worker that's stuck you can try and run php artisan
horizon:purge which should kill all rogue worker processes, and then
restart the daemon. It's advised to run the purge command in your
deployment script to make sure all stale processes are killed.
-- Mohamed Said [email protected]
However this how I got it sorted:
php artisan horizon:terminate
php artisan queue:restart
And then the code was working properly
| {
"pile_set_name": "StackExchange"
} |
Q:
Stop Propagation on Input Click
I have an html table, and when a user clicks a table row, the row's checkbox is checked, and some other functionality occurs. When a user clicks on a select or input, I would like to stop the propagation so the checkbox does not change. I have demonstrated the functionality I am looking for in this JSFiddle:
http://jsfiddle.net/ehf7pc3f/6/
On my development site, when a user clicks a select, the checkbox is changed (as intended), but if a user clicks an input, the checkbox does not change. I have this code to stop the checkbox from changing:
$("select").click(function (e) {
e.stopPropagation();
});
$("input").click(function (e) {
e.stopPropagation();
});
Does anyone have an idea as to why the select click works, but the input click does not?
Update*
JSFiddle: http://jsfiddle.net/ehf7pc3f/8/
I have added a new JSFiddle that fires an alert when the input is clicked and an alert when a row is clicked. In the fiddle, if I click the input, only the input alert fires. If I do this same test on my development site, only the row alert fires.
Here's the actual code on my development site:
<table class="full-width row-table" style="table-layout:fixed;">
<tr style="background:none;" class="no-hover row">
<td class="no-padding" style="width:16px;"><input class="check-box" style="margin:2px 0px;" type="checkbox" /></td>
<td class="no-padding" style="width:6px;"><span class="arrow2" style="margin:6px 0px 0px 0px;"></span></td>
<td style="width:94px;">
<span class="contact-label">Owner <br /> </span>
<select class="contact-drop-down hidden">
<option value="Owner">Owner</option>
<option value="Applicant">Applicant</option>
<option value="Contractor">Contractor</option>
</select>
</td>
<td style="width:95px;">
<p class="title-label">Owner</p>
</td>
<td style="width:119px;">
<p class="name-label">Michael Douglas</p>
</td>
</tr>
</table>
A:
Use event.preventDefault().
The event.stopPropagation() stops the event from bubbling up the parent elements in the DOM (or down if you're listening during capture phase). While event.preventDefault() stops default behaviour by the browser.
Further reading:
https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault
https://developer.mozilla.org/en-US/docs/Web/API/event.stopPropagation
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there any way to mask or encrypt a number in chat app in Android?
I created a chat app inside my application. In the chat application (SMSActivity) I have the code
editText.setText(phoneNo);
Is there any way to mask that number so the user sending the message doesn't see it.
A:
Set android:inputType="textPassword" on the EditText.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using COUNTIFS for a series of values at once
Working a step higher then COUNTIFS, I appose a challenge to write a formula without VBA code. The basic data is combined from 1000s of rows with:
Column A: rows with values from 1 to 3
Column B: rows with values from 1 to 250.
For this purpose lets say, we are looking at all cells of value "1" in column A, that suit value "5" in column B. To find all matches, we'd use COUNTIFS command.
1 1
2 5
1 5
1 7
1 10
3 45
2 12
1 2
2 1
=COUNTIFS(A1:A9;1;B1:B9;5)
The answer here is 1.
Next thing, the "5" in column B belongs to a group, e.g. group from 1 to 9. What would the best way be, to count all the matches in this example, so that for all "1"'s in column A, we'd have to find all matches with values from 1 to 9 in column B?! In the upper example that would result in "4". The obvious solution is with a series of IF commands, but that's unefficient and it easy to make a mistake, that get's easily overseen.
=COUNTIFS(A1:A9;1;B1:B9;"<="&9)
Works only as the upper limit. If I give the third criteria range and condition as ">="&1 it does not work - returns 0.
Gasper
A:
Where the data is in A1:B9, using a lookup table in D1:E10 with letters A-J in column D and numbers 0 to 9 in column E and the following formula in B11 referencing letters entered in A11 and A12:
=COUNTIFS(A1:A9,1,B1:B9,">="&VLOOKUP(A11,$D$1:$E$10,2,FALSE),B1:B9,"<="&VLOOKUP(A12,$D$1:$E$10,2,FALSE))
works, changing the letters in A11 and A12 gives the correct count according to what they correspond to in the looku in D1:E10.
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating index layer for multiple maps in ArcGIS Desktop?
I am trying to create an index layer of just the area within the Orange lines. I am having difficulty creating this layer due to it not being a simple box area.
The goal is to create a index layer, with grids, so that the Data Driven Pages would be used to generate it as a mapbook for the response area for my firehouse.
Below is an image of what I am speaking about.
Any ideas?
I am using ArcGIS Desktop.
A:
You have a couple of options here depending on some choices you make up front as far as requirements go. Both fishnet and the grid index tools can be constrained to only cover the area of a shape such as your orange outline. Both tools give you some options the other does not. For example grid index controls overlap through DDP and a percentage, whereas fishnet you have to manually edit or specify an overlap in units.
Do you want north to remain straight up on the map page? If not, fishnet allows you to rotate the grid so if you aligned it with your western edge the grid cells would have less 'wasted' space. However I do not recommend this for your application - whenever north isn't up or people are used to looking at things in a certain orientation, altering that orientation introduces a 'map reader orientation lag' as they get their bearings. Not ideal for emergency response.
You could use either tool to generate a grid that covers everything and then delete the cells that don't have any of your required area in them, similar to the grid you posted in a previous question. You would just have to redo the grid labels to be sequential afterward. You could also then shift grid cells that weren't quite working - for example if that narrow (highway?) corridor at the bottom was falling on the boundary of two cells, just shift one over so it's down the middle and delete the other.
You could also draw your own custom polygons to serve as an index - as PolyGeo pointed out, it doesn't have to be rectangular or even a grid. Any set of boundary polygons can serve as an index, though you have to keep scale in mind. There is a Strip Index tool designed for following linear features, but the concept can be adapted to any shape.
My (overview) workflow for this situation is:
Determine window size (based on page size and layout).
Determine desired map scale.
Multiply scale by size to determine grid cell size.
Run Create Fishnet (Data Management) Tool
Adjust grid cells for desired overlap (strips that show on adjacent pages).
That works for a regular grid. If I'm doing a strip, or detail areas, I follow Steps 1-3 to create a template polygon (sort of windowframe) I can move around the map and copy to create specific area pages. You can do a different template polygon for each scale, allowing multiple uniform scales in the same index layer. You can also adjust your window boundaries for odd overlaps as needed (just be sure to keep at least one unmodified as your template).
Below is an example image from the index page of the most recent mapbook project I worked on. There are two page series (all the same pagesize) - one is an overall grid that covers the entire area at a smaller scale (not shown), the other is a detail series that provides pages at a couple of different larger scales depending on how much detail was required. Each letter is a page; the black lines are roads with mileage marker numbers. I recommend as few scales as possible for this approach, though it depends on if you really care about accurate scale and how consistent it needs to be.
| {
"pile_set_name": "StackExchange"
} |
Q:
Count the number of arrangements of the letters in PHYSICS.
I thought it would be $7!$, but my book gives $7c2 * 5!$ as the answer. I don't understand why, considering we have $8!$ ways of arranging the letters in PHYSICAL.
A:
I think I understand now. You have 2 S's in PHYSICS, so you need to choose a combination of them first from the two letters and then do a permutation of the remaining 5 letters.
| {
"pile_set_name": "StackExchange"
} |
Q:
Convergence of sequence of functions under metric iff sequence converges uniformly.
Let $C[0,\infty)$ be the space of continuous functions on $[0,\infty)$. The "sup" norm on this space is too strong, as it eliminates all functions which are unbounded at infinity. Instead, we use the follow metric $\rho_\infty$. Let $s_n(f,g)=\sup_{x\in[0,n]}|f(x)-g(x)|$ and $\rho_n(f,g)=\frac{s_n(f,g)}{1+s_n(f,g)}$. Then,
$$
\rho_\infty(f,g)=\sum_{n=1}^\infty \frac{1}{2^n}\rho_n(f,g).
$$
a) Prove that $\rho_\infty$ is a metric.
b) Prove that $f_n \rightarrow f$ under $\rho_\infty$ if and only if functions $\{f_n\}$ converge uniformly to $f$ on every finite interval.
c) Prove that $(C[0,\infty),\rho_\infty)$ is a complete space.
So far I have done a) without much trouble but I am struggling on b) and c). Here's my work so far for b)
Work
"$\Rightarrow$"Let $f_n \rightarrow f$ under $\rho_\infty$ then $\forall \epsilon > 0 \exists \eta \in \mathbb{N}:\forall n \geq \eta$ we have $\rho_\infty(f_n,f)=\sum_{k=1}^\infty\frac{1}{2^k}\rho_k(f_n,f) < \epsilon$. Assume $\{f_n\}$ does not converge uniformly to $f$ on some interval $[0,m]$. Then $\exists \delta > 0$ such that $s_m(f_n,f)=\sup_{x\in [0,m]}|f_n(x)-f(x)| > \delta$. This holds for all $r \geq m$.
This is where I am stuck, I am trying to find a relationship for $\rho_m$ and then with $\rho_\infty$ but nothing I can come with sticks. I would gladly appreciate any help.
Thank you.
A:
For $f,g$ fixed, $s_n(f,g)$ is increasing with $n$ and $g : x \mapsto \frac{x}{1+x}$ strictly increasing continuously from $0$ to $1$ as $x$ increases from $0$ to $\infty$. Therefore for $N \in \mathbb N$
$$\begin{aligned}
\rho_\infty(f,g)=\sum_{k=1}^\infty \frac{1}{2^k}\rho_k(f,g) &\ge \frac{1}{2^{N+1}}g(s_{N+1}(f,g))+\sum_{k=1}^N \frac{1}{2^k}\rho_k(f,g)\\
&\ge \frac{1}{2^{N+1}}g(s_{N+1}(f,g))
\end{aligned}$$
Taking a finite interval $I$, it exists $N \in \mathbb N$ such that $I \subset [0,N]$. Applying previous inequality with $f,f_n$ we get
$$0 \le \frac{1}{2^{N+1}}g(s_{N+1}(f,f_n)) \le \rho_\infty(f,f_n).$$
$\lim\limits_{n \to \infty} \rho_\infty(f,f_n)=0$ implies $\lim\limits_{n \to \infty} g(s_{N+1}(f,f_n))=0$ and $\lim\limits_{n \to \infty} s_{N+1}(f,f_n)=0$ with what was said about $g$ above. Allowing to prove b). c) follows from b).
| {
"pile_set_name": "StackExchange"
} |
Q:
Verifing if text already exists
I have a sql table that saves a word and I need to check if that word already exists and I so, I should get a message saying that word already exists.
Is it possible? If so how should I do it?
I will leave it down below myccode to add the word for the sql, but if you need something else I will provide you without any problem.
string conn = ConfigurationManager.ConnectionStrings["test"].ConnectionString;
using (SqlConnection sqlConn = new SqlConnection(conn))
{
sqlConn.Open();
string sqlQuery = @"INSERT INTO testetiposdestados(CDU_ESTADOS) VALUES(@estados)";
SqlCommand SQLcm = new SqlCommand();
SQLcm.Connection = sqlConn;
SQLcm.CommandText = sqlQuery;
SQLcm.CommandType = CommandType.Text;
SQLcm.Parameters.AddWithValue("@estados", textBox1.Text);
SQLcm.ExecuteNonQuery();
sqlConn.Close();
}
I'm using c#
A:
You can use IF NOT EXIST statment like so
IF NOT EXISTS (SELECT * FROM testetiposdestados
WHERE CDU_ESTADOS = @estados)
BEGIN
INSERT INTO testetiposdestados(CDU_ESTADOS) VALUES(@estados)
END
Your query will become:
string sqlQuery =
@"IF NOT EXISTS(SELECT *
FROM testetiposdestados
WHERE CDU_ESTADOS = @estados)
BEGIN
INSERT INTO testetiposdestados(CDU_ESTADOS)
VALUES (@estados)
END";
If it inserted successfully it means it was not present in the table already.
| {
"pile_set_name": "StackExchange"
} |
Q:
Scout eclipse form template
I see in the tree representing my applications in the Scout Explorer view that I have two subfolders under the template node :
Forms
Form Fields
I know how to add form fields and its pretty simple, but I don't know how to create a form template and I can't find it on internet.
Marko
EDIT :
Now I figure out how to add form to From template folder. You just need to add abstract tag and then you can create new form from this template.
Now I need to change default main box class from : AbstractGroupBox to AbstractMyGroupBox.
To be understand, what I need is to set somehow inside AbstractMyForm, that all form that come from AbstractMyForm template have instead :
public class TestFromForm extends AbstractMyForm
...
@Order(10.0)
@ClassId("e23ebc80-d948-4e23-aff6-ae49d3278331")
public class MainBox extends AbstractGroupBox {
@Order(10.0)
@ClassId("571bc88f-67ee-454d-b6ce-9616bc43bf74")
public class OkButton extends AbstractOkButton {
}
@Order(20.0)
@ClassId("66969857-002f-4689-981e-20ab60bbaf0e")
public class CancelButton extends AbstractCancelButton {
}
}
have this :
@Order(10.0)
@ClassId("e23ebc80-d948-4e23-aff6-ae49d3278331")
public class MainBox extends AbstractMyGroupBox {
}
A:
You are right; there isn't any support in the Scout Perspective to create a form template. You need to use the Java tooling from the IDE.
Form template
A form template is nothing more than an Abstract class extending org.eclipse.scout.rt.client.ui.form.AbstractForm. Your template can be located where you want (where it makes sense, depending on your code organization). Possible package: <your_app>.client.ui.template.form.
This is a minimal example:
import org.eclipse.scout.commons.exception.ProcessingException;
import org.eclipse.scout.rt.client.ui.form.AbstractForm;
public abstract class AbstractMyForm extends AbstractForm {
/**
* @throws ProcessingException
*/
public AbstractMyForm() throws ProcessingException {
super();
}
}
Form and Mainbox
Be aware that a Form (used with a template or not) has only one MainBox (a root group box containing a tree of child fields). It is loaded during Form initialization. (see extended answer based on an example).
From the implementation of the private method AbstractForm.getConfiguredMainBox() I can deduce that only the first inner class implementing IGroupBox is selected.
Therefore Form Templates are suitable to mutualize logic on at form level. Sometime also some form handlers or tool buttons.
If the idea is to mutualize common fields between multiple forms, a possibility is to use a field template for the main box itself:
@Order(10.0)
public class MainBox extends AbstractMyTemplateGroupBox {
//…
}
Without knowing more on the use case, it is hard to tell what you should do.
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL Server compare numbers after decimal point
We have some numbers values in SQL server database such like 7.11 and 7.6.
Actually 7.11 is later version than 7.6, when using "max(vernum)" in SQL server, it will return 7.6. How can we let SQL server return 7.11?
Thanks
A:
You should go read the official docs .
By default, SQL Server uses rounding when converting a number to a
decimal or numeric value with a lower precision and scale
Try This
SELECT MAX(Version) OVER(ORDER BY CAST(PARSENAME(version, 2) AS INT) DESC,CAST(PARSENAME(version, 1) AS INT) DESC) Version, Version
FROM yourTable
FIDDLE DEMO
| {
"pile_set_name": "StackExchange"
} |
Q:
Making my toggle button work with Bootstrap
When I resize my browser and put it in mobile mode the button appears just fine. However, when i click on the button it does not drop the "home tab" which is what im trying to have drop. I was watching a video on youtube on how to do this but it was from 2013 and I think that is the problem. Here is my HTML:
<!DOCTYPE html>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="Template1css.css">
</head>
<body>
<div class="navbar navbar-default navbar-static-top">
<div class="container">
<div class="navbar-header">
<a href="#" class="navbar-brand">Welcome</a>
<button class="navbar-toggle" data-toggle="collapse" data-target=".navHeaderCollapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse navHeaderCollapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="#">Home</a></li>
</ul>
</div>
</div>
</div>
</body>
</html>
A:
You need to add the latest jQuery CDN before bootstrap js
<!DOCTYPE html>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="Template1css.css">
</head>
<body>
<div class="navbar navbar-default navbar-static-top">
<div class="container">
<div class="navbar-header">
<a href="#" class="navbar-brand">Welcome</a>
<button class="navbar-toggle" data-toggle="collapse" data-target=".navHeaderCollapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse navHeaderCollapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="#">Home</a></li>
</ul>
</div>
</div>
</div>
</body>
</html>
| {
"pile_set_name": "StackExchange"
} |
Q:
Which areas of arithmetic algebraic geometry can be learned as "black boxes" and are there any references where they are treated as such?
In Matthew Emerton's comment on Terry Tao's blog, he speaks about learning etale cohomology or the theory of Neron models as "black boxes". By this he means that you can learn what the theory is about and how to use it, without going into the detailed proofs of why they can be used.
Which theories (e.g. etale cohomology) can be learned as black boxes?
And where would one go (e.g. find lecture notes) to learn something like that?
Notes on something like this would ideally give you an idea of what is going on, give examples, and most importantly illustrate how they would be used to solve problems. I am mainly interested in arithmetic algebraic geometry and algebraic number theory, so I would especially like to know about "black boxes" in this direction, though "black boxes" in other areas might also be worth knowing about.
A:
I find Hodge theory pretty scary stuff with its compact inclusions of Sobolev spaces, pseudodifferential operators and parametrixes for elliptic differential operators. However it is very easy to use the results of Hodge theory as emanating from a black box. I remember how exhilarated I was by the argument that a Hopf surface, homeomorphic to $S^1 \times S^3$, could not be Kähler, and much less projective, just because its first Betti number is $b_1=1$. Whereas by Hodge theory a compact Kähler manifold $X$ has betti numbers $b_q(X)$ which are even whenever $q$ is odd.
A:
I have found Groebner bases to be incredibly useful for testing concrete ideas about varieties, and although I did spend time learning how they work, all I've ever really needed to know is how to interpret the results of a Groebner Basis calculation, and how to choose monomial orders that will produce useful answers. I don't actually know how the most efficient algorithms and their implementations (Fauguère F4 and F5) arrive at an answer---the textbook algorithms are painfully slow for complicated calculations.
| {
"pile_set_name": "StackExchange"
} |
Q:
Followup: "Sorting" colors by distinctiveness
Original Question
If you are given N maximally distant colors (and some associated distance metric), can you come up with a way to sort those colors into some order such that the first M are also reasonably close to being a maximally distinct set?
In other words, given a bunch of distinct colors, come up with an ordering so I can use as many colors as I need starting at the beginning and be reasonably assured that they are all distinct and that nearby colors are also very distinct (e.g., bluish red isn't next to reddish blue).
Randomizing is OK but certainly not optimal.
Clarification: Given some large and visually distinct set of colors (say 256, or 1024), I want to sort them such that when I use the first, say, 16 of them that I get a relatively visually distinct subset of colors. This is equivalent, roughly, to saying I want to sort this list of 1024 so that the closer individual colors are visually, the farther apart they are on the list.
A:
This also sounds to me like some kind of resistance graph where you try to map out the path of least resistance. If you inverse the requirements, path of maximum resistance, it could perhaps be used to produce a set that from the start produces maximum difference as you go, and towards the end starts to go back to values closer to the others.
For instance, here's one way to perhaps do what you want.
Calculate the distance (ref your other post) from each color to all other colors
Sum the distances for each color, this gives you an indication for how far away this color is from all other colors in total
Order the list by distance, going down
This would, it seems, produce a list that starts with the color that is farthest away from all other colors, and then go down, colors towards the end of the list would be closer to other colors in general.
Edit: Reading your reply to my first post, about the spatial subdivision, would not exactly fit the above description, since colors close to other colors would fall to the bottom of the list, but let's say you have a cluster of colors somewhere, at least one of the colors from that cluster would be located near the start of the list, and it would be the one that generally was farthest away from all other colors in total. If that makes sense.
A:
This problem is called color quantization, and has many well known algorithms: http://en.wikipedia.org/wiki/Color_quantization I know people who implemented the octree approach to good effect.
A:
It seems perception is important to you, in that case you might want to consider working with a perceptual color space such as YUV, YCbCr or Lab. Everytime I've used those, they have given me much better results than sRGB alone.
Converting to and from sRGB can be a pain but in your case it could actually make the algorithm simpler and as a bonus it will mostly work for color blinds too!
| {
"pile_set_name": "StackExchange"
} |
Q:
Parsing JSON in photoshop
I've recently found out that you can parse JSON files in photoshop using jamJSON
This is good news, but I've got a couple of stumbling blocks:
For example, this is my JSON file
{
"YEAR" : {
"longname" : "New Year"
}
}
I can access it with
var jsObj = jamJSON.parse (jsonText, true);
alert (jsObj["YEAR"]["longname"]) // New Year
But since each file is going to be different and "YEAR" may be "FRUIT" or "GOLD" in another file. How do I access the data without knowing the first part of the object?
A:
Although the answers are above are correct, I was getting confused between object and arrays (Easily done. I'm an artist, me) and was finally able to access the data using
var jsObj = jamJSON.parse (jsonText, true);
for (var key in jsObj)
{
var obj = jsObj[key];
alert (obj["longname"]);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating a muli-row table in JSF
I need to create a table structured as shown below:
+----+--------+
| ID | Values |
+----+--------+
| 1 | val 1 |
+----+--------+
| | val2 |
+----+--------+
| | val 3 |
+----+--------+
| 2 | val 4 |
+----+--------+
| | val 5 |
+----+--------+
i.e. the first column values may extend over multiple rows.
My JSF object is;
class abc {
int id;
String[] values;
}
A:
I ended up using a PrimeFaces implementation of panelGrid:
<p:panelGrid>
<p:row>
<p:column rowspan="2">Header 1</p:column>
<p:column>attrib 1 1</p:column>
<p:column>arrtib 1 2</p:column>
</p:row>
<p:row>
<p:column>attrib 2 1</p:column>
<p:column>arrtib 2 2</p:column>
</p:row>
</p:panelGrid>
| {
"pile_set_name": "StackExchange"
} |
Q:
How do we describe the molecule of Water (H2O) in English by the way of tradition/science or native/slang in the U.S.?
I don't know how to say the water molecule in English, Just use "Water Molecule" or any other scientific description?
A:
A molecule of water is called a molecule of water in English. If you want to be more scientific, you can say a molecule of H2O. If you want to be very scientific, you can say, an Oxygen atom covalently bonded to two Hydrogen atoms.
A water molecule is your best bet.
| {
"pile_set_name": "StackExchange"
} |
Q:
Log in persists in Postman but does not persist in browser with Angular
I have an API on node.js, with express. This API logs the user in. I use passsport to authenticate it.
I have two routes: / login and / companies. To begin with, the user must log in to the system, he receives the tokens and I log in. After that, he / she must access the route / companies, however, they must be logged in.
To validate if the user is logged in, I use the req.user. Here is the code for user login verification on the route / companies:
exports.list = function (req, res, next) {
console.log(req.user);
if (!req.user) {
return res.status(404).send("Precisa estar logado.");
}
...
Here are my server settings:
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.set('trust proxy', 1) // trust first proxy
app.use(session({
secret: 'MotomcoGroupAjm999MOTOMCO',
resave: false,
saveUninitialized: true,
cookie: { httpOnly: false }
}))
// Flash - Gerenciador de mensagens de resposta do servidor.
app.use(flash());
app.use(pass.initialize());
app.use(pass.session());
When doing tests with Postman, I can access / companies without problems, but when I try to access, after login, by the browser, I fall into (!req.user).
Is this a question of cookies? I have tried to use, when making the request to the server with the Angular, withCredentials, however, without success.
Question: Why is the session being written to the tests with Postman but is not recorded in the browser, when I test with Angular? What am I forgetting to do on the client side?
A:
The problem was with CORS. This is what I did to solve the problem:
var cors = require('cors');
app.use(cors({origin:true,credentials: true}));
And, set the headers:
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Origin, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, X-Response-Time, X-PINGOTHER, X-CSRF-Token,Authorization');
if (req.method === "OPTIONS") {
return res.status(200).end();
} else {
next();
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Disable HTML5 video download?
How can you disable downloading a video in HTML5? I Do not understand this and anyway the question doesn't have a satisfactory answer
A:
Im not really Sure about your question but from what I understand, you want to stop people from downloading your html5 video. To do so you can Either use this method or mine:
make 2 cshtml pages: page and ogvpage (you have tagged your question asp.net). insert this code in page:
var request = UrlData[0];
if(Request.Cookies["allow"] != null){
Response.Redirect(Href("VIDEO PATH", request + ".mp4"));
}
and this in ogvpage:
var request = UrlData[0];
if(Request.Cookies["allow"] != null){
Response.Redirect(Href("VIDEO PATH", request + ".ogv"));
}
page 1 will serve the mp4 video and 2 will serve ogv. open the page you want video on and replace your video element with this:
<video>
<source src="/page/video name without extention" type="video/mp4"/>
<source src="/ogvpage/video name without extention" type="video/ogv>
</video>
and finally put this at the top of your page:
if(Request.Cookies["allow"] == null){
HttpCookie myCookie = new HttpCookie("allow");
myCookie.Value = "true";
myCookie.Expires = DateTime.Now.AddSeconds(5);
Response.Cookies.Add(myCookie);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
When does this integral exist?
I try to learn about Sobolev-spaces defined with tempered distribution.
I would like to understand for what $s\in\mathbb{R}$ does
$$\int (1+|\xi|^2)^s \mathrm d\xi\,, \qquad \xi \in \mathbb{R}^n$$
exist?
I think this could be helpful to understand Sobolev-spaces in this context.
Can anybody help me with this? I am thankful for every help.
A:
You function is continuous everywhere, hence you need to study what happens when $|\xi|\to\infty$. By comparison with $|\xi|^{2s}$ you deduce easily that for $2s+n < 0$ the integral converges and for $2s+n\ge0$ the integral diverges. Polar coordinates help, too.
| {
"pile_set_name": "StackExchange"
} |
Q:
Find match in file, copy results line to other file's line where match occurs as well
I have searched about everywhere and tried out different programming languages but to no avail. (PHP, Shell, SED)
The problem: I have got 2 files. One contains text, the other contains filenames and their locations, one per line. I am trying to search the text file for a specific pattern which occurs in the other file as well and want to add the line containing the match from file 1 to file 2 where the match occurs.
So we have file 1:
Lots of text containing R5-3243567
Continuing on this line where we have X6-6703432
Going further with some W1-7684346
One final line containing U5-1234567
And file 2:
C:\Folder\Subfolder\X6-6703432.jpg
C:\Folder\Subfolder\U5-1234567.jpg
C:\Folder\Subfolder\W1-7684346.jpg
C:\Folder\Subfolder\R5-3243567.jpg
What the script has got to do: find a match in file 2 for /[A-Z][0-9]-[0-9]{7}/ in file 1 and place the full line after the matching line. Like so:
Lots of text containing R5-3243567 C:\Folder\Subfolder\R5-3243567.jpg
Continuing on this line where we have X6-6703432 C:\Folder\Subfolder\X6-6703432.jpg
Going further with some W1-7684346 C:\Folder\Subfolder\W1-7684346.jpg
One final line containing U5-1234567 C:\Folder\Subfolder\U5-1234567.jpg
Final output will be file links but the main problem for me is to get this to work.
I thought about using PHP and using one foreach loop inside the other. This works partially as it includes the match and adds the non-matches for each loop. I keep getting back to a nested foreach loop though.
foreach($file1 as $f1){
foreach($file2 as $f2){
echo $f1 . " " . $f2;
}}
A:
I'm pretty sure that this will do what you want. It is written using bash and relies on a relatively modern grep command. Any linux distro since mid-2001 should be fine. Use it as follows: ./script.sh file2 file1
#! /bin/bash
pats=$1
main=$2
cat $main | while read line
do
mpat=$(echo $line | grep -P -o '[A-Z][0-9]-[0-9]{7}')
tpat=$(grep -P $mpat $pats)
if [[ -n $tpat ]]
then
echo "$line $tpat"
else
echo $line
fi
done
Here's the output I get:
Lots of text containing R5-3243567 C:\Folder\Subfolder\R5-3243567.jpg
Continuing on this line where we have X6-6703432 C:\Folder\Subfolder\X6-6703432.jpg
Going further with some W1-7684346 C:\Folder\Subfolder\W1-7684346.jpg
One final line containing U5-1234567 C:\Folder\Subfolder\U5-1234567.jpg
| {
"pile_set_name": "StackExchange"
} |
Q:
Internet Explorer 8 generates huge traffic to macromedia.com every day - why?
Recently I found that my computer started generating much more traffic than usually while my usage patterns haven't changed.
I used Net Limiter to monitor traffic and found that huge part of that traffic was from Internet Explorer 8.0.6001.18702 and directed to macromedia.com. It constitutes about one third of all my daily traffic and this bothers me.
Why is this traffic there? How do I get rid of it?
A:
Macromedia was the maker of Flash before Adobe bought them, so that's your likely culprit. Is it possible you have something installed to clear you cache that's forcing you to re-download the latest flash update every time you start a new IE session?
| {
"pile_set_name": "StackExchange"
} |
Q:
If $A^3=-E$ then does $A=-E$
$E$ is the identity matrix.
$A$ is a 2 by 2 matrix where $A^3$ is equal to $-E$. Then does $A=-E$
A:
Hint: Take $A=\left[\begin{smallmatrix}\cos\theta&-\sin\theta\\\sin\theta&\cos\theta\end{smallmatrix}\right]$. What is $A^3$? When is it equal to $-\operatorname{Id}$?
| {
"pile_set_name": "StackExchange"
} |
Q:
Implementing an Array Based Memory Pool of Various Sized Structs
I am working on a concurrent data structure that uses a number of small sized temporary objects. A lot of these objects are the same size. So to reduce the strain on the memory allocator I have been using a thread local map to store the objects as <size, list> tuples.
When a thread needs an object, it checks the map for a suitable object before going to the allocator. This works well and has improved performance significantly, however it is prone to the issue where overtime one thread loses its entire pool to other threads, forcing it to allocate new objects. If the application runs for a long period of time, I find a few threads having memory pools way to large.
To solve this I want to add a shared memory pool between the thread local pools and the allocator. Since the number of structs and the size of the structs are constant at compile time, I figure that there should be someway using macros to map each size to an array position. Allowing for a much lighter memory management.
Here is my current solution
#define RC_OBJECT_COUNT 0
#define ADD_RC_OBJECT(object) \
#ifndef RC_MAP_``sizeof(object)''
#define RC_OBJECT_TEMP RC_OBJECT_COUNT \
#undefine RC_OBJECT_COUNT \
#define RC_OBJECT_COUNT RC_OBJECT_TEMP+1 \
#define RC_MAP_``sizeof(object)'' RC_OBJECT_TEMP
#endif
Is there a way to echo the the result of the call to sizeof(object) into the defined variable name? Preferably without a separate configuration script.
A:
I've written code that works kind of like what you are discussing, but I didn't use preprocessor macros at all the way you are trying to do.
My code has a single "object manager", with a small API. Any part of my program that wants to get objects calls an API function, the "register function", that says "I want to request objects with the following characteristics". The register function returns a handle. Then, there is a function GetObject() that takes the handle as an argument, and returns a pointer to an object. When the code is done with the object there is a function ReleaseObject() that takes a pointer to the object.
For each different object there is a linked list that I call the "ready list". The code always inserts and removes from the head of the list (since one uninitialized object is as good as another; they are all the same size). My code is single-threaded so I don't have any locking issues, but for multithreaded I would need to put a lock on each ready list. (But it's very fast to insert or remove at the head of a linked list so no thread would need the lock very long.)
For my purposes, different parts of my program could share objects, so I had a reference count on each object. ReleaseObject() would decrement the reference count, and when it went to zero, would put the object on the appropriate ready list.
The handle returned by GetObject() is really just a pointer to the linked list structure.
In my code, if there is a call to GetObject() and the ready list is empty, then malloc() is called automatically and a new object created and returned. The register function takes a pointer to a function to call to create an object with malloc(), a pointer to a function to free an object with free(), and a pointer to a "sanity check" function (since I like my programs to check themselves at runtime with calls to assert()), and any arguments like size of object.
If multiple parts of my program register that they want the same kind of object, the object manager notices this and just returns a handle to the ready list that was already set up by the first call to register. Now they are sharing objects in a single ready list.
This may sound complicated but it didn't take me long to build and it works very well. If there is no object on the ready list, the object manager knows to just call the function pointer stored in the ready list struct, to get a new object, and then it returns that.
The most common bug I have found in my programs: failure to call ReleaseObject() when done with the object. Then the program has a memory leak and calls malloc() a lot, and on an embedded platform runs out of memory and dies. Usually it's very easy to notice this, and add in an appropriate call to ReleaseObject().
EDIT: (In response to a question in the comments) The object manager keeps an array of different object management struct instances. Each struct stores three function pointers: pointer to a "new" function, a pointer to a "delete" function, a pointer to a "sanity check" function; a handful of values that are passed to the "new" function when it is called (for example, size of a desired buffer); and the head of the linked list of objects. When code calls the "register" function, the object manager checks to see if any spot in this array has identical values from "register" (the 3 function pointers and the handful of values). If the identical values are found, the object manager returns a pointer to that object manager struct instance. If the identical values are not found, the object manager copies those values into the next available struct in the array and returns a pointer to that.
This means that my "register" function is O(N) in the number of different kinds of objects being managed, but for my app there are only about 4 different kinds of objects so I never tried to optimize this. My "get" function is O(1), as it has a pointer right to the correct object manager struct, and removing from the head of a linked list is a constant-time operation.
The array of object manager structs is allocated by malloc() and if additional object types are registered the code can call realloc() to grow the memory.
In my application, I haven't had the need for an "unregister" operation, but if there were one, it would involve freeing all the objects on that ready list, and marking that spot in the object manager array as unused.
My app is an audio processing engine, and it never wants to call malloc() while processing audio because malloc() might decide to re-organize the free blocks list or something and take a while, and the audio playback might glitch. The engine has an "init" phase before starting playback where the code calls the "register" function and all the audio buffers get allocated; then at runtime the buffers just fly off and onto the ready lists. It really works quite well, and I have run it on low-power DSP chips with no problems.
| {
"pile_set_name": "StackExchange"
} |
Q:
Integrate Access report
How can I integrate Reports done in Microsoft Access in my WPF application?
A:
You'll have to define a little bit more what you mean by integration.
You are talking about a desktop application like word or PowerPoint or in this case Access. You can certainly automate or use Access as a com object and have access reports output their results as RFT or likey even better as a PDF document. So, it not clear when you speak of integration is really much centered around how you going to prompt the user for those report paramters and ask the user for filtering etc. So, choices you have range from a simple nightly batch job that runs and creates a bunch of PDF files on the users desktop and then are copied to a server, or perhaps even FTP up to the server.
Perhaps you talking about something a little bit tighter here?
So I'm not really sure if your questions any different than how would you integrate some PDF documents, or PowerPoint presentation, or in this case some Access reports. They are all the same concept and your question not really different then asking how to do this with power point.
However keep in mind that for Access 2010, there is WEB based reporting now. Those web reports actually use behind the scene are fully built around SQL server reporting services. In this case, the data will reside on SharePoint, but the WEB report side of Access are WPF presentation compatible reports since they are web based and run using sql server reporting services (they are RDL reports).
On the other hand if you're not really using Access in this case. You might as well just use the web based SQL server reporting service then. So do keep in mind that the web based reports Access uses for access 2010 is/are based on SQL server reporting services and it's actually creating RDL compatible reports.
However if you're not talking about the web based edition of access available in for 2010, then you're back to any old desktop program like excel are word or PDF documents or in this case Access. So, there's nothing different here about any old desktop program in windows and Access is one of those programs (sans the new weeb stuff for 2010).
So, the approach (or shall I say challenge) to getting that data into your presentation layer is not really a specific question to access alone, but is really much like a asking how can you have the output of your PowerPoint presentation brought into WPF.
You likely be best to have the report's render its output as PDF, or perhaps the XPS document writer is a sutiable output. So, your code take it from that point onwards for printing or display. So if you have the means to display a PDF or XPS doc, now then this would be a possible road to go down.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to detect collisions of two different shapes in c#
I have two different shapes . A rectangle which moves by using the keys up,down,right,left and a circle that is moving in a fixed position ( Up and down the Y axis) . I'm trying the detect the collision that if I move the rectangle into the circle the collision is to be detected and the game to stop . I have tried this code but it doesn't work:
public bool collision()
{
if (PlayerPositionX == EnemyPosX & PlayerPositionY == EnemyPosY )
{
_movementTimer.Stop();
}
if (collision()==true)
{
_movementTimer.Stop();
}
return collision();
}
this is the full code . Does anyone have any idea how to do it?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Timers;
using System.Drawing.Imaging;
using Timer = System.Windows.Forms.Timer;
namespace prot_4
{
public partial class Form1 : Form
{
int PlayerPositionX = 40, PlayerPositionY = 200, width = 40, height = 40; // player
int EnemyWidth = 40, EnemyHeight = 40, EnemyPosX = 100, EnemyPosY = 0, EnemySpeedX = 0, EnemySpeedY = 20; // enemy
int EnemyWidth2 = 40, EnemyHeight2 = 40, EnemyPosX2 = 200, EnemyPosY2 = 400, EnemySpeedX2 = 0, EnemySpeedY2 = 20; // enemy2
int EnemyWidth3 = 40, EnemyHeight3 = 40, EnemyPosX3 = 300, EnemyPosY3 = 0, EnemySpeedX3 = 0, EnemySpeedY3 = 20; // enemy3
int EnemyWidth4 = 40, EnemyHeight4 = 40, EnemyPosX4 = 400, EnemyPosY4 = 400, EnemySpeedX4 = 0, EnemySpeedY4 = 20; // enemy4
int EnemyWidth5 = 40, EnemyHeight5 = 40, EnemyPosX5 = 500, EnemyPosY5 = 0, EnemySpeedX5 = 0, EnemySpeedY5 = 20; // enemy5
int EnemyWidth6 = 40, EnemyHeight6 = 40, EnemyPosX6 = 600, EnemyPosY6 = 400, EnemySpeedX6 = 0, EnemySpeedY6 = 20; // enemy6
private bool moveUp, moveDown, moveLeft, moveRight;
private System.Windows.Forms.Timer _movementTimer = new Timer { Interval = 100 };
public bool collision()
{
if (PlayerPositionX == EnemyPosX & PlayerPositionY == EnemyPosY )
{
_movementTimer.Stop();
}
if (collision()==true)
{
_movementTimer.Stop();
}
return collision();
}
public Form1()
{
InitializeComponent();
_movementTimer.Tick += movementTimer_Tick;
}
private void movementTimer_Tick(object sender , EventArgs e)
{
playerControls();
}
//Form1_KeyDown
private void playerControls() // Player controls
{
if (moveRight)
{
PlayerPositionX += 5;
if (PlayerPositionX >= 800 - width)
{
PlayerPositionX = 800 - width;
}
}
if (moveLeft)
{
PlayerPositionX -= 5;
if (PlayerPositionX <= -43 + width)
{
PlayerPositionX = -43 + width;
}
}
if (moveUp)
{
PlayerPositionY -= 5;
if (PlayerPositionY <= 0)
{
PlayerPositionY = 0;
}
}
if (moveDown)
{
PlayerPositionY += 5;
if (PlayerPositionY >= 410)
{
PlayerPositionY = 410;
}
}
}
public void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Up:
moveUp = true;
break;
case Keys.Down:
moveDown = true;
break;
case Keys.Left:
moveLeft = true;
break;
case Keys.Right:
moveRight = true;
break;
}
playerControls();
_movementTimer.Start();
}
public void Form1_KeyUp(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Up:
moveUp = false;
break;
case Keys.Down:
moveDown = false;
break;
case Keys.Left:
moveLeft = false;
break;
case Keys.Right:
moveRight = false;
break;
}
if (!(moveUp || moveDown || moveLeft || moveRight ))
{
_movementTimer.Stop();
}
}
public void player(object sender, PaintEventArgs e) // drawing the player
{
e.Graphics.SmoothingMode =
System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
e.Graphics.Clear(this.BackColor);
e.Graphics.FillRectangle((Brushes.Blue), PlayerPositionX, PlayerPositionY, width, height);
e.Graphics.DrawRectangle(Pens.Black,
PlayerPositionX, PlayerPositionY,
width, height);
e.Graphics.SmoothingMode = //drawing the enemy
System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
e.Graphics.FillEllipse(Brushes.Red,
EnemyPosX, EnemyPosY,
EnemyWidth, EnemyHeight);
e.Graphics.DrawEllipse(Pens.Black,
EnemyPosX, EnemyPosY,
EnemyWidth, EnemyHeight);
e.Graphics.SmoothingMode = //drawing the enemy
System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
e.Graphics.FillEllipse(Brushes.Red,
EnemyPosX2, EnemyPosY2,
EnemyWidth2, EnemyHeight2);
e.Graphics.DrawEllipse(Pens.Black,
EnemyPosX2, EnemyPosY2,
EnemyWidth2, EnemyHeight2);
e.Graphics.SmoothingMode = //drawing the enemy
System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
e.Graphics.FillEllipse(Brushes.Red,
EnemyPosX3, EnemyPosY3,
EnemyWidth3, EnemyHeight3);
e.Graphics.DrawEllipse(Pens.Black,
EnemyPosX3, EnemyPosY3,
EnemyWidth3, EnemyHeight3);
e.Graphics.SmoothingMode = //drawing the enemy
System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
e.Graphics.FillEllipse(Brushes.Red,
EnemyPosX4, EnemyPosY4,
EnemyWidth, EnemyHeight);
e.Graphics.DrawEllipse(Pens.Black,
EnemyPosX4, EnemyPosY4,
EnemyWidth4, EnemyHeight4);
e.Graphics.SmoothingMode = //drawing the enemy
System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
e.Graphics.FillEllipse(Brushes.Red,
EnemyPosX5, EnemyPosY5,
EnemyWidth5, EnemyHeight5);
e.Graphics.DrawEllipse(Pens.Black,
EnemyPosX5, EnemyPosY5,
EnemyWidth5, EnemyHeight5);
e.Graphics.SmoothingMode = //drawing the enemy
System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
e.Graphics.FillEllipse(Brushes.Red,
EnemyPosX6, EnemyPosY6,
EnemyWidth6, EnemyHeight6);
e.Graphics.DrawEllipse(Pens.Black,
EnemyPosX6, EnemyPosY6,
EnemyWidth6, EnemyHeight6);
}
private void PlayerMoveTimer(object sender, EventArgs e ) // timer 2
{
Invalidate();
}
private void moveTimer(object sender, EventArgs e) // timer
{
//update coorndinates
EnemyPosX += EnemySpeedX; // how the enemy moves //timer 1
if (EnemyPosX < 0 ||
EnemyPosX + EnemyWidth > this.ClientSize.Width
)
{
EnemySpeedX = -EnemySpeedX;
}
EnemyPosY -= EnemySpeedY;
if (EnemyPosY < 0 ||
EnemyPosY + EnemyHeight > this.ClientSize.Height
)
{
EnemySpeedY = -EnemySpeedY;
}
EnemyPosX2 += EnemySpeedX2; // how the enemy moves //timer 1
if (EnemyPosX2 < 0 ||
EnemyPosX2 + EnemyWidth2 > this.ClientSize.Width
)
{
EnemySpeedX2 = -EnemySpeedX2;
}
EnemyPosY2 += EnemySpeedY2;
if (EnemyPosY2 < 0 ||
EnemyPosY2 + EnemyHeight2 > this.ClientSize.Height
)
{
EnemySpeedY2 = -EnemySpeedY2;
}
EnemyPosX3 += EnemySpeedX3; // how the enemy moves //timer 1
if (EnemyPosX3 < 0 ||
EnemyPosX3 + EnemyWidth3 > this.ClientSize.Width
)
{
EnemySpeedX3 = -EnemySpeedX3;
}
EnemyPosY3 -= EnemySpeedY3;
if (EnemyPosY3 < 0 ||
EnemyPosY3 + EnemyHeight3 > this.ClientSize.Height
)
{
EnemySpeedY3 = -EnemySpeedY3;
}
EnemyPosX4 += EnemySpeedX4; // how the enemy moves //timer 1
if (EnemyPosX4 < 0 ||
EnemyPosX4 + EnemyWidth4 > this.ClientSize.Width
)
{
EnemySpeedX4 = -EnemySpeedX4;
}
EnemyPosY4 += EnemySpeedY4;
if (EnemyPosY4 < 0 ||
EnemyPosY4 + EnemyHeight4 > this.ClientSize.Height
)
{
EnemySpeedY4 = -EnemySpeedY4;
}
EnemyPosX5 += EnemySpeedX5; // how the enemy moves //timer 1
if (EnemyPosX5 < 0 ||
EnemyPosX5 + EnemyWidth5 > this.ClientSize.Width
)
{
EnemySpeedX = -EnemySpeedX;
}
EnemyPosY5 -= EnemySpeedY5;
if (EnemyPosY5 < 0 ||
EnemyPosY5 + EnemyHeight5 > this.ClientSize.Height
)
{
EnemySpeedY5 = -EnemySpeedY5;
}
EnemyPosX6 += EnemySpeedX6; // how the enemy moves //timer 1
if (EnemyPosX6 < 0 ||
EnemyPosX6 + EnemyWidth6 > this.ClientSize.Width
)
{
EnemySpeedX6 = -EnemySpeedX6;
}
EnemyPosY6 += EnemySpeedY6;
if (EnemyPosY6 < 0 ||
EnemyPosY6 + EnemyHeight6 > this.ClientSize.Height
)
{
EnemySpeedY6 = -EnemySpeedY6;
}
//refresh windows
Invalidate();
}
}
}
A:
Sorry, but from a brief look at your code, it doesn't make much sense to me. A recursive collision-function which never returns an actual value. What is the idea behind that ? Does it even compile ?
Having said that, the specific collision detection you are after isn't that complicated. Here is the general way to do it.
If you know from the rectangle the coordinates of the four corners and from the circle the coordinate of the center and the length of the radius. All you have to do is calculate the distance (with the pythagoras formula) from each rectangle-corner to the center of the circle. If one or more of these distances is less than the radius of the circle you have a collision.
UPDATE
after giving this problem some more thought I now see there are some cases when a rectangle and circle collide which are not covered by my method. However I still think my method is a good way to start.
| {
"pile_set_name": "StackExchange"
} |
Q:
BigQuery: Select top 3 Day of Sales with GroupBy and save in separate columns leaving others
Input:
Have got Table 'A'
Store Category Sales Day
11 aaa 1.5 Sunday
11 aaa 0.5 Monday
11 aaa 2.5 Tuesday
11 aaa 2.0 Wednesday
11 aaa 3.0 Thursday
11 aaa 3.5 Friday
11 aaa 0.5 Saturday
22 bbb 0.5 Sunday
22 bbb 1.5 Monday
22 bbb 2.3 Tuesday
22 bbb 0.3 Wednesday
22 bbb 1.4 Thursday
22 bbb 4.1 Friday
22 bbb 0.2 Saturday
Scenario:
Have to take average of Sales grouped by Store,Category and save in separate column as well as pick top 3 sales day and save in separate column. As a result, one row for one store,category as shown below in sample output.
Expected Output:
Store Category AvgSales PeakDay1 PeakDay2 PeakDay3
11 aaa 1.92 Friday Thursday Tuesday
22 bbb 1.47 Friday Tuesday Monday
Tried Query:
SELECT
Store,
Category,
avg(Sales) as AvgSales,
ARRAY_AGG(Sales ORDER BY Sales DESC LIMIT 3) #but this line will not produce results in 3 separate columns
FROM A
GROUP BY Site, Category
Thanks in Advance!
A:
Below is for BigQuery Standard SQL
#standardSQL
SELECT Store, Category, AvgSales,
Days[OFFSET(0)] PeakDay1,
Days[SAFE_OFFSET(1)] PeakDay2,
Days[SAFE_OFFSET(2)] PeakDay3
FROM (
SELECT Store, Category,
ROUND(AVG(Sales), 2) AvgSales,
ARRAY_AGG(Day ORDER BY Sales DESC LIMIT 3) Days
FROM `project.dataset.table` t
GROUP BY Store, Category
)
If to apply to sample data from your question - output is
Row Store Category AvgSales PeakDay1 PeakDay2 PeakDay3
1 11 aaa 1.93 Friday Thursday Tuesday
2 22 bbb 1.47 Friday Tuesday Monday
| {
"pile_set_name": "StackExchange"
} |
Q:
When to start lifting after sprained ankle?
I sprained my ankle 3 weeks ago and I was wondering if it would be bad to start lifting again. I'm thinking of doing Leg Press to get started before I tackle squats.
I still lack some mobility in my ankle (pain when stretching) but it is very light. Can I work out safely despite that? (No bar squats don't hurt, except for slight lack of mobility)
I've been skipping leg day because of this, but it's my favourite day.
A:
It depends on how bad your injury is. When I went through a pretty serious sprained ankle injury, I did a lot of physiotherapy exercises for improving the stability and the ROM of this area before starting leg training again, including treatment with electricity and a very painful stretching massage. Only about 3-4 months after the injury I started working out again, starting with a high rep range (about 15/set) and putting a little effort into separated legs exercises (lunges, single-leg leg press, etc).
My conclusions are the following:
Getting back your stability and ROM is extremely important. My physiotherapist said I could stop when the leg was "almost" back to normal, but today, almost a year later, I still feel a difference in the ankles functioning. Keep going with this training even if you feel your functioning is relatively fine, because the process "stops" when you stop practicing.
Do single leg exercises. Lunges, single-leg leg press and later single-leg squat, single-leg leg curl, and maybe even single-leg calf raise (though I didn't try it myself). The strength difference between your legs increases on every day of "rest", so this is important for "balancing" your muscles.
Get back to everyday functioning as soon as possible (recommended by your doctor, of course), in order to shorten your recovery period.
Hope you'll feel better soon!
| {
"pile_set_name": "StackExchange"
} |
Q:
VSCode SSH remote friendly host name
I have this .config file for SSH hosts:
Host 10.32.1.43
HostName 10.32.1.43
User root
ForwardAgent yes
Host 10.32.0.39
HostName 10.32.0.39
User administrator
ForwardAgent yes
Can I give more friendly names to my machines, instead of remembering which of them is the Ubuntu machine, and which is the CentOS?
A:
If you change the Host line it changes the name displayed in VSCode and normal ssh commands
Host example
HostName myexampleip.local
User example
using this example config file can be used with this command
ssh example
| {
"pile_set_name": "StackExchange"
} |
Q:
Seeking for gimbal head-like vertically sliding clamp
for my project of wireless motorized gimbal head for DSLR, I am seeking for gimbal head-like vertically sliding clamp with quick release (ideally arca-swiss). The rail which it slides on is not a problem, there are plenty of them on a market. For better illustration, please see attached image.
Is it possible to buy something like this standalone for reasonable price? What is the correct name for such clamp? I am searching for it for half a day and I only found several extremely expensive spare parts.
The only option I see now is buying cheap (+- 50 €) gimbal head and just take it from there. But if you know some better/cheaper option, please let me know here. Thank you :)
A:
I have found "Bk-45 gimbal head" for less than 35 €, so I decided to buy it and modify it for my purposes. I was not successful in finding stand-alone sliding L-clamp cheaper than this, and I doubt that custom-made part would cost less.
| {
"pile_set_name": "StackExchange"
} |
Q:
why $x^{4} + y^{4} - 4 x y + 1$ graph differently in my textbook and mathematica?
why this function $x^{4} + y^{4} - 4 x y + 1$ graph differently between mathematica and my textbook? did I make some error with my mathematica syntax?
A:
If we let $f(x,y)=x^4-4 x y+y^4+1$ we can use the partial derivatives $\frac{\partial f}{\partial x}$ and $\frac{\partial f}{\partial y}$ to calculate that those humps that you see in the picture from the book must be at the points $(1,1,-1)$ and $(-1,-1,-1)$. So now we know that we should take something like $-2$ to $2$ for our $x$ and $y$ range. By evaluating $f(0,0)=1$ we see that we should not take our $z$ range to have a maximum value that is too big.
Try something like
Plot3D[x^4 + y^4 - 4 x*y + 1, {x, -2, 2}, {y, -2, 2}, PlotRange ->
{All, All, {-1, 2}}]
which results in
| {
"pile_set_name": "StackExchange"
} |
Q:
Exporting a Java Project as .jar with including .java source code and preserving external libraries dependecies
I know how to export a Java Project as a .jar including also .java source code (just export it as a plain .jar), and how how to export it as a runnable .jar including only .class files (just select the runnable .jar export style). If the project doesn't have dependecies on external libraries, I noticed that both .jar run correctly by command line.
Problem: if the project contains dependecies on some external library added in the Build Path, it results that the .jar exported as runnable correctly works while a plain .jar doesn't because the external libraries are not anymore found when launching from command line.
Annotation: external libraries are added as .jar in a folder "lib" in the project and from there added to the Build Path.
I want to be able to export the Java project while either including the .java source code and preserving the dependencies on external libraries so that it will run when launching it by command line. Any suggestion? All that I can find out is "just export it as runnable .jar", but this will hide the .java source codes.
EDIT: Can anyone explain why this happens?
A:
If you don't need an automated way you can achieve it with following manual steps:
First export it as runnable jar (a.jar)
Second export as jar with source (b.jar)
Use 7-zip or other archive tool to integrate the sources into the runnable jar. Open both jars and drag the folder containing the sources (first part of package name) from jar (b.jar) into the z-zip window of runnable jar (a.jar)
| {
"pile_set_name": "StackExchange"
} |
Q:
Best practice to build a CD pipeline to deploy application to different environments
Currently I'm trying to build a CD pipeline for our application, which is a typical Maven J2EE project and we'll deploy a war to Tomcat container.
Our plan for the CD pipeline looks like this:
CI(Run UT and build the WAR) -> Deploy to DEV -> Deploy to SIT -> Deploy UAT -> Deploy PROD
To follow the best practices of CD, we only build the binary(war) once in the CI phase, but we have some configuration files which are different for each environment, so what's the best way to put the related configuration files for each environment during the deployment phase?
We're using Jenkins and the build-pipe-line plugin to build the pipeline, are there any recommended plugins to make this happen?
Thanks.
A:
Configuring the artifact
Write a script to replace the config files if they're embedded in the
WAR.
You may employ maven-antrun-plugin to
Extract the WAR
Replace the config
Repack the WAR
The ant task should be reused for different environments:
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<configuration>
<tasks>
<echo message="Configuring artifact, ${PIPELINE_STAGE}"/>
<!-- extracting,replacing,repacking -->
</tasks>
</configuration?
Externalize the config files. Well, just upload the config files to the server.
Sharing the artifact through pipeline stages
Upload the WAR to your artifact repository.
Dowload the WAR built in your CI stage and configure it.
Deploy the configured WAR.
You may find the detail in the Sharing build artifacts throughout the pipeline from this article.
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP Root Directory Listing
There is any ways to listing all main directories present in php server(may it is wamp or xampp).
A:
Depending on what you mean by "root directory" it could be as simple as
foreach( glob($_SERVER['DOCUMENT_ROOT'] .'/*', GLOB_ONLYDIR) as $fn) {
echo basename($fn), "<br />\n";
}
| {
"pile_set_name": "StackExchange"
} |
Q:
MATLAB fitcSVM weight vector
I am training a linear SVM classifier with the fitcsvm function in MATLAB:
cvFolds = crossvalind('Kfold', labels, nrFolds);
for i = 1:nrFolds % iterate through each fold
testIdx = (cvFolds == i); % indices of test instances
trainIdx = ~testIdx; % indices training instances
cl = fitcsvm(features(trainIdx,:),
labels(trainIdx),'KernelFunction',kernel,'Standardize',true,...
'BoxConstraint',C,'ClassNames',[0,1], 'Solver', solver);
[labelPred,scores] = predict(cl, features(testIdx,:));
eq = sum(labelPred==labels(testIdx));
accuracy(i) = eq/numel(labels(testIdx));
end
As visible from this part of code, the trained SVM model is stored in cl. Checking the model parameters in cl I do not see which parameters correspond to classifier weight - ie. the parameter for linear classifiers which reflects the importance of each feature. Which parameter represents the classification weights? I see in the MATLAB documentation "The vector β contains the coefficients that define an orthogonal vector to the hyperplane" - is hence cl.beta representing the classification weights?
A:
As you can see in this documentation, the equation of a hyperplane in fitcsvm is
f(x)=x′β+b=0
And as you know, this equation shows following relationship:
f(x)=w*x+b=0 or f(x)=x*w+b=0
So, β is equal to w (weights).
| {
"pile_set_name": "StackExchange"
} |
Q:
Jquery and Hide a div on a click
i have a little problem with JQuery.
Well, i have a and i want to hide this div when an user click in a zone that is not in the like the "notifications" behavior in facebook.
The solution that i found is to use jQuery.live() method but i think there is a better way to do it.
Thank you.
A:
Assuming:
<div class="notification">You have 3 new messages</div>
use:
$(document).click(function(evt) {
if ($(this).closest("div.notification").length == 0) {
$("div.notification").fadeOut();
}
});
Basically this listens to all clicks. If one is received that doesn't occur inside a notification div it fades them out.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get the InnerHTML of a div in C#
I'm working on a project when I need to copy the innerHTML of a div and send it to a txt file in C#. While I can get the innerHTML of the entire page through this code:
private void button3_Click(object sender, EventArgs e)
{
using (WebClient client = new WebClient())
{
string htmlCode = client.DownloadString("youtube.com");
textBox1.Text = htmlCode;
}
}
What do I need to do to get the innerHTML of a specific div?
Thanks!
A:
I have a solution for this using HtmlAgilityPack...
Install HtmlAgilityPack from NuGet.
Use this code.
HtmlWeb web = new HtmlWeb();
HtmlDocument dc = web.Load("Your_Url");
var s = dc.DocumentNode.SelectSingleNode("//div[@id='div_id']").InnerHtml;
It will return inner html of div.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I redirect a URL to another domain?
I want foo.example.horse/short to redirect to the external URL https://some.long.org/url/that/i/want/to/redirect_to. Is there a simple way to do this from Joomla, or do I have to edit the .htaccess file?
A:
You could unpublish /short so that it 404s, and then use the redirects manager.
(Components > Redirects).
Details : https://docs.joomla.org/Help37:Components_Redirect_Manager
| {
"pile_set_name": "StackExchange"
} |
Q:
has the behaviour of static arrays changed?
I learnt c++ about 6 years ago and I remember in the section about arrays unless you instantiated them using new then their size was static and could only be set in the source code with literal constants, not at run time.
But I was just playing around with a tutorial at
http://www.cplusplus.com/doc/tutorial/dynamic/
and tried to do it without new, and to my surprise it worked. Am I misunderstanding something?
The original code is at the mentioned URL but it isn't too hard to see what it was from my modified code below.
I realise with strings, vectors etc... arrays aren't really needed (probably explains why this issue never occurred to me) but just humour me :)
// rememb-o-matic
#include <iostream>
#include <new>
using namespace std;
int main ()
{
int i,n;
// int * p;
cout << "How many numbers would you like to type? ";
cin >> i;
int p[i];
// p= new (nothrow) int[i];
// if (p == 0)
// cout << "Error: memory could not be allocated";
if (false)
cout << "whut?" << endl;
else
{
for (n=0; n<i; n++)
{
cout << "Enter number: ";
cin >> p[n];
}
cout << "You have entered: ";
for (n=0; n<i; n++)
cout << p[n] << ", ";
// delete[] p;
}
return 0;
}
A:
The code works because most compilers support Variable Length Arrays(VLA) through compiler extensions.
However, Variable Length arrays are not allowed by the C++ standard, Using such a compiler extension would result in your code being non portable and non standard conformant.
Since you are using gcc, Compile your code with -pedantic option and it will tell you it is not standard approved.
A:
There is no pressing need for variable length arrays in C++ because it has vectors. Just replace
int p[i];
with
std::vector<int> p(i);
and all is well.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unrecognized selector sent to class when using NSTimer in Swift; NSInvalidArgumentException
I'm trying to use an NSTimer to run a function at a certain interval, but every time it runs the program crashes with an exception:
+[Project.Class updateLabel]: unrecognized selector sent to class...
Terminating app due to uncaught exception "NSInvalidArgumentException".
The code is as follows:
class SecondViewController: UIViewController {
// MARK: Properties
override func viewDidLoad() {
super.viewDidLoad()
do {
try updateLabel()
try startTimer()
}
catch{
self.showAlert()
}
}
@IBOutlet weak var i2cLabel: UILabel!
// MARK: Actions
func startTimer() throws {
_ = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateLabel"), userInfo: nil, repeats: true)
}
func showAlert() {
}
func updateLabel() throws {
}
}
If I comment out the NSTimer line, the program compiles and runs just fine.
Note that updateLabel(), the selector function, takes no arguments so calling it as a selector without a colon suffix should work. This seems to be unique to this problem.
A:
Try update your code to:
override func viewDidLoad() {
super.viewDidLoad()
do {
updateLabel()
try startTimer()
}
catch{
self.showAlert()
}
}
// MARK: Actions
func startTimer() throws {
_ = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateLabel"), userInfo: nil, repeats: true)
}
func showAlert() {
}
func updateLabel() {
}
It seems that: NSTimer don't know call a function throws. So it will crash.
I have tried to find some official or some article describe about it. But sad that I can't find now.
You can reference to this question: Reference
Hope this help!
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I automate writing contracts in MS Word using a form?
At my job, vendor contracts must be written for service work. Many of the items on these contracts that must be filled out are repetitive data. Is there a way to set up an electronic form to fill out these items without having to type them every time?
For instance, there are five areas that are contracted for service work. There could be a dropdown list that contains these five places, and on submitting the form, it will automatically place the wording in the proper place on the contract.
Another example is that one of the outline lines states "Total price including labor and materials shall not exceed (price)." This amount could be entered on a form, and then have it output to the contract.
What is a good way to accomplish this?
A:
As noted in comments:
Start by using Use Mail Merge for the first example.
Start by using Fill-in fields for the second example.
| {
"pile_set_name": "StackExchange"
} |
Q:
cursor won't move when using move() or wmove() when using the curses library
I have this program which prints the first 5 lines or more of a text file to a curses window and then prints some personalized input. but after printing the lines from the text file, the cursor wont' move when using move or wmove. I printed a word after using both and refresh() but it is printed in the last position the cursor was in. I tried mvprintw and mvwprintw but that way I got no output at all.
this is a part of the code
while (! feof(results_file))
{
fgets(line,2048,results_file);
printw("%s",line);
}
fclose(results_file);
mvwprintw(results_scrn,num_rows_res,(num_col_res/2) - 2,"Close");
wrefresh(results_scrn);
A:
I suspect that you are trying to print outside the bounds of the window.
In particular, I would guess that here:
mvwprintw(results_scrn,num_rows_res,(num_col_res/2) - 2,"Close");
...num_rows_res is the number of rows in the results_scrn window - but that means that the valid row coordinates range from 0 to num_rows_res - 1.
If you try to move() or wmove() outside the window, the cursor will not actually move; a subsequent printw() or wprintw() will print at the previous cursor position. If you try to mvprintw() or mvwprintw(), the whole call will fail at the point of trying to move the cursor, and so it won't print anything at all.
Here's a complete demonstration (just printing to stdscr which has LINES rows and COLS columns):
#include <stdio.h>
#include <curses.h>
int main(void)
{
int ch;
initscr();
noecho();
cbreak();
/* This succeeds: */
mvprintw(1, 1, ">>>");
/* This tries to move outside the window, and fails before printing: */
mvprintw(LINES, COLS / 2, "doesn't print at all");
/* This tries to move outside the window, and fails: */
move(LINES, COLS / 2);
/* This prints at the cursor (which hasn't successfully moved yet): */
printw("prints at current cursor");
/* This is inside the window, and works: */
mvprintw(LINES - 1, COLS / 2, "prints at bottom of screen");
refresh();
ch = getch();
endwin();
return 0;
}
(In fact the functions do return a result; if you check it, you'll find that it's ERR in the cases that fail.)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to autoscale the contents of a WKWebView?
To autoscale a webpage inside a good old WebView in Swift, all I had to do was:
var w:UIWebView
w.scalesPageToFit=true
I cannot find an equivalent method for a WKWebView, and webpages appear too big in my app. How can I autoscale the contents of a WKWebView?
-I am using Xcode 7 and Swift
A:
Here is my solution:
extension WKWebView {
private struct key {
static let scale = unsafeBitCast(Selector("scalesPageToFit"), UnsafePointer<Void>.self)
}
private var sourceOfUserScript: String {
return "(function(){\n" +
" var head = document.getElementsByTagName('head')[0];\n" +
" var nodes = head.getElementsByTagName('meta');\n" +
" var i, meta;\n" +
" for (i = 0; i < nodes.length; ++i) {\n" +
" meta = nodes.item(i);\n" +
" if (meta.getAttribute('name') == 'viewport') break;\n" +
" }\n" +
" if (i == nodes.length) {\n" +
" meta = document.createElement('meta');\n" +
" meta.setAttribute('name', 'viewport');\n" +
" head.appendChild(meta);\n" +
" } else {\n" +
" meta.setAttribute('backup', meta.getAttribute('content'));\n" +
" }\n" +
" meta.setAttribute('content', 'width=device-width, user-scalable=no');\n" +
"})();\n"
}
var scalesPageToFit: Bool {
get {
return objc_getAssociatedObject(self, key.scale) != nil
}
set {
if newValue {
if objc_getAssociatedObject(self, key.scale) != nil {
return
}
let time = WKUserScriptInjectionTime.AtDocumentEnd
let script = WKUserScript(source: sourceOfUserScript, injectionTime: time, forMainFrameOnly: true)
configuration.userContentController.addUserScript(script)
objc_setAssociatedObject(self, key.scale, script, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
if URL != nil {
evaluateJavaScript(sourceOfUserScript, completionHandler: nil)
}
} else if let script = objc_getAssociatedObject(self, key.scale) as? WKUserScript {
objc_setAssociatedObject(self, key.scale, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
configuration.userContentController.removeUserScript(script)
if URL != nil {
let source = "(function(){\n" +
" var head = document.getElementsByTagName('head')[0];\n" +
" var nodes = head.getElementsByTagName('meta');\n" +
" for (var i = 0; i < nodes.length; ++i) {\n" +
" var meta = nodes.item(i);\n" +
" if (meta.getAttribute('name') == 'viewport' && meta.hasAttribute('backup')) {\n" +
" meta.setAttribute('content', meta.getAttribute('backup'));\n" +
" meta.removeAttribute('backup');\n" +
" }\n" +
" }\n" +
"})();"
evaluateJavaScript(source, completionHandler: nil)
}
}
}
}
}
extension WKUserContentController {
public func removeUserScript(script: WKUserScript) {
let scripts = userScripts
removeAllUserScripts()
scripts.forEach {
if $0 != script { self.addUserScript($0) }
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Check if property is decorated with specific annotation - Typescript
How can I determine if a specific property is decorated with a specific annotation?
For example this class:
class A {
@DecoratedWithThis
thisProp: number;
}
How can I know that thisProp is decorated with DecoratedWithThis?
My use case: I use the class from another file to generate code and HTML for the properties.
Could you imagine of another solution?
A:
There is no native way that I know of in typescript, but there is a way to do it using 'reflect-metadata' library https://github.com/rbuckton/reflect-metadata which is a proposed extension to native reflection api.
Decorators are just functions that get executed when your class is defined. in your case you want to create a property decorator
function (target, propertyKey) {}
Where target is your Object.prototype and name is the property name
Per Reflect Metadata Documentation
// define metadata on an object or property
Reflect.defineMetadata(metadataKey, metadataValue, target, propertyKey);
// get metadata value of a metadata key on the prototype chain of an object or property
let result = Reflect.getMetadata(metadataKey, target, propertyKey);
You can solve your problem by adding metadata to your property that you can read later on to check if that property has been decorated.
Example Implementation
import 'reflect-metadata';
const metadataKey = 'MyDecorator';
function MyDecorator(target, propertyKey) {
Reflect.defineMetadata(metadataKey, true, target, propertyKey);
}
function myDecoratorUsingClass<T>(type: Type<T>, propertyKey: string) {
return myDecoratorUsingInstance(new type(), propertyKey);
}
function myDecoratorUsingInstance<T>(instance: T, propertyKey: string) {
return !!Reflect.getMetadata(metadataKey, instance, propertyKey);
}
class MyClass {
@MyDecorator
property1;
property2;
}
console.log(myDecoratorUsingClass(MyClass, 'property1')); // true
console.log(myDecoratorUsingClass(MyClass, 'property2')); // false
const instance = new MyClass();
console.log(myDecoratorUsingInstance(instance, 'property1')); // true
console.log(myDecoratorUsingInstance(instance, 'property2')); // false
NOTE To use myDecoratorUsingClass your class should have a constructor where all the parameters are optional (or no parameters)
| {
"pile_set_name": "StackExchange"
} |
Q:
Tautology And Substitution
Let $ \alpha $ be some proposition, and let $ A = \alpha $, and let $ B = \neg \alpha $.
Is the statement $ A \lor B $ a tautology?
A:
Obviously, $α ∨ ¬α$ is a tautology.
But - in general - $A∨B$ is not a tautology.
The "rule" is:
every instance of a tautological schema will be a tautology.
In other words, given a tautological schema, like $\varphi \lor \lnot \varphi$, every formula obtained via substitution from it, like $p_1 \lor \lnot p_1$ or $\forall x Q(x) \lor \lnot \forall x Q(x)$, will be a tautology.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python socket stays blocked on socket.recv() when client expects data
I am trying my hand at socket programming in Python and ran an issue.
The code for the 'server' side is:
(connection, address) = in_socket.accept()
size_str = connection.recv(4)
result_size=struct.unpack('>i',size_str)
string_buffer=[]
print 'results size is: ',result_size[0]
while 1:
r = connection.recv(result_size[0])
print 'length is: ', len(r)
if not r:
break
string_buffer.append(r)
s = ''.join(string_buffer)
print 'recieved data: ', s
connection.send('Thanks for connecting')
And for the client side, it is:
sock.connect(server_address)
message = ('{\"message\":\"This is the messcxvage\"}')
packedlen=struct.pack('>i',len(message))
sock.send(packedlen)
sock.send(message)
xyz = sock.recv(1024)
When the client is expecting data back, the if condition for breaking out of the while loop in the server is never fulfilled. The server keeps waiting to receive more data. If I comment out the last lines from both code samples, it works as expected. Why does this happen and what is the fix for this?
Thanks in advance!
A:
Why does this happen
You correctly answered this question in your comment.
and what is the fix for this?
Just don't program an endless loop. You wisely send the length of the data from the client to the server, so the server knows how many bytes to await. On UNIX systems dispose of the whole while 1: loop as well as the s = ''.join(string_buffer) and write only
s = connection.recv(result_size[0], socket.MSG_WAITALL)
instead. On Windows systems (not having MSG_WAITALL) you still need to loop, but only until result_size[0] bytes overall have been received.
| {
"pile_set_name": "StackExchange"
} |
Q:
Use custom url for defining environment in gitlab-ci
Current configuration:
I am working with gitlab-ci. I currently have two stages in my gitlab-ci.yml file, one for building and one for deploying. The jobs are running successfully.
gitlab-ci.yml
stages:
- build
- deploy
d_build:
stage: build
tags:
- my-runner
script:
- echo "Build"
- sh testScript.sh
d_review:
stage: deploy
environment:
name: staging
url: (INSERT URL HERE)
tags:
- my-runner
script:
- echo "Foo"
Gitlab Runner Vesion: 11.7.0
OS: windows/amd64
Desired behavior:
The testScript.sh shell file is generating a url which I would like to use in the url field in the environment, in the deploy stage.
From the operations pane in gitlab, in the environments page, I would like to be able to select the "Open live environment" option for me to visualize the url generated by the .sh file. How can this be achieved?
I thought of two possible ways but I am not sure on how either of them can be achieved. Would it be possible, from "testScript.sh", to set up an environmental variable in the build stage so that it can then be picked up in the deploy stage?
Alternatively, if the "testScript.sh" file were to create a text file containing the url, how could I instruct the deploy stage to read from the text file and use its contents to define a variable for it to then be used in the url field?
What I tried:
As a test, I tried setting up a variable in variables in the build stage:
stages:
- build
- deploy
d_build:
stage: build
tags:
- my-runner
script:
- echo "Build"
- sh testScript.sh
variables:
url_endpoint: "myendpoint"
Modifying the url as follows:
d_review:
stage: deploy
environment:
name: staging
url: https://localhost:1234&endpoint=$url_endpoint
tags:
- my-runner
script:
- echo "Foo"
However this did not work, there was a blank in the final url instead of "myendpoint", which tells me I am missing something in how variables are propagated too. Would appreciate any suggestions.
A:
As of running the job, the url has to be set. You can not set the environment url in a job before the deployment:
The url parameter can use any of the defined CI variables, including predefined,
secure variables and .gitlab-ci.yml variables. You however cannot use variables
defined under script.
https://docs.gitlab.com/ee/ci/yaml/README.html#environmenturl
You could use a javascript redirect as workaround:
d_build:
stage: build
tags:
- my-runner
script:
- echo "Build"
- UUID=$(sh testScript.sh)
- echo '<html><head><script type="text/javascript">window.location.replace("https://localhost:5939/mywebpage/index.html?id='$UUID'");</script></head></html>' > redirect.html
d_review:
stage: deploy
environment:
name: staging
url: https://localhost:5939/mywebpage/redirect.html
tags:
- my-runner
script:
- echo "Foo"
This creates a redirect.html which redirects to your localhost url with the parameter created by testScript.sh. If the creation of the redirect.html fails due to character escaping, try to put the line starting with echo into your sh script.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using a C++11 initializer_list with a recursively defined type using constexpr
Is it possible to use the C++11 initializer_list to assemble a recursively defined class such as Foo, below, using constexpr constructors:
template <size_t N>
struct Foo {
constexpr Foo(int x, Foo<N-1> f) : x(x), xs(xs) {}
int x;
Foo<N-1> xs;
};
template <> struct Foo<0> {};
I can initialise a Foo<3> using:
int main(int argc, char *argv[])
{
Foo<3> a = Foo<3>(1,Foo<2>(2,Foo<1>(3,Foo<0>())));
return 0;
}
It would be nice to use Foo<3> a = {1,2,3} instead. If there was a constexpr tail function in initializer_list I think it should work.
A:
Yes, in a kind of round-about way, effectively unpacking and repacking the initializer list to a more suited format. However, there is a better (imho) way: Variadic templates.
#include <stddef.h>
#include <iostream>
template <size_t N>
struct Foo {
template<class... Tail>
constexpr Foo(int i, Tail... t) : x(i), xs(t...) {}
void print(){
std::cout << "(" << x << ", ";
xs.print();
std::cout << ")";
}
int x;
Foo<N-1> xs;
};
template <>
struct Foo<1> {
constexpr Foo(int i) : x(i) {}
void print(){ std::cout << "(" << x << ")"; }
int x;
};
int main(){
Foo<3> x = {1, 2, 3};
x.print();
std::cout << "\n";
}
Output as expected:
(1, (2, (3)))
Note that I chose 1 as the base case, as it simply makes more sense.
| {
"pile_set_name": "StackExchange"
} |
Q:
Conflicting shortcuts in XAML editor - Visual Studio 2010
I'd like to set a shortcut for "Navigate to Event Handler" operation available on events in XAML editor. Currently, I right-click the event name (in XAML) and select "Navigate to Event Handler". However, I'd like to be able to set a shortcut.
The shortcut I want for this action is F12, but there is already a shortcut "Edit.GoToDefinition" set to F12 (Global).
I can't set it to F12 without clearing the F12 (Global) setting for Edit.GoToDefinition.
There is a combo box "Use new shortcut in:" where I can set a context in which I want to use the shortcut. However, I can't find the XAML editor on the list. I've tried and set it to "HTML Editor Source View", but it didn't work. Then I've tried to set it to "Text Editor", and then it worked, but then Edit.GoToDefinition got overriden in source code. And since the "Navigate to Event Handler" has no meaning in code-behind, nothing happens on F12.
Is there an option in "Use new shortcut in:" I can use to limit F12 : EditorContextMenus.XAMLEditor.NavigateToEventHandler to work only in XAML editor?
A:
Well, here is your problem. The XAML editor is technically an extension of the Editor component itself. So there is no way, through the option box, for you to do what you want. Now you can punch in some code to do that, but that seems like firing a bazooka to kill an ant when a better alternative is to pick a different shortcut.
Now you CAN just write a macro and bind that to F12. Basically you can check the extension of the document you are working on. *.cs? Goto definitions. *.xaml? navigateto!
| {
"pile_set_name": "StackExchange"
} |
Q:
NHibernate one-to-one mapping - full object graph is not saved
I am trying to get NHibernate to save complete object graph in a one-to-one mapping scenario. I have following classes
public class Employee : EntityBase
{
public virtual string EmployeeNumber { get; set; }
public virtual Address ResidentialAddress {get; set; }
}
public class Address : EntityBase
{
public virtual string AddressLine1 { get; set; }
public virtual string AddressLine2 { get; set; }
public virtual string Postcode { get; set; }
public virtual string City { get; set; }
public virtual string Country { get; set; }
public virtual Employee Employee { get; set; }
}
I am trying to use one-to-one mapping here so that one employee has only one residential address. My mappings are below
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Domain" namespace="Domain">
<class name="Employee">
<id name="Id" generator="hilo" />
<property name="EmployeeNumber" length="10" />
<one-to-one name="ResidentialAddress" class="Address" property-ref="Employee" cascade="all" />
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Domain" namespace="Domain">
<class name="Address">
<id name="Id" generator="hilo" />
<property name="AddressLine1"/>
<property name="AddressLine2" />
<property name="Postcode" />
<property name="City" />
<property name="Country" />
<many-to-one name="Employee" class="Employee" unique="true" />
</class>
</hibernate-mapping>
I am using following code to save an instance of employee object
using (var transaction = Session.BeginTransaction())
{
id = Session.Save(new Employee
{
EmployeeNumber = "123456789",
ResidentialAddress = new Address
{
AddressLine1 = "Address line 1",
AddressLine2 = "Address line 2",
Postcode = "postcode",
City = "city",
Country = "country"
}
});
transaction.Commit();
}
In the above situation, the foreign key on Address back to Employee is always null. But if I change RResidentialAddress property on Employee class so that Employee property is always populated correctly as below
private Address address;
public virtual Address ResidentialAddress
{
get { return address; }
set
{
address = value;
if (value != null) value.Employee = this;
}
}
This makes it work perfectly. Why do I have to set ResidentialAddress.Employee? Am I missing something in the mappings? Should NHibernate not automatically save the complete object graph (and hence determine proper foreign key values).
The above working code concerns me as it may create a problem when called from NHiberante during loading of entity from database.
A:
Your are not missing anything.
We (developers) should always care about setting both ends of any bidirectional relation.
When we use one-to-many (without inverse="true") and without setting the many-to-one, we always end up with redundant and unefficient sequence of SQL statements:
INSERT child record, place NULL into Parent_ID
UPDATE child record, set the Parent_ID with Parent.ID
This is not suggested: 6.8. Bidirectional Associations:
... The non-inverse side is used to save the in-memory representation to the database. We would get an unneccessary INSERT/UPDATE and probably even a foreign key violation if both would trigger changes! The same is of course also true for bidirectional one-to-many associations...
So, that is in one-to-many, many-to-one.
In case of one-to-one
There is no collection persister in place as discussed above. No man in the middle, which would take care about the other end, and issue "unefficient" INSERT and later UPDATE. NHibernate will use standard entity persisters for Employee and Address.
Each association end of the relation (Employee-Address) has its own persister. These could be triggered in a cascade (usually good idea to have <one-to-one ... cascade="all" />)
But each persister needs enough information to create proper INSERT or UPDATE statement. I.e. even C# Address must know about its Employee. The Address persister, will handle INSERT/UPDATE alone, with access to Address instance only.
SUMMARY: We have to set both ends in code.... And that is good practice even if we are not forced (non inverse child mapping with nullable parent column).
BTW: once loaded from DB, we expect that NHibernate will set both ends... why should not we do the same?
| {
"pile_set_name": "StackExchange"
} |
Q:
What would happen if someone removed the PATH variable from /etc/environment?
Currently, the best known way we found to add an API key to a remote Ubuntu server was by editing it in as an environment variable in etc/environment. The infrastructure docs of the project were unfortunately lost in time.
In the etc/environment folder, the PATH variable is set that is used system-wide. If someone were to accidentally overwrite this variable when trying to add another environment variable, what would happen? Would the damage be so big that doing so would leave the machine in an non-recoverable state?
A:
If someone were to accidentally overwrite this variable when trying to add another environment variable, what would happen?
You would no longer be able to easily start programs that were installed to unusual locations – you would need to run them using the full path instead.
There is always a default PATH value set by several components (by the init system for services, by the login handler for interactive sessions), and although different Linux distros tweak it to their own needs, the default is always suitable for the basic system to boot up and let you log in.
(The only reason to have PATH in /etc/environment in the first place is if you need additional directories – e.g. some software installed in /opt or /u1 not through the distro's regular packaging.)
If the global PATH setting is corrupted in some other way but you can manage to log in via SSH or console, you can still run executables through their full path (e.g. /bin/sudo). And since environment variables are technically not global but copied per-process, you can set it for just that shell while trying to fix things.
Would the damage be so big that doing so would leave the machine in an non-recoverable state?
As long as you have physical or KVM access, a Linux system is almost always in recoverable state. Most of the boot process doesn't actually rely on PATH all that much, and there are several ways to interrupt it and get a recovery root shell from which you could edit the file back.
| {
"pile_set_name": "StackExchange"
} |
Q:
Flex slider 2 hide controlNav
I'm using Flexslider2 and wish to hide the Control Navigation below the slides (the little dots), does anyone know if this is possible. I have managed to turn the dots off with the ControlNav - False but is still keeps an empty box there.
A:
Looking at the plugin, this should do what you are looking for:
$('.flexslider').flexslider({
controlNav: false
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Зачем angular выдаёт такую ошибку?
Failed to compile.
Error [ERR_IPC_CHANNEL_CLOSED]: channel closed
at ChildProcess.target.send (internal/child_process.js:588:16)
at AngularCompilerPlugin._updateForkedTypeChecker (/home/user/Рабочий стол/lesson_proyect_angular/my-app/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:370:34)
at Promise.resolve.then (/home/user/Рабочий стол/lesson_proyect_angular/my-app/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:208:22)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
A:
Похоже на то, что это бага см. это и это
| {
"pile_set_name": "StackExchange"
} |
Q:
mocha & chai dependencies when running npm install
I want to run an Ionic app with Grunt (Yeoman Ionic)
To do this the script runs npm install and bower install. Then run grunt to compile and then grunt serve to serve it on local host.
npm install does not create peer dependencies with Mocha and Chai which is making bower install abort like so:
Running "karma:continuous" (karma) task
Warning: Cannot find module 'mocha' Use --force to continue.
Aborted due to warnings.
I ran npm install -g chai mocha then npm install and got the same
npm WARN [email protected] requires a peer of mocha@* but none was installed.
npm WARN [email protected] requires a peer of chai@* but none was installed.
Even though this is a warning it is yielding errors when running yo ionic:
npm WARN [email protected] requires a peer of chai@* but none was installed.
npm WARN [email protected] requires a peer of mocha@* but none was installed.
ERROR: Error: ENOENT: no such file or directory, rename '/Users/donjohnson/ionicNom/app/app/css' -> '/Users/donjohnson/ionicNom/app/app/styles'
ERROR: Error: ENOENT: no such file or directory, rename '/Users/donjohnson/ionicNom/app/app/js' -> '/Users/donjohnson/ionicNom/app/app/scripts'
ERROR: Error: ENOENT: no such file or directory, rename '/Users/donjohnson/ionicNom/app/app/img' -> '/Users/donjohnson/ionicNom/app/app/images'
This makes grunt serve open a browser page with nothing in it :(
A:
npm install --save-dev mocha chai to your project (without the -g).
As of version 3, npm does not automatically install peerDependencies
| {
"pile_set_name": "StackExchange"
} |
Q:
Did I diffrentiate correctly?
$$\dfrac{\mathrm d}{\mathrm dθ}\dfrac{6\sin(3θ)}{\cos^2(3θ)}=\dfrac{18\cos^3(3θ)+36\sin^2(3θ)\cos(3θ)}{\cos^4(3θ)}=18(\sec(3θ)+2\tan^2(3θ)\sec(3θ))$$
Did I get this right? wolfram gives me a different answer...
$$18 \sec^3(3θ)+18 \tan^2(3θ) \sec(3θ)$$
If somone can show me how this answer is received I'd be grateful, spent hours on it yesterday trying to figure out wolframs answer..I don't know where I'm going wrong, I used the quotient rule.
A:
$$\dfrac{\sin3\theta}{\cos^23\theta}=\dfrac{\sin3\theta}{\cos3\theta}\cdot\dfrac1{\cos3\theta}=\tan3\theta\sec3\theta$$
$$\dfrac{d[\tan3\theta\sec3\theta]}{d\theta}=\dfrac{d[\tan3\theta]}{d\theta}\cdot\sec3\theta+\tan3\theta\cdot\dfrac{d[\sec3\theta]}{d\theta}=?$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Xcode 7.1.1 installation fails
While trying to install Xcode 7 from dmg file by double clicking the Xcode icon, I got the famous GUI with the Xcode icon on one side the the application icon on the other size.
However, as you can see below, there's "non entry sign" over the Xcode icon, which prevent me from dragging it to the /Application folder.
Trying to do it manually, by opening Xcode.app from the mount point, I got the following error :
LSOpenURLsWithRole() failed with error -10825 for the file /Volumes/Xcode/Xcode.app
On other computer, I did the same experiment with the exact dmg file, and it worked. Any idea what can lead to this problem ?
A:
According to the App Store listing for Xcode 7.1.1, OS X 10.10.5 or later is required.
Compatibility: OS X 10.10.5 or later
You need to update OS X on your development machine, or use an earlier version of Xcode.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to execute Azure DevOps .NET Core CLI task with arguments
On Azure DevOps, I want to configure the .NET Core CLI task so that it executes restore with runtime win-x86.
I tried this configuration:
- task: DotNetCoreCLI@2
displayName: 'Restore NuGet'
inputs:
command: 'restore'
projects: './src/MySolution.sln'
feedsToUse: 'config'
nugetConfigPath: './NuGet.config'
arguments: '--runtime win-x86'
...which I thought would add --runtime win-x86 to the executed command. However, the command that gets executed...
/usr/bin/dotnet restore /home/vsts/work/1/s/./src/MySolution.sln --configfile /home/vsts/work/1/Nuget/tempNuGet_158.config --verbosity Detailed
...is missing the runtime option.
On Azure DevOps, is is possible to execute the .NET Core CLI task so that it executes restore with runtime win-x86?
I first tried to determine if there was something wrong with the documentation of the .NET Core CLI task by creating this issue, but it was closed without any dialog, and I was essentially told to post my question on SO instead.
A:
I don't know why, but it look like the version 2 of the task DotNetCoreCLI can't take another arguments in the restore command.
Switch the version to 1 - DotNetCoreCLI@1 and it will work:
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use Numeric[T] to represent zero of any numeric type
I have a piece of Scala code that I'd like to make more generic. I know that Numeric[T] exists, but I'm not sure how to use it.
def sumMaps[A](m1: Map[A, Long], m2: Map[A, Long]): Map[A, Long] = {
m1 ++ m2.map { case (k, v) => k -> (v + m1.getOrElse(k, 0L)) }
}
def sumMaps[A](m1: Map[A, Int], m2: Map[A, Int]): Map[A, Int] = {
m1 ++ m2.map { case (k, v) => k -> (v + m1.getOrElse(k, 0)) }
}
def sumMaps[A](m1: Map[A, Double], m2: Map[A, Double]): Map[A, Double] = {
m1 ++ m2.map { case (k, v) => k -> (v + m1.getOrElse(k, 0)) }
}
I'd like to write something like this (just once), where the zero value gets auto-converted to a B type.
def sumMaps[A, B: Numeric[?]](m1: Map[A, B], m2: Map[A, B]): Map[A, B] = {
m1 ++ m2.map { case (k, v) => k -> (v + m1.getOrElse(k, 0)) }
}
A:
Try
def sumMaps[A, B](m1: Map[A, B], m2: Map[A, B])(implicit num: Numeric[B]): Map[A, B] = {
m1 ++ m2.map { case (k, v) => k -> num.plus(v, m1.getOrElse(k, num.zero)) }
}
or
import Numeric.Implicits._
def sumMaps[A, B](m1: Map[A, B], m2: Map[A, B])(implicit num: Numeric[B]): Map[A, B] = {
m1 ++ m2.map { case (k, v) => k -> (v + m1.getOrElse(k, num.zero)) }
}
or
def sumMaps[A, B: Numeric](m1: Map[A, B], m2: Map[A, B]): Map[A, B] = {
val num = implicitly[Numeric[B]]
import num._
m1 ++ m2.map { case (k, v) => k -> (v + m1.getOrElse(k, zero)) }
}
The imports provide implicit conversion infixNumericOps
m1 ++ m2.map { case (k, v) => k -> (infixNumericOps(v) + m1.getOrElse(k, num.zero)) }
so we do not have to explicitly use Numeric.plus like in the first example.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why isn't the Ito integral just the Riemann-Stieltjes integral?
Why isn't the Ito integral just the Riemann-Stieltjes integral?
What I mean is, given a continuous function $f$, some path of standard brownian motion $B$, and the integral:
$$\int_0^Tf(t)\;dB(t).$$
So what if we can't apply the change of variables formula to make sense of
$$\int_0^Tf(t)B'(t)\;dt,$$
the Riemann-Stieltjes integral never required differentiability of the integrator anyways.
Is there a reason to distinguish the Ito integral from the Riemann-Stieltjes integral above and beyond the need to develop a theory (Ito Calculus) to get around all the problems caused by the failure of change of variables?
A:
First of all, Brownian motion is almost surely nondifferentiable meaning that you can't just apply the rule you cite to Stieltjes integrals.
Second, in essence the Ito integral is Riemann Stieltjes integration when you observe the path of Brownian motion, but not entirely. You can think of it as Stieltjes integration where the "integrator" as you call it has an extra variable of dependence, in this case on the probability space of realizable Brownian paths. Specifically $B_t$ is a random variable. The definition is then essentially the same as its a limit over partitions. However Brownian motion is not of bounded variation so you cannot apply the usual definitions of Riemann Stieltjes to evaluate the integrals along some realized path. In particular you get the integral evaluated as a limit of sums over partitions converges in probability.
A:
You can't simply integrate with regards to Brownian motion pathwise because it's not of bounded variation (because such functions are differentiable almost everywhere) and functions of bounded variation are precisely those with respect to which you can compute the Riemann–Stieltjes integrals.
| {
"pile_set_name": "StackExchange"
} |
Q:
Передать переменную в html
На php пишу:
$name = $row['first_name'];
$welcomeblock = file_get_contents('./blocks/profile/welcome.min', true);
require_once('./blocks/profile/profile.min');
Происходит так, что выводится profile.min, где такой код:
<div class="frame">
<?php
echo $welcomeblock;
?>
</div>
То есть читается php переменная, которая выводится через html. Здесь все в порядке. Дальше читается welcomeblock из файла welcome.min, а там:
<div id = "startpage">
Здравствуйте, <?php echo $name; ?>!<br>
Выберите пункт в меню
</div>
И вот на этом месте после здравствуйте ничего не выводится, хотя php получает не пустой name. Что можно сделать, чтобы имя все-таки выводилось?
Все то же самое с любыми другими переменными, которые были получены таким образом: переменная из php в блок кода из php, который подгружается в общий код
A:
Тут скорее всего дело в том что вы получаете СОДЕРЖИМОЕ welcome.min, которое, в отличии от profile.min, не включается в исполняемый скрипт, соответственно и не исполняется интерпретатором. Могу быть не точен, но насколько мне известно, когда вы подключаете файл при помощи require - он становится частью скрипта. То есть это то же самое что вставить в место строчки require_once('./blocks/profile/profile.min') содержимое этого файла, поэтому для файлов подключенных при помощи require_once происходит выполнение всех php инструкций. Решить данную проблему, как мне кажется, можно следующими способами:
1) В файле, содержимое которого вы получаете при помощи file_get_contents, вместо php инструкций использовать некие ключевые слова (например, {name}), означающие переменные, которые потом можно будет заменить на значения этих самых переменных при помощи функции str_replace.
$welcomeblock = str_replace(['{name}','{surname}'],[$name,$surname],$welcomeblock);
2) Подключать файл welcome.min при помощи того же require или include, но при этом использовать перед подключением ob_start(); чтобы при подключении файла все что будет отдано им, не выводилось но было возвращено как строка при помощи функции ob_get_clean();, которую следует вызвать после.
| {
"pile_set_name": "StackExchange"
} |
Q:
I keep getting errors when trying to execute a stored procedure
I have a stored procedure which is supposed to update two tables, and it is defined as follows
CREATE procedure ChangeNames
@oldname nvarchar(100),
@newname nvarchar(100),
@tablename nvarchar(100)
AS
Begin
Declare @sql nvarchar(max);
Set @sql = 'UPDATE' + @tablename + 'SET NAMES =' + @newname + 'where
names =' + @oldname +
'UPDATE ref_names SET NAMES =' + @newname + 'where names =' + @oldname
Execute sp_executesql @sql
End`
I then execute the procedure as follows:
USE [database_name]
GO
exec dbo.ChangeNames
@oldname = 'ab',
@newname = 'cd',
@tablename = 'ef'
GO
I get the following error:
Incorrect syntax near '='.
How can I fix this?
A:
You are missing a few spaces between keywords and single quotes and when delimiting literal values:
Set @sql = '
UPDATE ' + @tablename + ' SET
NAMES = ''' + @newname + '''
WHERE
names = ''' + @oldname + '''
UPDATE ref_names SET
NAMES = ''' + @newname + '''
WHERE
names = ''' + @oldname + ''''
It's recommended to use PRINT to check the generated SQL before executing dynamic SQL, you will be able to spot these mistakes.
PRINT (@sql)
-- Execute sp_executesql @sql
Also add QUOTENAME to object names, like your dynamic table reference. The object name might have characters that break your dynamic SQL, such as spaces. Using QUOTENAME will correctly escape them.
Set @sql = 'UPDATE ' + QUOTENAME(@tablename) + --...
One last thing, make sure the value you are passing to search and update have escaped single quotes as they will also break your dynamic SQL otherwise.
So if you want to update values to FLIGHT CENTRE's TRAVEL GROUP (note the single quote in the middle) you will have to actually write FLIGHT CENTRE''s TRAVEL GROUP so the quote is escaped correctly.
| {
"pile_set_name": "StackExchange"
} |
Q:
+exposeBinding not working
I'm trying to expose a custom binding in an subclass of an NSWindowController. I added the following code to the subclass:
+(void)initialize { [self exposeBinding:@"customBinding"]; }
Then, in IB, I have an object instance of my subclass. But, when I look at the bindings of the custom NSWindowController, I don't see the 'customBinding' exposed. Am I missing something?
A:
These methods are for use in legacy Interface Builder plug-ins only. Xcode 4 doesn't officially support plug-ins. You have create these bindings in code using -bind:toObject:withKeyPath:options:. The “type whatever you like” part only applies to the key paths you bind to, not to the binding names themselves.
| {
"pile_set_name": "StackExchange"
} |
Q:
Grails domain class fields nullable validator decided by other fields
For example, I have a domain class called:
class Employee {
boolean belongToDepartment
Department department
static constraints = {
department ????
}
}
I want to write a validator for department which is if the field belongToDepartment is true, department is not null, otherwise department can be null.
I am not sure whether this is make sense?
A:
You can use custom validator on department to check if the boolean flag on the domain object is true and the department value is null. In that case it is a constraint failure, you can return false or an error code depending your need.
static constraints = {
department nullable: true, validator: {dep, obj ->
return !(obj.belongToDepartment && !dep)
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Когда правильнее делать дамп MySQL?
Есть курсовая работа. Тема курсовой работы "Автоматизированная система ЗАГС". Ну можно сказать работу я закончил, но так как данные ЗАГСа очень важны, вот я и решил написать скрипт который сделал бы dump базы данных.
Когда правильнее делать dump? Может каждый час или после каждого рабочего дня или может после каждого изменения в базе данных?
A:
Есть два варианта, которые вам стоит рассмотреть, если вы хотите обеспечить сохранность вашей базы данных.
Действительно, делать бекап базы данных. Частоту выбирать согласно тому, насколько проблемно реально потом будет восстановить данные руками либо вашими, либо персонала, введенные за текущий / предыдущий день. Но имейте ввиду, что дамп подразумевает остановку работы с базой.
Настроить репликацию, которая позволит иметь копию базы данных на момент отказа основного сервера. Руководств в сети полно, ищутся по запросу mysql репликация.
Естественно, что при желании вы можете и совместить их. При этом в случае совмещения дамп можно делать на slave-сервере, в таком случае отпадет необходимость останавливать работу с master-сервером.
A:
Обычно для значимых данных используют комбинацию из нескольких способов:
Бэкап базы данных. Для важных данных делают ежедневно (точнее каждую ночь, когда меньше нагрузка на базу). А в случае ЗАГСа это еще лучше, т.к. там ночью не будет никаких изменений базы.
Для данных, которые поступают уже после крайнего бэкапа лучше использовать временное хранилище. Т.е. при записи данных, они пишутся в основную базу и временное хранилище. Сразу после ночного бэкапа временное хранилище очищается. Репликацию использовать нужно, но она предназначена немного для другого. При падении базы да, она спасает ситуацию, но в случае неверной записи или преднамеренного изменения/удаления данных она перезапишет изменения в копии базы и информация будет безвозвратно удалена.
| {
"pile_set_name": "StackExchange"
} |
Q:
We need better ways to explain to users how the site should work
Coming from this post, people (possibly me) apparently don't understand what a good answer is and when it should happen. It is starting to get out of hand in the comments and I thought maybe a meta discussion would be a good place to point them or to correct me if I'm wrong.
Basically, the OP asked a question and there still isn't enough information to answer efficiently. I have commented and voted to close as is appropriate. I have downvoted all of the answers and commented on why (which seems to be a rarity these days). These answers are guesses and this hurts the site, the OP, and others.
Why?
The OP may get steered in the wrong direction since he is given information that may or may not help to solve the problem.
Other people, seeing 3 similar "answers" may not bother to look at
it assuming it has been solved. One of these people may have been
able to help further.
The site will continue to get bad posts which may deteriorate the effectiveness of the site if not resolved
With the enormous amount of bad posts we get on SO (Qs and As) and all of the posts on meta addressing that or people asking why their post is so bad or why they get downvotes, I think situations like this are important for the "higher rep" users to understand how we should handle "answers".
These may or may not help the OP but they most likely won't be all that helpful to future visitors which is a big part of our goal (to build an efficient Q&A DB).
Goal of the post
I would like someone to point out if they think I handled this inappropriately and if not then maybe us "higher rep" users can be more effective when viewing these posts. There are now at least 7 (The OP, 3 answerers, 2 commenters, and me) users associated with this post so I think everyone could gain from this discussion. Or maybe I'm frustrated with all of the bad posts and need to relax.
A:
The first action to reach for when encountering a question that is unclear, missing information or otherwise unanswerable is to close it.
That said, none of the answers on that question are "Not an Answer." They are all attempts at answering. Moderators will not remove answers that are actually answers, no matter how bad the answer is, unless it's clearly not adding any value, or is actively harmful. Bad answers should be downvoted, not moderator-flagged.
NullPointerException questions are a bit of a special case; they are all resolved in the same way: find the object you're attempting to dereference which is null. There exists a well-written Canonical/Reference question to close such questions as duplicates of; I've closed the question accordingly.
| {
"pile_set_name": "StackExchange"
} |
Q:
glReadPixels doesn't work for getting depth on OpenGL ES 1.0
I'm trying to get depth value from depth buffer with glReadPixels function. It always return 0 to me.
first of all, I create depth buffer attachment:
glGenFramebuffersOES(1, &viewFramebuffer);
glGenRenderbuffersOES(1, &viewRenderbuffer);
glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
[self.context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:(CAEAGLLayer*)self.layer];
glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, viewRenderbuffer);
glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth);
glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight);
if (USE_DEPTH_BUFFER)
{
glGenRenderbuffersOES(1, &depthRenderbuffer);
glBindRenderbufferOES(GL_RENDERBUFFER_OES, depthRenderbuffer);
glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, backingWidth, backingHeight);
glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthRenderbuffer);
}
then I call glReadPixels function to get the depth value from depth buffer:
float depth = 0.0f;
glReadPixels(point.x, self.renderUIView.frame.size.height - point.y, 1, 1, GL_DEPTH_COMPONENT16_OES, GL_FLOAT, &depth);
but it doesn't work, the depth value always is 0. I try to get error code from glGetError(), It return 1280. Is anything I missed to setup?
A:
What you are trying isn't supported in OpenGL ES (any API version) - there is no means to use glReadPixels on depth buffers.
Also in general note that using glReadPixels for any real 3D game as part of your main rendering loop is a "really bad idea" - it forces a pipeline flush which will totally kill your performance.
| {
"pile_set_name": "StackExchange"
} |
Q:
using javascript & jquery to access header attribute
I'm trying to access an attribute of the head tag with a script that's placed within the head.
<head myattr="123">
<script src="/Scripts/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
alert($("head").attr("myattr"));
</script>
...
I cannot use includes or <%#"123%> or <%="123%> in .net "because of code execution order & page header dabinding. So i just set header attribute from code-behind.
Anyway the question is: is there something wrong with the way i'm approaching the problem?
Is it possible that when i call alert($("head").attr("myattr")); that i could get an undefined response?
I'm assuming that since <head myattr="123"> happens before the alert(...) script is called, i won't get an undefined alert ... am i assuming wrong?
EDIT: Forgot to mention. Can't use $(document).ready(... it has to execute in the header.
I'm basically concerned if there are any unknowns such as compatibility issues etc that i'm not taking into considerations. Maybe some browsers will return undefined some not? maybe it can execute too early in some cases?
A:
It's fine, since your script is after/within the head tag. However, myattr makes your HTML invalid.
| {
"pile_set_name": "StackExchange"
} |
Q:
Finite State Machine in Scheme
I am trying to finish a finite state machine in Scheme. The problem is, that I am not sure how to tell it what characters it should test. If I want to test a String "abc112" then how do I do that?
Here is the code:
#lang racket
(define (chartest ch)
(lambda (x) (char=? x ch)))
;; A transition is (list state char!boolean state)
(define fsmtrlst
(list
(list 'start char-alphabetic? 'name)
(list 'start char-numeric? 'number)
(list 'start (chartest #\() 'lparen)
(list 'start (chartest #\)) 'rparen)
(list 'name char-alphabetic? 'name)
(list 'name char-numeric? 'name)
(list 'number char-numeric? 'number)))
(define (find-next-state state ch trl)
(cond
[(empty? trl) false]
[(and (symbol=? state (first (first trl)))
((second (first trl)) ch))
(third (first trl))]
[else (find-next-state state ch (rest trl))]))
(define fsmfinal '(name number lparen rparen))
(define (run-fsm start trl final input)
(cond
[(empty? input)
(cond
[(member start final) true]
[else false])]
[else
(local ((define next (find-next-state start (first input) trl)))
(cond
[(boolean? next) false]
[else (run-fsm next trl final (rest input))]))]))
And here is the launch code which I am trying to test:
(fsmtrlst (list 'start (lambda (abc112) (char=? abc112 ))))
EDIT:
ok,.. the overall product is okey, but my tutor is not happy with it,.. he wants me to make a finite state machine with transition function -> something like a global definition which would say: when in state X comes character Y go to Z ... and then i will test a list of characters to see if it is false or true ... So the only difference is that the code shouldn't be specific to use only numbers and letters but any character... is it somehow possible? thank you for your answer
EDIT 2: now I have the basic info how it should look like:
That is, the machine looks like
A ---------> B ----------> C ----------> D ----------> (E)
letter number number letter
(define fsmtrlst
(list
(list 'A char-alphabetic? 'B)
(list 'B char-numeric? 'C)
(list 'C char-numeric? 'D)
(list 'D char-alphabetic 'E)))
(define fsmfinal '(E))
(define fsmstart 'A)
but i am not sure how to write the definition of fsmstart.
Thank you for answers.
This accepts sequences of exactly four characters which are letter, number, number, letter, and nothing else.
EDIT 3: I am using tutorials online and a book that my mentor teacher provided. I figured out the fsm I wanted to make. Thank you for your help.
Just out of curiosity:
How would differ to have rather specific fsm?
Example:
START ----"b"-----> STATE A -----"a" ----> STATE B -----"c"-----> FINAL STATE
That the fsm would be true only when the list of characters is "bac" and nothing else.
Is it possible?
Thank you for your feedback.
EDIT 4:
Ok, I managed to do write but once again, I am not sure how to make the input of characters. This is the code:
There are 3 states but it will be true only when going from state A to state C.
(define (chartest ch)
(lambda (x) (char=? x ch)))
(define fsm-trans
'((A, "a", B), (A, "b", A), (B, "c", C)))
(define (find-next-state state ch trl)
(cond
[(empty? trl) false]
[(and (symbol=? state (first (first trl)))
((second (first trl)) ch)) <- And also this line returns an error
(third (first trl))]
[else (find-next-state state ch (rest trl))]))
(define fsm-final '(C))
(define start-state 'A)
(define (run-fsm start trl final input)
(cond
[(empty? input)
(cond
[(member start final) true]
[else false])]
[else
(local ((define next (find-next-state start (first input) trl)))
(cond
[(boolean? next) false]
[else (run-fsm next trl final (rest input))]))]))
(run-fsm start-state fsm-trans fsm-final (list '("a", "c"))) <- I know this is the last problem with the code, the definition of the input. How can I tell Scheme what characters I want to test?
Thank you for your answer!!!
A:
I am curious: I take it you did not write this fsm? Is this for a homework assignment or are you trying to teach yourself? The code for the FSM looks fine (quite fine, in fact). However, your launch line:
(fsmtrlst (list 'start (lambda (abc112) (char=? abc112 ))))
Makes no sense. Here is why: fsmtrlst is the finite state machine transition list. It was defined in the first big block of code. It is not a function to be called. I believe the function you want to call is run-fsm. That takes a start symbol, a transition list, a list of final states, and an input. The input is not actually a string, but a list. As a consequence, you can launch it with the following line:
(run-fsm 'start fsmtrlst fsmfinal (string->list "abc112"))
That will call run-fsm with the defined transition list fsmtrlst, the defined list of final states, and the input-ready form of the string "abc112".
Incidentally, everything except 'start is defined to be a final (accepting) state. Not all inputs are accepting inputs, though. For example, replacing "abc122" with "abc(122" is not accepted.
Is this what you want?
Update:
Your edit has clarified things. Your definition of fsmstart is fine. You did miss a question mark (?) on one of your char-alphabetic? usages in fsmtrlst. Is your confusion that you don't know how to use your new definitions? First, you should remove the old definitions of fsmtrlst and fsmfinal. Otherwise, you will likely get a duplicate definition error. From your new definition, your line to execute should look like:
(run-fsm fsmstart fsmtrlst fsmfinal (string->list "w00t"))
This will return #t, because "w00t" is a character followed by two numbers, followed by a character.
I speculate that you are still having difficulty with the syntax rules of scheme, and not just problems with the logic of your particular program. You might want to try a simpler exercise.
UPDATE 2: Shouldn't you consider formulating a new question?
Your most recent update has broken the code. The transition portion of the fsm worked because transitions were defined as a list:
(from-state test-function to-state)
You have attempted to create a transition:
(from-state string-literal to-state)
You could change (A, "a", B) to (A (lambda (x) (string=? x "a") B).
When you tried to invoke your function, you took a function that expected a list of characters and gave it a list of list of strings. These are not the same thing. Also, did you notice that you put commas in your lists, but they existed nowhere else in the code? These mistakes are why I suggest you begin a scheme tutorial. These are basic scheme problems, unrelated to your particular exercise. I suggest you rewind your edits to what you had yesterday.
Unfortunately, I can no longer update this answer. I wanted to update my answer so that if someone came along your question with similar concerns, they would see a complete answer. However, you have provided a moving target. Please consider halting your edits and submit a new question when you have one.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create a OData List?
I want to create a OList, so that every position opened a new OList if I tap on it. At this moment I have following code:
function readCustomerSuccessCallback(data, response) {
var citems = [];
for (var i = 0; i < data.results.length; i++) {
var citem = new sap.m.StandardListItem(
{
type: "Active",
tap : readProducts(data.results[i].STATION_ID),
title: data.results[i].CUSTOMER_NAME,
description: data.results[i].STATION_ID
});
citems.push(citem);
}
var oList = new sap.m.List({
headerText : "Customers",
setGrowingScrollToLoad: true,
items : citems,
press: function(e) {
console.log(oList.getSelectedItems());
}
});
oList.placeAt("content"); // place model onto UI
}
function readProducts(category) {
console.log("read request started");
startTime = new Date();
if (!haveAppId()) {
return;
}
sURL = myUrl;
var oHeaders = {};
oHeaders['Authorization'] = authStr;
//oHeaders['X-SMP-APPCID'] = appCID; //this header is provided by the logon plugin
var request = {
headers : oHeaders,
requestUri : sURL,
method : "GET"
};
OData.read(request, readProductsSuccessCallback, errorCallback);
}
The function read CustomerSuccesCAllback creates a OList,and if I tap on a field of this list, I want that a new List shows up. For the second step is the function readproducts responsible.
With this code it doesnt work. It shows me not the customers, but only theyre details.
Has anybody an idea?
A:
Change in readCustomerSuccessCallback:
tap: function(e){
readProducts(this.getDescription),
}
//this will stop invoking the function while defining your items
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is 'UnhandledAlertException' still being outputted to the Console Window?
Why is 'UnhandledAlertException' still being outputted to the Console Window?
I have the methods listed below, which use TestNG 'Before' and 'After' method to close modal popups,
but why is 'UnhandledAlertException' still being outputted to the console window even when im ignoring unhandled alert exceptions.
TestNG Invoked Methods:
@BeforeMethod(alwaysRun = true)
public void closeModalPopup() throws Exception {
basePage.closeModalPopup();
}
@AfterMethod(alwaysRun = true)
public void closeModalPopup2() throws Exception {
basePage.closeModalPopup();
}
Main methods created to close popups etc:
public void waitUntilModalDisapears() {
WebDriverWait tempWait = new WebDriverWait(this.driver, 60);
try {
tempWait.until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector(".modal-body")));
} catch (UnhandledAlertException e) {
// Do nothing
} catch (StaleElementReferenceException e) {
// do nothing
} catch (NullPointerException e) {
// do nothing
} catch (Exception e) {
// do nothing
}
}
/** Modal Closer **/
public void closeModalPopup() throws InterruptedException {
int attempts = 0;
while (attempts < 10) {
try {
jsExecutor.executeScript("var p=document.querySelector('.modal.fade.in button.close span'); if ( p) p.click();");
} catch (UnhandledAlertException e) {
//Do nothing
} catch (StaleElementReferenceException e) {
//do nothing
} catch (NullPointerException e) {
// do nothing
} catch (Exception e) {
// do nothing
}
attempts++;
waitUntilModalDisapears();
}
}
Jenkins Console Output:
11:48:48 Jun 01, 2017 11:48:48 AM org.openqa.selenium.support.ui.ExpectedConditions findElement
11:48:48 WARNING: WebDriverException thrown by findElement(By.cssSelector: .modal-body)
11:48:48 org.openqa.selenium.UnhandledAlertException: unexpected alert open: {Alert text : Click OK to confirm your personal message is correct as this is exactly how it will be printed.}
11:48:48 (Session info: chrome=58.0.3029.110)
11:48:48 (Driver info: chromedriver=2.29.461591 (62ebf098771772160f391d75e589dc567915b233),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
11:48:48 Command duration or timeout: 31 milliseconds: null
11:48:48 Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
11:48:48 System info: host: 'DEV007', ip: '172.16.2.192', os.name: 'Windows Server 2008 R2', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_131'
11:48:48 Driver info: org.openqa.selenium.chrome.ChromeDriver
11:48:48 Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.29.461591 (62ebf098771772160f391d75e589dc567915b233), userDataDir=C:\Users\GIANNI~1.BRU\AppData\Local\Temp\3\scoped_dir6676_5813}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=58.0.3029.110, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=ignore}]
11:48:48 Session ID: 738b699457547ad20f328acd1580afab
11:48:48 *** Element info: {Using=css selector, value=.modal-body}
11:48:48 at sun.reflect.GeneratedConstructorAccessor17.newInstance(Unknown Source)
11:48:48 at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
11:48:48 at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
11:48:48 at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:215)
11:48:48 at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:173)
11:48:48 at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:671)
11:48:48 at org.openqa.selenium.remote.RemoteWebDriver.findElements(RemoteWebDriver.java:437)
11:48:48 at org.openqa.selenium.remote.RemoteWebDriver.findElementsByCssSelector(RemoteWebDriver.java:505)
11:48:48 at org.openqa.selenium.By$ByCssSelector.findElements(By.java:441)
11:48:48 at org.openqa.selenium.remote.RemoteWebDriver.findElements(RemoteWebDriver.java:398)
11:48:48 at org.openqa.selenium.support.ui.ExpectedConditions.findElement(ExpectedConditions.java:882)
11:48:48 at org.openqa.selenium.support.ui.ExpectedConditions.access$000(ExpectedConditions.java:44)
11:48:48 at org.openqa.selenium.support.ui.ExpectedConditions$20.apply(ExpectedConditions.java:580)
11:48:48 at org.openqa.selenium.support.ui.ExpectedConditions$20.apply(ExpectedConditions.java:576)
11:48:48 at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:209)
11:48:48 at BuyAGiftFramework.pageObjects.Base_Page.waitUntilModalDisapears(Base_Page.java:706)
11:48:48 at BuyAGiftFramework.pageObjects.Base_Page.closeModalPopup(Base_Page.java:734)
11:48:48 at BuyAGiftFramework.utilities.BrowserFactory.closeModalPopup2(BrowserFactory.java:417)
11:48:48 at sun.reflect.GeneratedMethodAccessor8.invoke(Unknown Source)
11:48:48 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
11:48:48 at java.lang.reflect.Method.invoke(Method.java:498)
11:48:48 at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
11:48:48 at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:564)
11:48:48 at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:213)
11:48:48 at org.testng.internal.Invoker.invokeMethod(Invoker.java:786)
11:48:48 at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
11:48:48 at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
11:48:48 at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
11:48:48 at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
11:48:48 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
11:48:48 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
11:48:48 at java.lang.Thread.run(Thread.java:748)
11:48:48
11:48:48 Jun 01, 2017 11:48:48 AM org.openqa.selenium.support.ui.ExpectedConditions findElement
11:48:48 WARNING: WebDriverException thrown by findElement(By.cssSelector: .modal-body)
11:48:48 org.openqa.selenium.UnhandledAlertException: unexpected alert open: {Alert text : Click OK to confirm your personal message is correct as this is exactly how it will be printed.}
11:48:48 (Session info: chrome=58.0.3029.110)
11:48:48 (Driver info: chromedriver=2.29.461591 (62ebf098771772160f391d75e589dc567915b233),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
11:48:48 Command duration or timeout: 0 milliseconds: null
11:48:48 Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
11:48:48 System info: host: 'DEV007', ip: '172.16.2.192', os.name: 'Windows Server 2008 R2', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_131'
11:48:48 Driver info: org.openqa.selenium.chrome.ChromeDriver
11:48:48 Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.29.461591 (62ebf098771772160f391d75e589dc567915b233), userDataDir=C:\Users\GIANNI~1.BRU\AppData\Local\Temp\3\scoped_dir6676_5813}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=58.0.3029.110, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=ignore}]
11:48:48 Session ID: 738b699457547ad20f328acd1580afab
11:48:48 *** Element info: {Using=css selector, value=.modal-body}
11:48:48 at sun.reflect.GeneratedConstructorAccessor17.newInstance(Unknown Source)
11:48:48 at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
11:48:48 at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
11:48:48 at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:215)
11:48:48 at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:173)
11:48:48 at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:671)
11:48:48 at org.openqa.selenium.remote.RemoteWebDriver.findElements(RemoteWebDriver.java:437)
11:48:48 at org.openqa.selenium.remote.RemoteWebDriver.findElementsByCssSelector(RemoteWebDriver.java:505)
11:48:48 at org.openqa.selenium.By$ByCssSelector.findElements(By.java:441)
11:48:48 at org.openqa.selenium.remote.RemoteWebDriver.findElements(RemoteWebDriver.java:398)
11:48:48 at org.openqa.selenium.support.ui.ExpectedConditions.findElement(ExpectedConditions.java:882)
11:48:48 at org.openqa.selenium.support.ui.ExpectedConditions.access$000(ExpectedConditions.java:44)
11:48:48 at org.openqa.selenium.support.ui.ExpectedConditions$20.apply(ExpectedConditions.java:580)
11:48:48 at org.openqa.selenium.support.ui.ExpectedConditions$20.apply(ExpectedConditions.java:576)
11:48:48 at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:209)
11:48:48 at BuyAGiftFramework.pageObjects.Base_Page.waitUntilModalDisapears(Base_Page.java:706)
11:48:48 at BuyAGiftFramework.pageObjects.Base_Page.closeModalPopup(Base_Page.java:734)
11:48:48 at BuyAGiftFramework.utilities.BrowserFactory.closeModalPopup(BrowserFactory.java:412)
11:48:48 at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)
11:48:48 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
11:48:48 at java.lang.reflect.Method.invoke(Method.java:498)
11:48:48 at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
11:48:48 at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:564)
11:48:48 at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:213)
11:48:48 at org.testng.internal.Invoker.invokeMethod(Invoker.java:653)
11:48:48 at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
11:48:48 at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
11:48:48 at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
11:48:48 at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
11:48:48 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
11:48:48 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
11:48:48 at java.lang.Thread.run(Thread.java:748)
11:48:48
A:
Probably in your catch{UnhandledAlertException e) block handle it by providing:
Alert alert = driver.switchTo().alert();
alert.accept();
| {
"pile_set_name": "StackExchange"
} |
Q:
Using a private auto property instead of a simple variable for a programming standard
In a discussion with a peer, it was brought up that we should consider using auto properties for all class level variables... including private ones.
So in addition to a public property like so:
public int MyProperty1 { get; set; }
Our private class-level variables would look like this:
private int MyProperty2 { get; set; }
Instead of:
private int _myProperty2;
I'm on the fence about why someone would want to do this but I can't decide if my reluctance to accept this is because of my own internal brainwashing with how I write my code to the same programming standards and naming conventions I've used for 10 years or because I've never seen this before (for a reason).
I realize it's extra code to type but to be honest, when using auto-properties, I don't think I've ever typed it out due to the 'prop' and 'propg' snippets so it'd be very simple to set up a new snippet to create a private auto property so the extra code doesn't bother me too much since I never have to type it.
Other than aesthetics which may just be my subconscious, are there any issues that could result from using fully private auto properties? Are there any good reasons to do this or not to do it? I've seen a lot of code in my day on stackoverflow, codeplex, codeproject, etc. and I've never seen anyone use this standard.... is there a reason why?
A:
Private auto-properties are completely pointless, in my opinion. What value does a private auto-property provide that a plain field doesn't?
(It's different when the auto-property is only partially private -- eg, a public/protected getter with a private setter -- or when you use a private non-automatic property to enable you to wrap additional code around the getter/setter.)
A:
This does not make too much sense.
I can think of a 'benefit':
you can later add logic to the getter and/or setter and be sure it is always passed
but frankly your classes should not become so big that this is useful.
"are there any issues" ?
Your properties won't work as arguments to ref or out parameters.
A:
It's not nearly as useful for privates as for publics.
Suppose you took your automatic private property and later built some logic into it (being able to do that without breaking anything is the whole point of auto props)...
This would require you to create a private backing member for the property to wrap.
So now you've got two different private ways (member and property) of doing the same thing though one has hidden side effects (the property) and you've now also got the problem of ensuring none of your other methods in the class access that member directly.
Ends up being much more of a headache than just using a private member from the beginning.
| {
"pile_set_name": "StackExchange"
} |
Q:
Write a dataframe formatted to a csv sheet
I am having a dataframe which looks like that:
> (eventStudyList120_After)
Dates Company Returns Market Returns Abnormal Returns
1 25.08.2009 4.81 0.62595516 4.184045
2 26.08.2009 4.85 0.89132960 3.958670
3 27.08.2009 4.81 -0.93323011 5.743230
4 28.08.2009 4.89 1.00388875 3.886111
5 31.08.2009 4.73 2.50655343 2.223447
6 01.09.2009 4.61 0.28025201 4.329748
7 02.09.2009 4.77 0.04999239 4.720008
8 03.09.2009 4.69 -1.52822071 6.218221
9 04.09.2009 4.89 -1.48860354 6.378604
10 07.09.2009 4.85 -0.38646531 5.236465
11 08.09.2009 4.89 -1.54065680 6.430657
12 09.09.2009 5.01 -0.35443455 5.364435
13 10.09.2009 5.01 -0.54107231 5.551072
14 11.09.2009 4.89 0.15189458 4.738105
15 14.09.2009 4.93 -0.36811321 5.298113
16 15.09.2009 4.93 -1.31185921 6.241859
17 16.09.2009 4.93 -0.53398643 5.463986
18 17.09.2009 4.97 0.44765285 4.522347
19 18.09.2009 5.01 0.81109101 4.198909
20 21.09.2009 5.01 -0.76254262 5.772543
21 22.09.2009 4.93 0.11309704 4.816903
22 23.09.2009 4.93 1.64429117 3.285709
23 24.09.2009 4.93 0.37294212 4.557058
24 25.09.2009 4.93 -2.59894035 7.528940
25 28.09.2009 5.21 0.29588776 4.914112
26 29.09.2009 4.93 0.49762314 4.432377
27 30.09.2009 5.41 2.17220569 3.237794
28 01.10.2009 5.21 1.67482716 3.535173
29 02.10.2009 5.25 -0.79014302 6.040143
30 05.10.2009 4.97 -2.69996146 7.669961
31 06.10.2009 4.97 0.18086490 4.789135
32 07.10.2009 5.21 -1.39072582 6.600726
33 08.10.2009 5.05 0.04210020 5.007900
34 09.10.2009 5.37 -1.14940251 6.519403
35 12.10.2009 5.13 1.16479551 3.965204
36 13.10.2009 5.37 -2.24208216 7.612082
37 14.10.2009 5.13 0.41327193 4.716728
38 15.10.2009 5.21 1.54473332 3.665267
39 16.10.2009 5.13 -1.73781565 6.867816
40 19.10.2009 5.01 0.66416288 4.345837
41 20.10.2009 5.09 -0.27007314 5.360073
42 21.10.2009 5.13 1.26968917 3.860311
43 22.10.2009 5.01 0.29432965 4.715670
44 23.10.2009 5.01 1.73758937 3.272411
45 26.10.2009 5.21 0.38854011 4.821460
46 27.10.2009 5.21 2.72671890 2.483281
47 28.10.2009 5.21 -1.76846884 6.978469
48 29.10.2009 5.41 2.95523593 2.454764
49 30.10.2009 5.37 -0.22681024 5.596810
50 02.11.2009 5.33 1.38835160 3.941648
51 03.11.2009 5.33 -1.83751398 7.167514
52 04.11.2009 5.21 -0.68721323 5.897213
53 05.11.2009 5.21 -0.26954741 5.479547
54 06.11.2009 5.21 -2.24083342 7.450833
55 09.11.2009 5.17 0.39168239 4.778318
56 10.11.2009 5.09 -0.99082271 6.080823
57 11.11.2009 5.17 0.07924735 5.090753
58 12.11.2009 5.81 -0.34424802 6.154248
59 13.11.2009 6.21 -2.00230195 8.212302
60 16.11.2009 7.81 0.48655978 7.323440
61 17.11.2009 7.69 -0.21092848 7.900928
62 18.11.2009 7.61 1.55605852 6.053941
63 19.11.2009 7.21 0.71028798 6.499712
64 20.11.2009 7.01 -2.38596631 9.395966
65 23.11.2009 7.25 0.55334705 6.696653
66 24.11.2009 7.21 -0.54239847 7.752398
67 25.11.2009 7.25 3.36386413 3.886136
68 26.11.2009 7.01 -1.28927630 8.299276
69 27.11.2009 7.09 0.98053264 6.109467
70 30.11.2009 7.09 -2.61935612 9.709356
71 01.12.2009 7.01 -0.11946242 7.129462
72 02.12.2009 7.21 0.17152317 7.038477
73 03.12.2009 7.21 -0.79343095 8.003431
74 04.12.2009 7.05 0.43919792 6.610802
75 07.12.2009 7.01 1.62169804 5.388302
76 08.12.2009 7.01 0.74055990 6.269440
77 09.12.2009 7.05 -0.99504492 8.045045
78 10.12.2009 7.21 -0.79728245 8.007282
79 11.12.2009 7.21 -0.73784636 7.947846
80 14.12.2009 6.97 -0.14656077 7.116561
81 15.12.2009 6.89 -1.42712116 8.317121
82 16.12.2009 6.97 0.95988962 6.010110
83 17.12.2009 6.69 0.22718293 6.462817
84 18.12.2009 6.53 -1.46958638 7.999586
85 21.12.2009 6.33 -0.21365446 6.543654
86 22.12.2009 6.65 -0.17256757 6.822568
87 23.12.2009 7.05 -0.59940253 7.649403
88 24.12.2009 7.05 NA NA
89 25.12.2009 7.05 NA NA
90 28.12.2009 7.05 -0.22307263 7.273073
91 29.12.2009 6.81 0.76736750 6.042632
92 30.12.2009 6.81 0.00000000 6.810000
93 31.12.2009 6.81 -1.50965723 8.319657
94 01.01.2010 6.81 NA NA
95 04.01.2010 6.65 0.06111069 6.588889
96 05.01.2010 6.65 -0.13159651 6.781597
97 06.01.2010 6.65 0.09545081 6.554549
98 07.01.2010 6.49 -0.32727619 6.817276
99 08.01.2010 6.81 -0.07225296 6.882253
100 11.01.2010 6.81 1.61131397 5.198686
101 12.01.2010 6.57 -0.40791980 6.977920
102 13.01.2010 6.85 -0.53016383 7.380164
103 14.01.2010 6.93 1.82016604 5.109834
104 15.01.2010 6.97 -0.62552046 7.595520
105 18.01.2010 6.93 -0.80490241 7.734902
106 19.01.2010 6.77 2.02857647 4.741424
107 20.01.2010 6.93 1.68204556 5.247954
108 21.01.2010 6.89 1.02683875 5.863161
109 22.01.2010 6.90 0.96765669 5.932343
110 25.01.2010 6.73 -0.57603687 7.306037
111 26.01.2010 6.81 0.50990350 6.300096
112 27.01.2010 6.81 1.64994011 5.160060
113 28.01.2010 6.61 -1.13511086 7.745111
114 29.01.2010 6.53 -0.82206204 7.352062
115 01.02.2010 7.03 -1.03993428 8.069934
116 02.02.2010 6.93 0.61692305 6.313077
117 03.02.2010 7.73 2.53012795 5.199872
118 04.02.2010 7.97 1.96223075 6.007769
119 05.02.2010 9.33 -0.76549820 10.095498
120 08.02.2010 8.01 -0.34391479 8.353915
When I write it to a csv sheet it looks like that:
write.table(eventStudyList120_After$`Abnormal Returns`, file = "C://Users//AbnormalReturns.csv", sep = ";")
In fact I want to let it look like that:
So my question is:
How to write the data frame as it is into a csv and how to transpose the Abnormal return column and put the header as in the example sheet?
A:
Two approaches: transpose the data in R or in Excel
In R
Add an index column, select the columns you want and transpose the data using the function t
d <- anscombe
d$index <- 1:nrow(anscombe)
td <- t(d[c("index", "x1")])
write.table(td, "filename.csv", col.names = F, sep = ";")
Result:
"index";1;2;3;4;5;6;7;8;9;10;11
"x1";10;8;13;9;11;14;6;4;12;7;5
In Excel
Excel allows you to transpose data as well: http://office.microsoft.com/en-us/excel-help/switch-transpose-columns-and-rows-HP010224502.aspx
| {
"pile_set_name": "StackExchange"
} |
Q:
How to add a value in a matrix and make it decrease in radial way?
I got a matrix with odd lines and columns and all positions with 0 (zero) values, I want to add an X value (16 for example) at the center position of the matrix and make the other positions around to decrease an Y value (3 for example) but in a radial way, until those positions reach zero.
Like this image I created (I added colors just for better understanding):
I'm starting to work with matrices, I searched the web for something similar that could help but nothing very understandable. How that could be done? There is some for-loop trick to do this? Anyone had tried before? If someone could help I'll be grateful.
A:
[EDIT]
So based on you're edit i thought this solution. Since you don't specify any programming language i'll use some c-like functional programming. I'll leave you the work of transforming it to object oriented if you need it.
Input:
Global maxtrix that starts in M[0,0] and ends in M[100'000, 100'000] (Note that, to make it easier to understand, i want check if i reach board, you should check)
Position for first number (X,Y) (in your example 5,5)
First number called N (in your example 16)
Decrement for along axis D (in your example 3)
main(){
computeValues(M, X, Y, N, D)
}
computeValues(M, X, Y, N, D){
M[X,Y] = N
if( N-D <= 0 ) return;
if( M[X,Y-1] == 0 ){
computeValues(M, X, Y-1, N-D, D)
}
if( M[X,Y+1] == 0 ){
computeValues(M, X, Y+1, N-D, D)
}
if( M[X-1,Y] == 0 ){
computeValues(M, X-1, Y, N-D, D)
}
if( M[X+1,Y] == 0 ){
computeValues(M, X+1, Y, N-D, D)
}
}
It should be pretty self-explanatory, anyway this function ends when reach 0 with the N-D <= 0 control. Once a position recive the number, it check for near position not yet evaluated and assign them N-D number, the new position if N-D <= 0 will continue to check for near position not evaluated and so on...
IMPORTANT NOTE: This function return the matrix as you asked in the text of your answer, which is a little bit different from the image you posted (Example M[4,4] in your example is 11 but it should be 10 and M[5,0] should be 1)
OLD ANSWER
This should not to much difficult. The only things you missed to say is how to compute value by value.
To accomplish this algorithm you need to know (and tell us, if you want) the rule or maybe the function that allow as to get the right value.
An example to make my point clearer:
Y
Y X Y
Y
If X=17 how do we know if Y, for example, need to be 15 or 14?
[If you edit you're answer whit those information i'll try to answer you properly]
| {
"pile_set_name": "StackExchange"
} |
Q:
Angular 2/4 - Storing the Current User Object Details in front-end (rather than making continuous HTTP requests to back-end)
I would like an efficient way to store (and update) the current user details in the frontend, rather than making new HTTP GET requests to the backend whenever a new component is loaded.
I have added a UserService class which sets/updates a currentUser object when a method in the class is called.
import { Http, Response } from '@angular/http';
import { Injectable } from '@angular/core';
@Injectable()
export class UserService {
public currentUser: any;
constructor(private http: Http) { }
updateCurrentUser() {
this.http.get('api/login/currentUser').subscribe(data => {
this.currentUser = data;
});
}
}
I have found this method to cause a race condition problems. For example, an error occurs if the currentUser.username is requested in the profile component but the service class hasn't completed the request yet.
I've also tried checking if the currentUser is undefined and then calling the updateCurrentUser() but it doesn't seem to work.
if(this.userService.currentUser === undefined){
this.userService.updateCurrentUser();
}
Update:The error message shown in the browser console
Update on HTML used:
I am using data binding to display the username (calling it directly from the UserService class). E.g.
<span class="username-block">{{userService.currentUser.username}}</span>
I have also tried assigning the currentUser object to a variable within the component that I trying to display the username but it has the same result.
I would appreciate any help/feedback.
A:
You can try the Elvis/existential operator (I think that's the right name) in the html. The question mark after currentUser says don't bother trying to evaluate username if currentUser is undefined.
Assuming your async code will eventually fill it in, the page should then display it.
<span class="username-block">{{userService.currentUser?.username}}</span>
Edit
I just noticed you are outputting userService.currentUser.username. You may want to return an observable from the service to the component so that the data is reactive.
Something like,
updateCurrentUser() {
return this.http.get('api/login/currentUser')
.catch(error => this.handleError(error, 'currentUser'));
}
Then in the component,
private currentUser;
ngOnInit() {
this.userService.updateCurrentUser()
.take(1)
.subscribe(data => { this.currentUser = data });
}
and the html now refers to the local component copy, initially undefined but eventually filled in by the subscription. Note, take(1) is to close the subscription and avoid memory leaks.
<span class="username-block">{{currentUser?.username}}</span>
Edit #2
Apologies, your question asks about avoiding multiple HTTP calls.
In that case the service code should be
export class UserService {
private currentUser: any; // private because only want to access through getCurrentUser()
constructor(private http: Http) { }
getCurrentUser() {
return this.currentUser
? Observable.of(this.currentUser) // wrap cached value for consistent return value
: this.http.get('api/login/currentUser')
.do(data => { this.currentUser = data }) // cache it for next call
.catch(error => this.handleError(error, 'currentUser'));
}
A:
Are you using routing? If so, you could set up a route resolver on your first route that needs the user data. The resolver then always waits to display the view until the resolver data is retrieved.
For example, here is one of my route resolvers. Notice that it calls a service to retrieve the data.
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { IMovie } from './movie';
import { MovieService } from './movie.service';
@Injectable()
export class MovieResolver implements Resolve<IMovie> {
constructor(private movieService: MovieService) { }
resolve(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<IMovie> {
const id = route.paramMap.get('id');
return this.movieService.getMovie(+id);
}
}
The resolver is then added to the appropriate route, something like this:
{
path: ':id',
resolve: { movie: MovieResolver },
component: MovieDetailComponent
},
That route won't be displayed then until the data is retrieved.
| {
"pile_set_name": "StackExchange"
} |
Q:
Memory efficient way to manipulate images?
I have some code that takes two images and merges the middle section of them together into one image. The code works, but uses quite a lot of memory, so it fails on some devices that don't have enough memory.
Is there some way to make this code more memory efficient?
The code
private void convertImages(){
ImageView imageView = (ImageView) findViewById(R.id.imageView);
File leftFile = new File(Environment.getExternalStorageDirectory(), "images/left.jpg");
File rightFile = new File(Environment.getExternalStorageDirectory(), "images/right.jpg");
Bitmap left = BitmapFactory.decodeFile(leftFile.getAbsolutePath());
Bitmap right = BitmapFactory.decodeFile(rightFile.getAbsolutePath());
Rect srcRect = new Rect( (int)(left.getWidth()*0.25), 0, (int)(left.getWidth()*0.75), left.getHeight() );
Rect dstRectLeft = new Rect( 0, 0, (int)(srcRect.width()/2), srcRect.height() );
Rect dstRectRight = new Rect( (int)(srcRect.width()/2), 0, srcRect.width(), srcRect.height() );
Bitmap outBitmap = Bitmap.createBitmap(srcRect.width(), srcRect.height(), Bitmap.Config.ARGB_8888);
Canvas outCanvas = new Canvas(outBitmap);
outCanvas.drawBitmap(left, srcRect, dstRectLeft, null);
outCanvas.drawBitmap(right, srcRect, dstRectRight, null);
imageView.setImageBitmap( outBitmap );
}
A:
You can try compression. Try this helpful imagecompressor class, copied and pasted for your convenience into this thread:
Android: Compressing images creates black borders on left and top margin
The compressor java will compress your pictures to about 1/10 of their size so for a 3mb picture, it will become 300kb. Hopefully that will save you some memory.
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.media.ExifInterface;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import timber.log.Timber;
//http://voidcanvas.com/whatsapp-like-image-compression-in-android/
public class ImageCompressor {
public ImageCompressor() {}
public static String compressImage(String imagePath, Context context) {
Bitmap scaledBitmap = null;
String filename = "compressed_" +imagePath.substring(imagePath.lastIndexOf("/")+1);
BitmapFactory.Options options = new BitmapFactory.Options();
// by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If
// you try the use the bitmap here, you will get null.
options.inJustDecodeBounds = true;
Timber.e( "imagePath "+imagePath);
Timber.e("filename "+filename);
Bitmap bmp = BitmapFactory.decodeFile(imagePath, options);
if (options == null) {
Timber.e("zero bitmap");
}
int actualHeight = options.outHeight;
int actualWidth = options.outWidth;
float imgRatio = actualWidth / actualHeight;
float maxHeight = actualHeight * 10/20;
float maxWidth = actualWidth * 10/20;
float maxRatio = maxWidth / maxHeight;
// width and height values are set maintaining the aspect ratio of the image
if (actualHeight > maxHeight || actualWidth > maxWidth) {
if (imgRatio < maxRatio) {
imgRatio = maxHeight / actualHeight;
actualWidth = (int) (imgRatio * actualWidth);
actualHeight = (int) maxHeight;
} else if (imgRatio > maxRatio) {
imgRatio = maxWidth / actualWidth;
actualHeight = (int) (imgRatio * actualHeight);
actualWidth = (int) maxWidth;
} else {
actualHeight = (int) maxHeight;
actualWidth = (int) maxWidth;
}
}
// setting inSampleSize value allows to load a scaled down version of the original image
options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
// inJustDecodeBounds set to false to load the actual bitmap
options.inJustDecodeBounds = false;
// this options allow android to claim the bitmap memory if it runs low on memory
options.inPurgeable = true;
options.inInputShareable = true;
options.inTempStorage = new byte[16 * 1024];
try {
// load the bitmap from its path
bmp = BitmapFactory.decodeFile(imagePath, options);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
try {
scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
float ratioX = actualWidth / (float) options.outWidth;
float ratioY = actualHeight / (float) options.outHeight;
float middleX = actualWidth / 2.0f;
float middleY = actualHeight / 2.0f;
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
Canvas canvas = new Canvas(scaledBitmap);
canvas.setMatrix(scaleMatrix);
canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));
// check the rotation of the image and display it properly
ExifInterface exif;
try {
exif = new ExifInterface(imagePath);
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, 0);
Timber.e("Exif: " + orientation);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
Timber.e( "Exif: " + orientation);
} else if (orientation == 3) {
matrix.postRotate(180);
Timber.e( "Exif: " + orientation);
} else if (orientation == 8) {
matrix.postRotate(270);
Timber.e( "Exif: " + orientation);
}
scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix,
true);
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
FileOutputStream out = null;
try {
out = context.openFileOutput(filename, Context.MODE_PRIVATE);
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return filename;
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; }
final float totalPixels = width * height;
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
return inSampleSize;
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Keep Element At The Bottom Of the Parent ELEMENT
I have a simple animation. Take a look at it. http://jsfiddle.net/5wJ5D/
MY QUESTION:
How can I make the children elements stay at the bottom of the screen. After the animation goes for a while, all the elements eventually go to the bottom because eventually one of them is height:100%.. how can I get the elements to be at the bottom of the screen even before this happens?
JavaS:
setInterval(function(){
var height = Math.floor(Math.random() * (10 - 1 + 1)) + 1;
$('#container').prepend('<div style="height:'+height+'0%"></div>');
}, 500);
html, body, #container {
height:100%;
}
#container > div {
width:20px;
background:black;
display:inline-block;
}
I tried position:absolute; bottom:0.. but that obviously doesn't work.
A:
My solution require that you wrap your container with an other div. I've called it outerContainer. Once you have that and set its height at 100%, you can use the display table trick :
#outerContainer{
display : table;
}
#container{
display : table-cell;
vertical-align:bottom;
}
Fiddle : http://jsfiddle.net/5wJ5D/2/
| {
"pile_set_name": "StackExchange"
} |
Q:
Nested element in custom control is missing in the Visual Tree
I do have two problems regarding custom controls:
I created a custom UserControl
public partial class MyControl : UserControl
{
public static DependencyProperty ControlProperty = DependencyProperty.Register("Control", typeof(UIElement), typeof(MyControl ), null);
public UIElement Control
{
get { return GetValue(ControlProperty) as UIElement; }
set { SetValue(ControlProperty,value); }
}
}
Now I want to embed any "regular" control into my control using XAML
<Grid>
<own:MyControl>
<own:MyControl.Control>
<TextBox x:Name="txtTest" />
</own:MyControl.Control>
</own:MyControl>
</Grid>
1) When trying to access the TextBox by its name in code-behind I just can't because it is null. What might the problem be? If I would place the same TextBox just inside the Grid the name would resolve to the instance as it should.
2) I can't find my class using the VisualTreeHelper. The GetChild method just pretends my control isn't there. Why does this happen?
Thank you in advance!
A:
VisualTreeHelper isn't "pretending" at all. The value of the MyControl.Control property is not in the Visual Tree. Just being present in the Xaml does not mean it will be added to the visual tree.
Only when the control is added as a child of UI Element that is already in the Visual Tree such as a Panel, a ContentControl or a Border will it also become part of the visual tree.
You could do this:-
<Grid>
<own:MyControl x:Name="myControl">
<own:MyControl.Control>
<TextBox x:Name="txtTest" />
</own:MyControl.Control>
</own:MyControl>
</Grid>
In code-behind:-
txtTest = myControl.Control as TextBox;
Probably isn't what you are trying to do, so what is it you are trying to do?
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating a matrix of 2D cosines waves with coefficients and variable number of entries
After I posted this question yesterday, I realized that I want to create similar matrices of different n x n dimensions with each entry of the form
a * cos(j * x + k * y)
where a is a vector of coefficients; and j, x, k and y are indexes from 0 to n - 1.
If, for instance, n = 4,
>> n = 4;
>> x = 0:(n-1);
>> y = 0:(n-1);
>> [x,y] = meshgrid(x,y)
x =
0 1 2 3
0 1 2 3
0 1 2 3
0 1 2 3
y =
0 0 0 0
1 1 1 1
2 2 2 2
3 3 3 3
The resultant matrix would have 16 entries which could be computed by the function:
f = @(x, y,a0,a1,a2,a3,b0,b1,b2,b3,c0,c1,c2,c3,d0,d1,d2,d3)...
a0*cos(0*x + 0*y) + a1*cos(0*x + 1*y) +...
a2*cos(0*x + 2*y) + a3*cos(0*x + 3*y) + ...
b0*cos(1*x + 0*y) + b1*cos(1*x + 1*y) + ...
b2*cos(1*x + 2*y) + b3*cos(1*x + 3*y) + ...
c0*cos(2*x + 1*y) + c1*cos(2*x + 1*y) + ...
c2*cos(2*x + 2*y) + c3*cos(2*x + 3*y) + ...
d0*cos(3*x + 1*y) + d1*cos(3*x + 1*y) + ...
d2*cos(3*x + 2*y) + d3*cos(3*x + 3*y)
Of course, aside from the need to furnish the coefficients in front of the cosines, typing all these cosine expressions is not doable if I want to generate a 256 x 256 matrix, for example...
I played with for-loops but I didn't get what I am after, getting error regarding the number of independent indexing loops within a function.
A:
EDIT: I edited my initial answer, adding the idea given in Guille's comment. (Haven't seen that in first place...) Please, see the updated code.
Smee again. You can combine anonymous functions / function handles like this:
f = @(x) sin(x);
g = @(x) cos(x);
h = @(x) f(x) + g(x);
Nevertheless, I guess, it's necessary to encapsulate the setup of your function (handle) f into some "real" MATLAB function, see the following code:
function f = setupF(n, a)
% Possibly, add some checks, e.g. for numel(a) == n^2, and so on.
% Initialize function handle.
f = @(x, y) 0;
ind = 0;
% Iteratively add cosine parts.
for ii = 0:(n-1)
for jj = 0:(n-1)
ind = ind + 1;
g = @(x, y) a(ind) * cos(ii * x + jj * y);
f = @(x, y) f(x, y) + g(x, y);
end
end
end
Here comes a test script:
% Set up parameters.
n = 3;
a = reshape(1:n^2, n, n);
% Set up f(x, y) by function.
f = setupF(n, a);
% Set up f explicitly, as g(x, y).
g = @(x, y) ...
a(1) * cos(0*x + 0*y) + ...
a(2) * cos(0*x + 1*y) + ...
a(3) * cos(0*x + 2*y) + ...
a(4) * cos(1*x + 0*y) + ...
a(5) * cos(1*x + 1*y) + ...
a(6) * cos(1*x + 2*y) + ...
a(7) * cos(2*x + 0*y) + ...
a(8) * cos(2*x + 1*y) + ...
a(9) * cos(2*x + 2*y);
% Set up f(x, y) by vectorization, as h(x, y).
I = 0:(n-1);
J = 0:(n-1);
[I, J] = meshgrid(I, J);
h = @(x, y, n, a) sum(reshape(a .* cos(x * I + y * J), n^2, 1));
h = @(x, y, n, a) arrayfun(@(x, y) h(x, y, n, a), x, y);
% Set up test data.
x = linspace(0, 2*pi, 5);
y = linspace(0, 2*pi, 5);
[X, Y] = meshgrid(x, y);
% Compare outputs.
fRet = f(X, Y)
gRet = g(X, Y)
hRet = h(X, Y, n, a)
And, the output:
fRet =
45.0000 -18.0000 15.0000 -18.0000 45.0000
-6.0000 -5.0000 -2.0000 5.0000 -6.0000
15.0000 -6.0000 5.0000 -6.0000 15.0000
-6.0000 5.0000 -2.0000 -5.0000 -6.0000
45.0000 -18.0000 15.0000 -18.0000 45.0000
gRet =
45.0000 -18.0000 15.0000 -18.0000 45.0000
-6.0000 -5.0000 -2.0000 5.0000 -6.0000
15.0000 -6.0000 5.0000 -6.0000 15.0000
-6.0000 5.0000 -2.0000 -5.0000 -6.0000
45.0000 -18.0000 15.0000 -18.0000 45.0000
hRet =
45.0000 -18.0000 15.0000 -18.0000 45.0000
-6.0000 -5.0000 -2.0000 5.0000 -6.0000
15.0000 -6.0000 5.0000 -6.0000 15.0000
-6.0000 5.0000 -2.0000 -5.0000 -6.0000
45.0000 -18.0000 15.0000 -18.0000 45.0000
And, of course, the "vectorization" approach wins in terms of performance:
| {
"pile_set_name": "StackExchange"
} |
Q:
Understanding LDA Transformed Corpus in Gensim
I tried to examine the contents of the BOW corpus vs. the LDA[BOW Corpus] (transformed by LDA model trained on that corpus with, say, 35 topics)
I found the following output:
DOC 1 : [(1522, 1), (2028, 1), (2082, 1), (6202, 1)]
LDA 1 : [(29, 0.80571428571428572)]
DOC 2 : [(1522, 1), (5364, 1), (6202, 1), (6661, 1), (6983, 1)]
LDA 2 : [(29, 0.83809523809523812)]
DOC 3 : [(3079, 1), (3395, 1), (4874, 1)]
LDA 3 : [(34, 0.75714285714285712)]
DOC 4 : [(1482, 1), (2806, 1), (3988, 1)]
LDA 4 : [(22, 0.50714288283121989), (32, 0.25714283145449457)]
DOC 5 : [(440, 1), (533, 1), (1264, 1), (2433, 1), (3012, 1), (3902, 1), (4037, 1), (4502, 1), (5027, 1), (5723, 1)]
LDA 5 : [(12, 0.075870715371114297), (30, 0.088821329943986921), (31, 0.75219107156801579)]
DOC 6 : [(705, 1), (3156, 1), (3284, 1), (3555, 1), (3920, 1), (4306, 1), (4581, 1), (4900, 1), (5224, 1), (6156, 1)]
LDA 6 : [(6, 0.63896110435842401), (20, 0.18441557445724915), (28, 0.09350643806744402)]
DOC 7 : [(470, 1), (1434, 1), (1741, 1), (3654, 1), (4261, 1)]
LDA 7 : [(5, 0.17142855723258577), (13, 0.17142856888458904), (19, 0.50476192150187316)]
DOC 8 : [(2227, 1), (2290, 1), (2549, 1), (5102, 1), (7651, 1)]
LDA 8 : [(12, 0.16776844589094803), (19, 0.13980868559963203), (22, 0.1728575716782704), (28, 0.37194624921210206)]
Where,
DOC N is the document from the BOW corpus
LDA N is the transformation of DOC N by that LDA model
Am I correct in understanding the output for each transformed document "LDA N" to be the topics that the document N belongs to? By that understanding, I can see some documents like 4, 5, 6, 7 and 8 to belong to more than 1 topic like DOC 8 belongs to topics 12, 19, 22 and 28 with the respective probabilities.
Could you please explain the output of LDA N and correct my understanding of this output, especially since in another thread HERE - by the creator of Gensim himself, it's been mentioned that a document belongs to ONE topic?
A:
Your understanding of the output of LDA from gensim is correct. What you need to remember though is that LDA[corpus] will only output topics that exceed a certain threshold (set when you initialise the model).
The document belongs to ONE topic issue is one you need to make a decision about on your own. LDA gives you a distribution over the topics for each document you feed into it*. You need to then make a decision whether a document having (for instance) 50% of a topic is enough for that document to belong to said topic.
(*) again you have to keep in mind that LDA[corpus] will only show you those ones that exceed a threshold, not the whole distribution. You can access the whole distribution as well using
theta, _ = lda.inference(corpus)
theta /= theta.sum(axis=1)[:, None]
| {
"pile_set_name": "StackExchange"
} |
Q:
All records being deleted when deleting records from a temp table
I have a stored procedure that I am passing a string of documentIDs to and its supposed to delete the documentID where its roleID = @roleID, but instead it is deleting all the records based on the roleID and all I want to do is delete the documentIDs from the table based on the roleID
My sp is
ALTER PROCEDURE sp_RemoveDocumentIDsFromRole
(
@roleID int,
@group_name varchar(50),
@DocumentIDString varchar(500),
@group_display_name varchar(50)
)
as
UPDATE [master_groups]
set group_name = @group_name, @group_display_name = @group_display_name
where roleID = @roleID
-- Creating Variables
DECLARE @numberLength int
DECLARE @numberCount int
DECLARE @TheDocumentIDs VarChar(500)
DECLARE @sTemp VarChar(100) -- to hold single characters
-- Creating a temp table
DECLARE @T TABLE
(
TheDocumentIDs VarChar(500)
)
--Initializing Variables for counting
SET @numberLength = LEN (@DocumentIDString)
SET @numberCount = 1
SET @TheDocumentIDs = ''
--Start looping through the keyword ids
WHILE (@numberCount <= @numberLength)
BEGIN
SET @sTemp = SUBSTRING (@DocumentIDString, @numberCount, 1)
IF (@sTemp = ',')
BEGIN
INSERT @T(TheDocumentIDs) VALUES (@TheDocumentIDs)
SET @TheDocumentIDs = ''
END
IF (@sTemp <> ',')
BEGIN
SET @TheDocumentIDs = @TheDocumentIDs + @sTemp
END
SET @numberCount = @numberCount + 1
END
declare @rLevel int
set @rLevel = 0
delete from [master_group_document_relations] where exists(select documentID = @TheDocumentIDs from @T) and roleID = @roleID
UPDATE: SAMPLE DATA
A:
Not sure what you get in @TheDocumentIDs, but I suppose it should work for you.
First of all as @Chris mentioned, you should check put condition to where clause and as documentIds is a list of id's it should used with IN condition and not equality, that's why you need or use sp_executesql or fill id's to a temp table.
EXECUTE sp_executesql
N'delete from [master_group_document_relations]
where documentID IN (@TheDocumentIDs)
and roleID = @roleID',
N'@TheDocumentIDs varchar(500), @roleID int',
@DocumentIDString,
@roleID;
Or try this
delete from [master_group_document_relations]
where documentID IN (SELECT TheDocumentIDs FROM @T)
and roleID = @roleID
| {
"pile_set_name": "StackExchange"
} |
Q:
Cloneable in Derived Classes
Assume I have a class A, and B which derives from A:
class A : ICloneable
{
public object Clone() {...}
}
class B : A, ICloneable
{
public object Clone() {...}
}
which gives
'B.Clone()' hides inherited member 'A.Clone()'. Use the new keyword if hiding was intended.
warning.
(1) What is the suggested way? using new or declaring A.Clone() as virtual and override in B?
(2) If there are some members in A and properly cloned in A.Clone(), is there an easy way to clone them in B.Clone() or do I have to explicitly clone them in B.Clone() also?
A:
If you have access to your source (which I'm guessing is the case here) then absolutely declare it as virtual and override it. If hide the base Clone with new might be a bad idea. If any code doesn't know that it's working with a B, then it will fire the wrong clone method and not return a proper clone.
Regarding the assignment of properties, perhaps consider implementing copy constructors and each level can handle its own cloning:
public class A : ICloneable
{
public int PropertyA { get; private set; }
public A()
{
}
protected A(A copy)
{
this.PropertyA = copy.PropertyA;
}
public virtual object Clone()
{
return new A(this);
}
}
public class B : A, ICloneable
{
public int PropertyB { get; private set; }
public B()
{
}
protected B(B copy)
: base(copy)
{
this.PropertyB = this.PropertyB;
}
public override object Clone()
{
return new B(this);
}
}
Each copy constructor calls the base copy constructor passing itself down the chain. Each inheritance level copies the properties belonging to it directly.
EDIT: If you use the new keyword to hide the base implementation, here's an example of what might happen. With a sample implementation (which on the face of it looks fine)
public class A : ICloneable
{
public int PropertyA { get; protected set; }
public object Clone()
{
Console.WriteLine("Clone A called");
A copy = new A();
copy.PropertyA = this.PropertyA;
return copy;
}
}
public class B : A, ICloneable
{
public int PropertyB { get; protected set; }
public new object Clone()
{
Console.WriteLine("Clone B called");
B copy = new B();
copy.PropertyA = this.PropertyA;
copy.PropertyB = this.PropertyB;
return copy;
}
}
But when you use it:
B b = new B();
A a = b;
B bCopy = (B)a.Clone();
//"Clone A called" Throws InvalidCastException! We have an A!
| {
"pile_set_name": "StackExchange"
} |
Q:
Flask broken pipe when redirecting after AJAX call
I have an JQuery AJAX call:
$.getJSON($SCRIPT_ROOT + '/_click_btn?btnId='+$(this).attr("id"),
$('form').serialize(),
function(data) {
// return to send_messages page
window.location = 'send_messages';
});
It doesn't do anything fancy. It just saves some form data to a database (using SQLAlchemy). I put a break point on the window.location statement and the broken pipe won't happen if I delay the redirection by 1-2 seconds. What's the best practice for handling this?
One other item of note is the DB session remains open after the AJAX call is complete.
The error message is below.
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib64/python2.7/threading.py", line 813, in __bootstrap_inner self.run()
File "/usr/lib64/python2.7/threading.py", line 766, in run self.__target(*self.__args, **self.__kwargs)
File "/gui/venv/lib/python2.7/site-packages/werkzeug/serving.py", line 656, in inner srv.serve_forever()
File "/gui/venv/lib/python2.7/site-packages/werkzeug/serving.py", line 496, in serve_forever HTTPServer.serve_forever(self)
File "/usr/lib64/python2.7/SocketServer.py", line 238, in serve_forever
self._handle_request_noblock()
File "/usr/lib64/python2.7/SocketServer.py", line 297, in _handle_request_noblock
self.handle_error(request, client_address)
File "/usr/lib64/python2.7/SocketServer.py", line 295, in _handle_request_noblock
self.process_request(request, client_address)
File "/usr/lib64/python2.7/SocketServer.py", line 321, in process_request
self.finish_request(request, client_address)
File "/usr/lib64/python2.7/SocketServer.py", line 334, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib64/python2.7/SocketServer.py", line 655, in __init__
self.handle()
File "/gui/venv/lib/python2.7/site-packages/werkzeug/serving.py", line 216, in handle rv = BaseHTTPRequestHandler.handle(self)
File "/usr/lib64/python2.7/BaseHTTPServer.py", line 340, in handle
self.handle_one_request()
File "/gui/venv/lib/python2.7/site-packages/werkzeug/serving.py", line 251, in handle_one_request
return self.run_wsgi()
File "/gui/venv/lib/python2.7/site-packages/werkzeug/serving.py", line 193, in run_wsgi
execute(self.server.app)
File "/gui/venv/lib/python2.7/site-packages/werkzeug/serving.py", line 184, in execute
write(data)
File "/gui/venv/lib/python2.7/site-packages/werkzeug/serving.py", line 152, in write
self.send_header(key, value)
File "/usr/lib64/python2.7/BaseHTTPServer.py", line 401, in send_header
self.wfile.write("%s: %s\r\n" % (keyword, value))
IOError: [Errno 32] Broken pipe
A:
As a temporary solution, I've added a 500 ms delay before redirecting. Seems like there must be a better way, but this works for now.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.