text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
PHP Convention - Assignment in condition
I'm been searching what the correct PHP convention is for assignments in conditions.
<?php
if(false !== ($var = something())) {
...
}
// or
if(($var = something()) !== false) {
...
}
Usually I'm using the first solution for small methods that I don't want to clutter with too much code, but some of my collegues use it the other way. What would be the right one to use and why?
I know that functionally it doesn't matter at all, I'm just asking this for enlightenment on conventions.
Thanks in advance.
A:
Do it the way the code base does it. Don't be that guy who injects your own preferences into the collective which clash with the norm.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I validate the dimensions of an uploaded image in Sanity?
I have an image type field in Sanity (docs) and I need to make sure that the dimensions are within a particular range to avoid breaking the website they're going on. Sanity offers validations, but the image type only has “required” and “custom” rules, and the field information passed into the custom validator doesn't include the image metadata.
How can I work around this limitation and offer in-CMS validation of the dimensions?
A:
While Sanity doesn't pass the image metadata into the validator, you can extract image format and dimension information from the asset ID that is provided. According to this documentation, this is a supported, stable way of accessing this information without loading the image object from Sanity.
For example, here's the first argument passed to the Rule.custom validator:
{
"_type": "image",
"alt": "Example Image",
"asset": {
"_ref": "image-bff149a0b87f5b0e00d9dd364e9ddaa0-700x650-jpg",
"_type": "reference"
}
}
Getting to the image dimensions can be accomplished like this:
{
title: "My Image",
name: "image",
type: "image",
options: {
accept: "image/*",
},
validation: Rule => Rule.custom(image => {
if (!image) return true
const { dimensions } = decodeAssetId(image.asset._ref)
return dimensions.width >= 500 || "Image must be wider"
}
}
const pattern = /^image-([a-f\d]+)-(\d+x\d+)-(\w+)$/
const decodeAssetId = id => {
const [, assetId, dimensions, format] = pattern.exec(id)
const [width, height] = dimensions.split("x").map(v => parseInt(v, 10))
return {
assetId,
dimensions: { width, height },
format,
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Distinguish between folders and files in C++
I have this code that opens a directory and checks if the list is not a regular file (means it's a folder) it will open it too. How can I distinguish between files and folders with C++.
here is my code if this helps :
#include <sys/stat.h>
#include <cstdlib>
#include <iostream>
#include <dirent.h>
using namespace std;
int main(int argc, char** argv) {
// Pointer to a directory
DIR *pdir = NULL;
pdir = opendir(".");
struct dirent *pent = NULL;
if(pdir == NULL){
cout<<" pdir wasn't initialized properly!";
exit(8);
}
while (pent = readdir(pdir)){ // While there is still something to read
if(pent == NULL){
cout<<" pdir wasn't initialized properly!";
exit(8);
}
cout<< pent->d_name << endl;
}
return 0;
}
A:
One way would be:
switch (pent->d_type) {
case DT_REG:
// Regular file
break;
case DT_DIR:
// Directory
break;
default:
// Unhandled by this example
}
You can see the struct dirent documentation on the GNU C Library Manual.
| {
"pile_set_name": "StackExchange"
} |
Q:
Eclipse Plugin-Development Debugger out of Sync
for some internal development I currently customize a Eclipse Plug in. The Plug in I use is deployed as .jar File. Now I extracted the Content and imported it as Eclipse Plug in project. Everything works fine until is start to add some Code.
For testing the new functionality I like to debug my code. Therefore I run the Eclipse Plug in project in Debug mode. I've got a Debugging connection but the line of code highlighted in the editor doesn't match with the code.
1 private void a(){
2 doSomething();
3 }
4
5 private void b(){
6 doSomethingElse();
7 }
For example the Debug view says I am in the Method b(). But the Highlighter, in the Text-Editor, point to line 3.
I tried several things like Cleaning and searched nearly everywhere in the Debug-Configurations but nothing helped me.
A:
If the displayed code doesn't fit what the debugger tells you it is executing, then you are simply not debugging the code that you see in the editor (but probably still the version without your modifications).
There are a lot of potential reasons for this. For the most easy failure please check your debug configuration. On the plugins page of the debug configuration there are plugins shown as living in your workspace and being provided by the Eclipse installation. Make sure that for your plugin the checkbox is at the workspace version, like the first checkbox in this image:
| {
"pile_set_name": "StackExchange"
} |
Q:
R: creating a likert scale barplot
I'm new to R and feeling a bit lost ... I'm working on a dataset which contains 7 point-likert-scale answers.
My data looks like this for example:
My goal is to create a barplot which displays the likert scale on the x-lab and frequency on y-lab.
What I understood so far is that I first have to transform my data into a frequency table. For this I used a code that I found in another post on this site:
data <- factor(data, levels = c(1:7))
table(data)
However I always get this output:
data
1 2 3 4 5 6 7
0 0 0 0 0 0 0
Any ideas what went wrong or other ideas how I could realize my plan?
Thanks a lot!
Lorena
A:
This is a very simple way of handling your question, only using base-R
## your data
my_obs <- c(4,5,3,4,5,5,3,3,3,6)
## use a factor for class data
## you could consider making it ordered (ordinal data)
## which makes sense for Likert data
## type "?factor" in the console to see the documentation
my_factor <- factor(my_obs, levels = 1:7)
## calculate the frequencies
my_table <- table(my_factor)
## print my_table
my_table
# my_factor
# 1 2 3 4 5 6 7
# 0 0 4 2 3 1 0
## plot
barplot(my_table)
yielding the following simple barplot:
Please, let me know whether this is what you want
| {
"pile_set_name": "StackExchange"
} |
Q:
Get page title in Magento 2
I want to get the page title in a PHTML template file. Is there a global function I can call to retrieve this?
A:
At magento every phtml file have block class.So you get page title by
$block->getLayout()->getBlock('page.main.title')->getPageTitle()
A:
Unfortunately, there's no global function you can call to retrieve this.
Here are the solutions:
Quick but not recommended
You can call the following directly in your template file:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$title = $objectManager->get('Magento\Framework\View\Page\Title');
Quick but unstable
See Amit answer, however, it will fail if the theme ever removes that block.
Recommended via DI
For this one, you have to have your own custom block that is used to render the template.
First, you need to inject \Magento\Framework\View\Page\Title in your block constructor:
protected $_pageTitle;
public function __construct(
...
\Magento\Framework\View\Page\Title $pageTitle
) {
$this->_pageTitle = $pageTitle;
...
}
Then you can declare a function in your block class:
public function getTitle()
{
return $this->_pageTitle->getShort();
}
And finally you can call it in your template:
$block->getTitle();
| {
"pile_set_name": "StackExchange"
} |
Q:
GSA OneBox - Internal Provider will account for the overall QPS
I think the title is self explanatory.
When I create a GSA OneBox which is powered for an internal collection. I then make a GSA search request which triggers the OneBox. Now, will the number of search request on that given second will be 1 or 2?
All i'm trying to figure out is if the OneBox which is an internal provider account for the Appliance's QPS.
A:
It will be two while the onebox search is executing.
| {
"pile_set_name": "StackExchange"
} |
Q:
Stream live video to browser (with low latency)
I want to stream live video to a browser with low latency.
As far as I understood, there are two clients:
HTML5 video tag
Flash video player
There are multiple ways to send the stream:
TCP/IP using HTTP, using progressive downloads (and html5 range-request)
UDP (which uses Flash)
And there are multiple solutions to broadcast the stream:
Using Apple's HTTP Live Stream (which provides a m3u-playlist of small file segments)
...?
and there is the issue of publishing and distributing the stream over the internet.
What I need is
sync video content with javascript
low latency accros the country / the world for many viewers
media server: (custom) desktop app (or browser solution) to upload webcam stream
other existing software solutions to serving media?
Will HTTP Live Stream cause a high latency, because the stream needs to be segmented and uploaded into small files? (Ruling out html5-solutions?)
What does the Flash player need for input (i.e. web-adress, file on the server?)
What does the Flash player need for a server? (also, to distribute it for many viewers?)
How do I upload a video stream to flash? (i.e. existing software solutions / is it possible to write a custom app that uploads the webcam stream?)
Thank you very much for answering this elaborate question!!
A:
3 years later, in 2014, WebRTC is gaining more and more adoption and popularity. Although it is limited to modern browsers only, its benefits in quality and performance far outweigh outdated Flash or limited HTML5-only solutions.
Google Hangouts uses WebRTC technology, and there are third-party services that provide the libaries and servers needed to stream, broadcast and connect video.
| {
"pile_set_name": "StackExchange"
} |
Q:
C# use Linq method instead of for loop
I have a string array and a for loop to add items to list.
Here is my code:
//customers table :
// Firstname, Lastname, Age, BrowserName, Date
string[] browsers = {"chrome", "Firefox", "Edge"}
var users = db.customers.ToList();
list<string> names = new List<string>();
for(var i = 0; i < browsers.lenght; i++) {
names.Add(users.where(x => x.BrowserName == browsers[i]).FirstName);
}
Is there any way to use Linq method or something else instead of for ?
A:
Instead of
for(var i = 0; i < browsers.lenght; i++) {
names.Add(users.where(x => x.BrowserName == browsers[i]).FirstName);
}
Use this
names = users.Where(x => browsers.Contains(x.BrowserName)).Select(y => y.FirstName).ToList();
| {
"pile_set_name": "StackExchange"
} |
Q:
Iterating through class names and hiding some in vanilla js
Stumped and I am sure there is an easy explanation to this.
So I want to iterate through all of the class names called 'images' and hide say the last 4:
images = document.getElementsByClassName("images");
for (var i = 0; i < images.length; i++) {
if(images[i] == images[5] || images[6] || images[7] || images[8]) {
images[5].style.display = "none";
images[6].style.display = "none";
images[7].style.display = "none";
images[8].style.display = "none";
}
}
Is there anyway of making this code shorter? Seems a bit laborious if you were to have loads of images.
No frameworks on this please! Many thanks for your help.
A:
Looking for a shorter version?
images = document.getElementsByClassName("images");
for (var i = 0; i < images.length; i++) {
if( i >= images.length-4 ) { // Last 4
images[i].style.display = "none";
}
}
1<img class="images" src="https://via.placeholder.com/50x50"><br/>
2<img class="images" src="https://via.placeholder.com/50x50"><br/>
3<img class="images" src="https://via.placeholder.com/50x50"><br/>
4<img class="images" src="https://via.placeholder.com/50x50"><br/>
5<img class="images" src="https://via.placeholder.com/50x50">
Or another Version mentioned by @Hector
images = [...document.getElementsByClassName("images")].slice(-4); // last 4
for( let i in images ) {
images[i].style.display = "none";
}
1<img class="images" src="https://via.placeholder.com/50x50"><br/>
2<img class="images" src="https://via.placeholder.com/50x50"><br/>
3<img class="images" src="https://via.placeholder.com/50x50"><br/>
4<img class="images" src="https://via.placeholder.com/50x50"><br/>
5<img class="images" src="https://via.placeholder.com/50x50">
| {
"pile_set_name": "StackExchange"
} |
Q:
Python Loop In HTML
I have the following row within a table:
<TR>
<TD style="text-align:center;width:50px">{% for z in recentResultHistory %} {{ z.0 }} {% endfor %}</TD>
<TD style="text-align:center;width:100px"></TD>
<TD style="text-align:center;width:50px">V</TD>
<TD style="text-align:center;width:100px"></TD>
<TD style="text-align:center;width:50px">{% for z in recentResultHistory %} {{ z.0 }} {% endfor %}</TD>
</TR>
when the first instance of the {% for z in recentResultHistory %} {{ z.0 }} {% endfor %} runs I get the expected result. When it runs for the second time it produces no results like it is not looping at all. Do I need to reset the loop in some way?
The variable is created in my django view.py as follows:
cursor = connection.cursor()
cursor.execute("""
select
team,
group_concat( concat(result, '-', convert(opponent USING utf8), '-', team_score, '-', opponent_score, '-', mstatus)
order by fixturedate desc
separator '|') as output from plain_result
where (select count(*)
from plain_result as p
where plain_result.team = p.team
and p.fixturedate>=plain_result.fixturedate) <= 5
group by team
""")
recentResultHistory = cursor.fetchall
A:
I should be using list(cursor) rather than cursor.fetchall(). Daniel and dkasak gave me the inspiration to look and I found the following which solved my issue:
cursor.fetchall() vs list(cursor) in Python
| {
"pile_set_name": "StackExchange"
} |
Q:
How to change/set DateTimePicker value
I am trying to set / change the DateTimePicker value (using vb.net) but can't work out how to do it.
I have added the control to the page and I have tried using the following code but it doesn't work and I can't work out how to set the value during run-time.
DateTimePicker1.Value = Now.Day & "-" & Now.Month & "-" & Now.Year
The format of the control is set to Long and it looks like this when first loaded:
Tuesday, February 26, 2013
But I can't work out how to change it.
The error I get based on my code above is:
Conversion from string "26-2-2013" to type 'Date' is not valid.
Anyone got any ideas ?
A:
I ended up getting it working by doing the following:
DateTimePicker1.Value = New Date(2013, 2, 26)
I was loading the value wrong.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create this loop (WordPress/PHP)
I am learning WordPress at the moment and I am working with custom field/post types to see how they work within WordPress.
Here I have a section of code where I can clearly see I am repeating myself in order to spit out the Custom Field Label and the Custom field.
<?php if( $query->have_posts() ) : while( $query->have_posts() ) : $query->the_post(); ?>
<?php $field_name = "about";
$field = get_field_object($field_name);?>
<h5 class="cv-subtitle"><?php echo $field['label'];?></h5>
<p class=""><?php the_field('about'); ?></p>
<?php $field_name = "work_experience";
$field = get_field_object($field_name);?>
<h5 class="cv-subtitle"><?php echo $field['label'];?></h5>
<p class=""><?php the_field('work_experience'); ?></p>
<?php $field_name = "education";
$field = get_field_object($field_name);?>
<h5 class="cv-subtitle"><?php echo $field['label'];?></h5>
<p class=""><?php the_field('education'); ?></p>
<?php $field_name = "skills";
$field = get_field_object($field_name);?>
<h5 class="cv-subtitle"><?php echo $field['label'];?></h5>
<p class=""><?php the_field('skills'); ?></p>
<?php endwhile; endif; wp_reset_postdata(); ?></div>
This is for an "About" page on my portfolio which is displayed in the style of a CV.
I am aware repeating my self in this way is not good practice and understand some sort of loop is needed in order to prevent this.
If anyone could help create this loop or point me in some direction, that would be great.
Thanks
A:
<?php if( $query->have_posts() ) : while( $query->have_posts() ) : $query->the_post(); ?>
<?php
$field_names = ['about','work_experience','education','skills'];
foreach($field_names as $field_name)
{
$field = get_field_object($field_name); ?>
<h5 class="cv-subtitle"><?php echo $field['label'];?></h5>
<p class=""><?php the_field($field_name); ?></p>
<?php
}
?>
<?php endwhile; endif; wp_reset_postdata(); ?></div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Possible lock combinations
A combination look has 60 different position. To open the look you need to move to 3 numbers. If consecutive numbers cannot be the same, how many different combinations are there?
I am not sure if the possible position can have 60 options or 59 because consecutive options cannot be the same.
A:
I will address your question in the case of a combination lock with 5 positions and the same restriction. First, how many choices do you have for the first position? At that point, no other numbers have been chosen so you don't need to worry about what a previous choice had been. Therefore you have 5 possible first positions. Once you've chosen your first position, you only have 4 options remaining for your second, since you can't repeat your previous choice. For your third position, you can't repeat your second position, but you can go back to your first, so you still have 4 options available. Therefore the total number of combinations is $5\cdot 4\cdot 4=80.$ How does this generalize to 60 possible positions?
| {
"pile_set_name": "StackExchange"
} |
Q:
Generating select options with v-for using an object
I have an object that contains user names in this structure:
clients: {
1: {
first_name:"John"
last_name:"Doe"
middle_name:"A"
},
2: {
first_name:"Jenny"
last_name:"Doe"
},
}
I want to loop though them in a select input as options
<option v-for="(value, client, index) in clients" :value="">{{ value }}</option>
I came until here, but I couldn't figure out how to organize the string properly. Maybe, is there a way to parse it in computed properties so I can have room to put code?
If I could use something like this, I think it would work, but couldn't figure out how to do it like this either.
computed:{
clientNameOptions() {
for (const key of Object.keys(this.clients)) {
return `<option value="` + this.clients[key].first_name + ' ' + this.clients[key].middle_name + ' ' +
this.clients[key].last_name + `"></option>`
}
}
}
What is the proper way of achieving it?
A:
This is primarily a guess at what you want, but you could build your options using a computed property.
console.clear()
new Vue({
el:"#app",
data:{
clients: {
1: {
first_name:"John",
last_name:"Doe",
middle_name:"A"
},
2: {
first_name:"Jenny",
last_name:"Doe"
},
},
selectedClient: null
},
computed:{
options(){
return Object.keys(this.clients).map(k => {
let o = this.clients[k]
return `${o.first_name} ${o.middle_name ? o.middle_name : ''} ${o.last_name}`
})
}
}
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="app">
<select v-model="selectedClient">
<option v-for="option in options" :value="option">{{option}}</option>
</select>
<hr>
Selected: {{selectedClient}}
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Cypress, If else /switch case doesn't work
I am trying to add else if /switch case in my test , but
else if - it goes to only if case, if 'if' fail it doesn't go in else if
it's happen in switch case also.
module.exports.selectEnviroment = function(env) {
switch (env) {
case 'alpha':
cy.get('[role="presentation"]')
.find('[href="#/company-detail/5bb3765e64f66ca0027e15245"]')
.click();
break;
case 'beta':
cy.get('[role="presentation"]')
.find('[ng-href="#/company-detail/5bb62c019ee36000273a6e2b"]')
.eq(0)
.click();
break;
}
it('Booking should be done using invoice', () => {
cy.visit(`${blah_URL}#/xyz/`);
let env = blah.split('.')[1];
selectEnviroment(env);
According to environment, it should select the case ,but it doesn't
if (
cy.get('[role="presentation"]').find('[ng-href="#/company-detail/5bb62c019ee36000273a6e2b"]') ) {
cy.get('[role="presentation"]')
.find('[ng-href="#/company-detail/5bb62c019ee36000273a6e2b"]')
.eq(0)
.click();
} //alpha
else if (cy.get('[role="presentation"]').find('[ng-href="#/company-detail/5bae05a39af4a90027fcdf43"]')) {
cy.get('[role="presentation"]')
.find('[ng-href="#/company-detail/5bae05a39af4a90027fcdf43"]')
.eq(0)
.click();
} //QA
else if (cy.get('[role="presentation"]').find('[ng-href="#/company-detail/5b855022323d37000f48bcdc"]')) {
cy.get('[role="presentation"]')
.find('[ng-href="#/company-detail/5b855022323d37000f48bcdc"]')
.eq(0)
.click();
} //Gamma
else if (cy.get('[role="presentation"]').find('[ng-href="#/company-detail/5bb62ccf5cb043002737d929"]')
) {
cy.get('[role="presentation"]')
.find('[ng-href="#/company-detail/5bb62ccf5cb043002737d929"]')
.eq(0)
.click();
}
it('flight booking should be done using new credit card', () => {
cy.visit(`${COCKPIT_URL}#/company-list/`);
selectEnviroment();
failure message
A:
You are using Cypress commands and expecting them to generate results right away. This is not how Cypress works. Calling a Cypress function is simply a way to ask Cypress to add a command to its list of commands to eventually run.
.then() was created with this type of situation in mind. It allows you to add some code to be run directly after the previous command in the chain:
cy.get('.myDiv').then(elem => {
// elem is a jQuery object
console.log(elem.text());
if (elem.text() == 'Some text') {
// do something
else {
// ...
}
}
I strongly suggest reading the introduction to Cypress in the docs. It is well-written and easy to read. Cypress is not like other testing frameworks, and a basic understanding of how Cypress works is necessary to write good Cypress code.
| {
"pile_set_name": "StackExchange"
} |
Q:
What version of angular to use in a new project?
I need to start a project with angular in the company where I work. Currently, most projects are developed using version 4 but I have the chance to choose the version.
What do you recommend? I want to know the reasons for using and not using a specific version.
Thanks!
A:
I recommend you always use the latest version which you can find by following this URL. As I think the main reason why you should choose latest one is that there are many improvements, speed optimizations and bug fixes. So why choose old version when you always can be up to date!
| {
"pile_set_name": "StackExchange"
} |
Q:
Default move constructor Visual Studio 2015
There seems to be conflicting documentation as to whether Visual Studio 2015 supports generation of default move constructors.
This link and this link seem say to no, whereas this link says yes.
I tried something simple:
class Test {
public:
Test(int data) : data(data) {}
Test(Test&& other) = default;
Test(Test& other) = delete;
int data;
};
int main() {
Test c(3);
std::cout << c.data << std::endl;
Test b(std::move(c));
std::cout << b.data << std::endl;
}
It prints out 3 and 3 as expected. Am I making some mistake or is the default move constructor actually being generated?
Edit: Removed "implicit" wording
A:
The move constructor is being generated. It just happens that moving an int is achieved by copying (setting the "moved" object to some other value would be more expensive than just leaving it as is.)
You could test this by using a verbose movable type as data member instead of an int.
| {
"pile_set_name": "StackExchange"
} |
Q:
order by in mdx query
I want to order by only one element in the column, but code which I already write order by two elements:
Here is my query:
SELECT
NON EMPTY
{
CrossJoin
(
[Data Zameldowania].[Data zameldowania].[Miesiac slownie]
,[Data Zameldowania].[Rok].[Rok]
)
} ON 0
,NON EMPTY
{[Pokoj].[Typ].[Typ]} ON 1
FROM [Hurtownia Danych]
WHERE
[Measures].[Rezerwacja Count];
Here is the output of my query:
Here is what I try to do, but it doesn't work:
NON EMPTY
Order
(
{
CrossJoin
(
[Data Zameldowania].[Data zameldowania].[Miesiac slownie]
,[Data Zameldowania].[Rok].[Rok]
)
}
,desc
) ON 0
Is possible to order by only on "[Miesiac slownie]"? If so what I could do to achieve this? I will be very grateful for help!
A:
Try this:
Add this in front of your query:
WITH MEMBER [MEASURES].[X] AS
[Data Zameldowania].[Data zameldowania].[Miesiac slownie].membervalue
Then amend your order snippet to this:
NON EMPTY
Order
(
[Data Zameldowania].[Data zameldowania].[Miesiac slownie] *
[Data Zameldowania].[Rok].[Rok],
[MEASURES].[X]
,bdesc //<< changed to break natural hier order
) ON 0
Second attempt. Please try using the member name property. So try the following
Add this in front of your query:
WITH MEMBER [MEASURES].[X] AS
[Data Zameldowania].[Data zameldowania].[Miesiac slownie].CurrentMember.PROPERTIES("Name")
Then amend your order snippet to this:
NON EMPTY
Order
(
[Data Zameldowania].[Data zameldowania].[Miesiac slownie] *
[Data Zameldowania].[Rok].[Rok],
[MEASURES].[X]
,bdesc //<< changed to break natural hier order
) ON 0
| {
"pile_set_name": "StackExchange"
} |
Q:
Retrieving call log from Twilio using the Python Rest API
I'm trying to retrieve a list of calls completed after 1/1/2017 to now. Based on the documentation I tried:
calls=client.calls.list(started_after=date(2017,1,1))
for call in calls:
print("Call to: {} call from {} duration {}".format(call.to,call.from_, call.duration))
I'm retrieving a call log but all I'm getting is the calls for the current day.
A:
Twilio developer evangelist here.
I believe the sort order for the list of calls is in reverse chronological order, so you are getting the most recent calls first. All list resources from Twilio are paginated in order to retrieve more. The default page size is 50.
You can turn the pageSize up to 1000 at the most to get more records in one API call.
calls=client.calls.list(started_after=date(2017,1,1), page_size=1000)
Or, you can use the Python helper library's iter method, to iterate over the list of calls, making all the API calls you need to fetch all the data.
calls=client.calls.iter(started_after=date(2017,1,1))
Let me know if that helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
implementation of ng-options
i want to show A abd B as my options list from the below
$scope.devices={
"A": {
"status": 3,
"event": "Door was opened",
"name": "xxxxxx ",
"latlng": "xxxxx"
},
"B": {
"status": 4,
"event": "kitchen was opened",
"name": "xxxxx ",
"latlng": "xxxxx"
}
}
iam trying like this
<select ng-change="selected(prop)" style="color:black;" ng-model="prop" ng-options="item as item for item in devices">
<option value="">-- choose an option --</option>
</select>
A:
You can have like this,
<label for="reason">Device</label>
<select ng-change="selected(Device)" ng-model="Device" ng-options="key as key for (key , value) in devices"></select>
</div>
DEMO
| {
"pile_set_name": "StackExchange"
} |
Q:
Can these sigils Ned saw at the tourney be identified?
In the first book A Game of Thrones, during the tourney being held in honor of the new Hand of the King, Ned is walking through the ground and notices the following sigils:
The shields displayed out each tent heralded its occupant: the silver eagle of Seagard, Bryce Caron's field of nightingales, a cluster of grapes for the Redwynes, brindled boar, red ox, burning tree, white ram, triple spiral, purple unicorn, dancing maiden, blackadder, twin towers, horned owl, and last the pure white blazons of the Kingsguard, shining like the dawn. - A Game of Thrones, Chapter 30
So the first few are identified, but what about the others? Do we know the names of the house they belong to?
A:
Brindled Boar:
This is sigil of House Crakehall. They are a vassal of House Lannister and their current lord is Roland Crakehall. Their seat is Crakehall and their words are None So Fierce.
Red Ox:
This is sigil of House Prester. They are vassals to House Lannister and their current lord is Garrison Prester. Their seat is Feastfires and their words are Tireless.
Burning Tree:
This is sigil of House Marbrand. They are a vassal of House Lannister and their current lord is Damon Marbrand. Their seat is Ashemark and their words are Burning Bright.
White Ram:
This is sigil of knightly House Rambton. They are a vassal of House Sunglass (Who are vassals of House Baratheon of Dragonstone, previously House Targaryen) and their last known lord was Ser Hubart Rambton. Their words and seat are unknown.
Triple Spiral:
This is sigil of House Massey. They are direct vassals of the Royal dynasty and their current lord is unknown. Their seat is Stonedance however their words are also unknown.
Purple Unicorn:
This is sigil of House Brax. They are bannermen to Lord of Casterly Rock and their current lord is Tytos Brax. Their seat is Hornvale and their words are unknown.
Dancing Maiden:
This is sigil of House Piper. They are bannermen to House Baelish (Previously House Tully) and their current lord is Clement Piper. Their seat is Pinkmaiden but their words are unknown as per canon sources. Semi Canon sources put it as Bright and Beautiful.
Black Adder:
This is sigil of House Wyl. They are bannermen to House Martell and their current lord is unknown. Their seat is Wyl and their words are unknown.
Twin Towers:
This is sigil of House Frey. They are bannermen to House Baelish (Previously House Tully) and their current lord is Walder Frey. Their seat is the Crossing/Twin towers of Frey and their words are unknown.
Horned Owl:
This is sigil of House Mertyns. They are bannermen to House Baratheon of Storm's End (Not House Baratheon of King's Landing) and their current lady is Mary Mertyns. Their seat is Mistwood and their words are unknown.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it correct to use "catered" in a sentence like "which is an technology originally catered for..."?
I wrote the following sentence which my tutor doubted it, but I cannot see the why. Can anyone help me figure it out?
More specific, should catered be replaced as caters or catering or other forms? or there is no problem for the following sentence.
Multi-sensor fusion is also known as multi-sensor data fusion, which
is an emerging technology originally catered for the military needs
A:
Well you should ask your tutor to explain why...
Anyway, it should be catering. If you go to the time of "originally", cater indicates a continuing action, so you would use -ing verb form. As defined below, it is not a single action or event.
The definition here would be cater sense 2:
intransitive verb
2) to take special pains in seeking to gratify another's needs or desires (with to or, in Brit. usage, for)
This is different from the other definitions (relating to catered meals and such), which could be considered as single events.
As for the preposition, I (American) would use catering to, but it seems BrE speakers use catering for.
| {
"pile_set_name": "StackExchange"
} |
Q:
Magento 2 Create Custom module
I have search many times, with key code "create module magento 2".
Can you help me more link is exactly what I should be doing to create a module with magento 2.
I have tried follow example in this Link but it not work.
Have any for:
rewrite Event "Observer";
Custom Template.
or more.
A:
I can recommend you as a study this sample module I've created some time ago. Not sure if it works on the latest versions, but it's a place to start.
I also started a module creator for Magento 2. This is in the dev phase for now and it only allows you to create backend CRUD modules, but frontend and others will follow (sooner or later).
A:
Further to what @Marius has suggested, you will probably benefit from reading the Magento 2 Dev Docs. Specifically the architecture and module sections. The Magento 2 documentation is significantly better than Magento 1.
| {
"pile_set_name": "StackExchange"
} |
Q:
Find out where [ shortcode ] leads in wordpress
I'm no word press guru, but I think i have a good grip how to manage a site. The problem I'm having is that I have a site which i haven't done myself and i'm trying to delete a product from a page.
The page only have [productspage] as content though and i cannot for the life of me figure out where it gets the data from. Is there any way to find out where [productspage] gets the data? I've checked in widgets and other pages but even though i search i cannot find anything.
A:
If you have access on the FTP, download the files in a local machine. Then use a software like Sublime Text 3 and its feature of "Search in files".
Choose all the folders you downloaded from the FTP and search for the name of the Shortcode. In your example, search for productspage without the brackets of the shortcode.
Probably, you will have many results. Some put it in functions.php, some others in new files. You need to find the right one which is a function with a similar name of productspage. Just to be sure, close to that function, you will find also something like this:
add_shortcode('productspage','the_name_of_the_function_you_found');
That function is what you are looking for. You will be able to check how it works and from where it retrieve the data.
| {
"pile_set_name": "StackExchange"
} |
Q:
What are the min and max parameters?
Several of the api methods (e.g. questions) have min and max parameters with the following description:
min (optional)
Minimum of the range to include in the current .
number
max (optional)
Maximum of the range to include in the current .
number
This seems incomplete. Can anyone explain what these parameters are for?
A:
Yeah... These are kind of complicated, but very flexible. They're also getting better docs soon-ish.
Basically, min & max are the range of the sorted results to return.
So, if you order a list of questions (pick your API method of choice) by votes, you can set min to 5 and max to 10 to only return questions that have a score of at least 5 and no more than 10.
If you were to sort by creation, you could instead only return questions created between (inclusive) the 1st and 15th of June 2009 by setting min to 1243832400 and max to 1245042000.
Comparing pure strings (as in name) gives you a lexographic range though the exact one is something of an implementation detail.
Not specifying min or max causes that end of the range to by unbound. So you could use get all questions with at least a score of 10 by setting min to 10, sort to votes, and omitting max on the appropriate methods.
| {
"pile_set_name": "StackExchange"
} |
Q:
django-social-auth facebook login keeps overwriting same user
I implemented django-social-auth and got it to authenticate me with Facebook.
I would like it to also create a new user in the system, and write the email, name, and phone number if possible.
However, each time i log in with a user, it keeps overwriting the root user and not creating a new user?
I am also using a custom authentication module, and it's not creating a user in the custom model.
Settings.py:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'something.urls'
WSGI_APPLICATION = 'something.wsgi.application'
TEMPLATE_DIRS = (
templatedir
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'frontpage',
'social_auth',
'django.contrib.admin'
)
AUTHENTICATION_BACKENDS = (
'something.auth_backends.CustomUserModelBackend',
'social_auth.backends.twitter.TwitterBackend',
'social_auth.backends.facebook.FacebookBackend',
)
CUSTOM_USER_MODEL = 'accounts.CustomUser'
SOCIAL_AUTH_NEW_ASSOCIATION_REDIRECT_URL = '/newuser/'
SOCIAL_AUTH_DISCONNECT_REDIRECT_URL = '/disconnected/'
SOCUAL_AUTH_USER_MODEL = 'accounts.CustomUser'
SOCIAL_AUTH_CREATE_USERS = True
FACEBOOK_APP_ID = 'XXX'
FACEBOOK_API_SECRET = 'XXX'
FACEBOOK_EXTENDED_PERMISSIONS = ['email','user_birthday','user_hometown','user_location','user_about_me']
LOGIN_URL = '/'
LOGIN_REDIRECT_URL = '/home/'
LOGIN_ERROR_URL = '/login-error/'
SOCIAL_AUTH_DEFAULT_USERNAME = 'social_auth_user'
SOCIAL_AUTH_ENABLED_BACKENDS = ('twitter','facebook','google')
TWITTER_CONSUMER_KEY = 'XXX'
TWITTER_CONSUMER_SECRET = 'XXX'
URL's.py
from django.conf.urls import patterns, include, url
from django.contrib.auth.views import login, logout
from frontpage.views import LoginPage, FrontPageView
from frontpage import views
from django.contrib import admin
from social_auth import __version__ as version
from social_auth.utils import setting
admin.autodiscover()
urlpatterns = patterns('',
url(r'', include('social_auth.urls')),
url(r'^$', views.LoginPage, name='LoginPage'),
url(r'^login/$', views.loginreq, name='loginreq'),
url(r'^newuser/$', views.newuser, name='newuser'),
url(r'^logout/$', views.logout, name='logout'),
url(r'^home/$', views.HomePage, name='HomePage'),
url(r'^jobs/offers$', views.jobsoffers, name='jobsoffers'),
url(r'^jobs/view$', views.jobsview, name='jobsview'),
#url(r'^home/$', FrontPageView.as_view(), name='front_list'),
(r'^admin/jsi18n/$', 'django.views.i18n.javascript_catalog'),
# Examples:
# url(r'^$', 'something.views.home', name='home'),
# url(r'^something/', include('something.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
Views.py
class FrontPageView(ListView):
context_object_name = 'front_list'
template_name = 'homepage.html'
queryset = classifield.objects.all()
def get_context_data(self, **kwargs):
context = super(FrontPageView, self).get_context_data(**kwargs)
context['offers'] = offers.objects.all()
return context
def logout(request):
auth_logout(request)
return HttpResponseRedirect('/')
def LoginPage(request):
classifield_list = classifield.objects.all()
offers_list = offers.objects.all()
return render_to_response("login.html", {'classifield_list': classifield_list,'offers_list':offers_list}, context_instance=RequestContext(request))
@login_required
def HomePage(request):
classifield_list = classifield.objects.all()
ctx = {'last_login':request.session.get('social_auth_login_backend')}
return render_to_response("homepage.html", {'classifield_list': classifield_list, 'ctx':ctx}, context_instance=RequestContext(request))
A:
Ok, to anyone else who gest stuck with this:
DONT LOG IN TO THE ADMIN!
Since you're logged in to the admin, it keeps overwriting your admin user.
Log out of the admin, and it will work!
Yeeey!
| {
"pile_set_name": "StackExchange"
} |
Q:
How does a Child Tax Credit work to reduce my taxes?
Let's say I make 100K a year from my business and I have 3 kids under 9 years old. I read that each child can give me $2000 child tax credit.
So if my 100K business income is taxed and say its 40%:
100K x 40% (40K) = 60K take home
Does the child tax credit apply to the 100K first making it:
100K - 3 Kids (6K) = 94K income x 40% (37.6K) = 62.4K take home
OR is it:
100K x 40% (40K) = 60K + 6K child credit = 66K take home?
A:
There are two types of items that reduce your income tax: deductions and tax credits.
With a deduction, you subtract the deduction from your income before the tax is calculated. The benefit to you with a deduction is dependent on your tax rate. So if you are in the 22% tax bracket, a $6000 deduction would ultimately be worth $1320 to you.
With a tax credit, the tax is calculated first and then the tax credit is subtracted from your tax due. The tax credit is worth the full amount to you, because it directly reduces your tax bill.
Because the Child Tax Credit is a tax credit (not a deduction), a $6000 credit is worth the full $6000 to your situation.
| {
"pile_set_name": "StackExchange"
} |
Q:
regex to accept number in fomat 00.00
In my Angular App I am trying to set validation on input field such as
it should accept only 2 digit number or floating point number with 2 digit after point and before point too
Example
Accepted value
3,
33,
33.3,
33.33
Max value can be 99.99
Not accepting
333
33.333
3.333
333.33
Currently I am using
pattern="[+]?((\d{1,2})+(?:[\.][0-9]{0,2})?|\.[0-9]{0,2})$"
it validate 2 digit after point but failed to validate two digit before point as it accept 333.33 (which is wrong)
I also tried
pattern="[+]?(([0-9])+(?:[\.][0-9]{0,2})?|\.[0-9]{0,2})$"
But same thing happen , it does not validate two digit before point
A:
This pattern (\d{1,2})+ will match 1 - 2 digits and will repeat that one or more times.
A pattern like \.[0-9]{0,2} will also match just a single dot because the digits will match 0 - 2 times.
You could use an anchor to assert the start ^ and the end $ of the string. Match 1 or 2 digits with an optional part that matches a dot and 1 or 2 digits:
^\d{1,2}(?:\.\d{1,2})?$
Regex demo
Explanation
^ Assert the start of the string
\d{1,2} Match a digit 1 or 2 times
(?: Non capturing group
\.\d{1,2} Match a dot literally and 1 or 2 digits
)? Close non capturing group and make it optional
$ Assert the end of the string
If you want to match an optional plus at the beginning, the start of the regex could be^\+?
let pattern = /^\d{1,2}(?:\.\d{1,2})?$/;
let strs = [
"99",
"3",
"33",
"33.3",
"33.33",
"333",
"33.333",
"3.333",
"333.33"
];
strs.forEach((s) => {
console.log(s + " ==> " + pattern.test(s));
});
| {
"pile_set_name": "StackExchange"
} |
Q:
python reuse code, parse add to list and print match line
I am trying a code where:
List a contains: Benny and search in two.txt and prints matching line benny. And contains Adarsh and adds adarsh to list and should print the matching line of adarsh.
Coding:
import re
a=[]
with open('one.txt', 'r') as f:
for line in f:
res = re.findall(r'(?:Dr[.](\w+))', line)
if res:
a.extend(res)
print a
with open('two.txt', 'r') as f:
lines = f.readlines()
for key in a:
for line in lines:
if key in line:
print line
for ln1 in line #<-obtained output lines
res = re.findall(r'(?:Dr[.](\w+))', ln1)
if res:
a.extend(res)
for key in a:
for line in lines:
if key in line:
print line
one.txt contains:
Dr.Benny
two.txt contains:
Benny is a good friend Dr.Adarsh
Kim is a good boy
I am good boy
Adarsh and him are the best friends.
Output getting:
Benny is a good friend Dr.Adarsh
Desired Output:
Benny is a good friend Dr.Adarsh
Adarsh and him are the best friends
A:
The first part of your code is fine, so we can simplify it to:
import re
a = ['Benny']
However, the second part makes no sense. You are trying to extend a while iterating over it, which could create a never-ending loop. I think what you want is:
with open('two.txt') as f:
lines = f.readlines() # get lines from second file
b = [] # new names
for line in lines: # iterate once for the new names
if any(name in line for name in a):
b.extend(re.findall(r'(?:Dr[.](\w+))', line))
a += b # add new names to original names
for line in lines: # iterate again to display results
if any(name in line for name in a):
print line
Note that:
list.extend doesn't do anything if the list is empty, so there's no need to check; and
adding an optional whitespace character '\s?' to your regex and making the word boundary '\b' explicit would allow you to capture more sensibly-formatted names like 'Dr. Adarsh' (see demo).
| {
"pile_set_name": "StackExchange"
} |
Q:
Passing a string through a function. C
void printInstructions();
char *getUserWord();
int main()
{
printInstructions();
char *baseWord = getUserWord();
printf("%s", baseWord);
return 0;
}
void printInstructions()
{
printf(" Instructions: \n"
"===================================================================\n"
"= This program is a hangman game. =\n"
"= The first user will enter the name to be guessed =\n"
"= After that, the second user will guess the letters of the word =\n"
"= the second user will loose if they have three strikes =\n"
"===================================================================\n");
return;
}
char *getUserWord()
{
static char str[20];
scanf("%s", str);
return str;
}
My function getUserWord accomplishes its task by passing a string. From what I read online char *baseWord = getUserWord(); was the only way to assign the string to a variable within the main function. I do not know why this is working and I am not even sure what this is doing in memory. Below is what would make sense to me. Why would this not work?
char baseWord[21];
baseWord = getUserWord();
A:
You've fallen for the trap of believing that a pointer and an array are the same thing. They are not.
A string, by convention in C, is normally represented as an array of char, with an additional terminator of '\0' (the so-called nul-character) appended on the end. So the string literal "AB" is represented as an array of three char with values 'A', 'B', and '\0'.
A pointer is completely different from an array and, since a string is represented using an array of char, a pointer and a string are completely separate things. A pointer is a variable that contains an address in memory.
Where things get confused is the name of an array is, in a number of contexts, converted into a pointer. For example;
char x[] = "AB";
char *p = x;
This assignment works, but that doesn't mean an array is a pointer, or a pointer is an array. Instead, the name x is converted into a pointer to its first character. So the initialisation is functionally equivalent to
char *p = &x[0];
so p points to the character with value 'A' in the string "AB".
The same thing is happening in your code, so
char *getUserWord()
{
static char str[20];
scanf("%s", str);
return str;
}
is equivalent to
char *getUserWord()
{
static char str[20];
scanf("%s", &str[0]);
return &str[0];
}
In both cases, the pointer returned by getUserWord() has a value which is the address of str[0]. That is the value that is used to initialise baseWord in main()
char *baseWord = getUserWord();
Because baseWord now points at the first character of an array, it can be treated AS IF it is an array. In C, for a given value of i, this includes an equivalence between baseWord[i] (in main()) and str[i] (in getUserWord()). The fact that array syntax is used does not mean that a pointer and array are the same thing. It just means they can be worked on using the same syntax.
The important thing to realise, however, is that a pointer can be returned from a function (and the returned value assigned to, or used to initialise, another pointer) but an array cannot. So, in main() this is legal;
char *p = getUserWord();
p[0] = 'X'; /* will change str[0] in getUserWord() */
but this will not be;
char array[20] = getUserWord();
A:
Arrays cannot be assigned in C. This is mandated by the C Standard1. The lvalue in your second example is baseWord and has the type char[21] which is an array.
In your first example, when you return str, which has the type static char[20], it is converted to the type char* and can be returned from the function and assigned to pointer baseWord. Since str has static storage duration, the pointer points to a valid object.
If you want to return a non-static string, you can allocate it (using the function malloc), pass an existing string to a function or wrap the string with a struct.
1(Quoted from: ISO:IEC 9899:201X 6.3.2.1. Lvalues, arrays, and function designators 1 )
A modifiable lvalue is an lvalue that
does not have array type, does not have an incomplete type, does not have a const-
qualified type, and if it is a structure or union, does not have any member (including,
recursively, any member or element of all contained aggregates or unions) with a const-
qualified type.
A:
this will solve your problem.
#include <stdio.h>
void getUserWord(char* str);
int main(void)
{
char baseWord[21] = ""; /* initialize for avoiding undefined behavior in case no data is read */
getUserWord(baseWord);
printf("%s", baseWord);
return 0;
}
void getUserWord(char* str)
{
scanf("%s", str);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
C# Interface can be inherited in which languages?
We have designed an API which exposes a series of interfaces written in C#.
Apart from C# what languages can inherit from the C# interface?
The motivation behind this question is that we are writing the API documentation and would like to state which languages can utilise the interfaces we have written in C#.
For example can VB.NET or F# inherit an interface written in C#?
EDIT ----
I should note that I have since discovered the CLSCompliant attribute which forces the compiler to check for Common Language Specification (CLS) compliance at compile time. This is a useful attribute for public API's to ensure compliance with other .NET languages.
Link to article explaining the use of the CLSCompliant atribute
A:
If you stick to CLS (Common Language Specification), you can inherit that interfaces in all CLS compliant languages. For example Visual Basic, F# are CLS compliant and can inherit C# classes and interfaces.
An example: You cannot have the same names which only differ by case - e.g. METHOD(), method(), Method(), mEtHoD()... these ones cannot be present together in one interface.
Some programming languages may support only older CLS specification. For example CLS 1.0 languages don't support generic types.
You can found more information on CLS requirements in MSDN.
http://msdn.microsoft.com/en-us/library/12a7a7h3.aspx
http://msdn.microsoft.com/en-us/library/a2c7tshk.aspx
| {
"pile_set_name": "StackExchange"
} |
Q:
MPI Check if communicator is MPI_COMM_WORLD
I need to check if a MPI communicator is MPI_COMM_WORLD comm. This means that all processors are within this communicator.
I tried this
int isCommWolrd(MPI_Comm comm) {
int size_comm = 0;
int size_comm_world = 0;
MPI_Comm_size(comm, &size_comm);
MPI_Comm_size(MPI_COMM_WORLD, &size_comm_world);
return (size_comm == size_comm_world);
}
Is it sufficient to check only the sizes of the communicator. Can there be a false positive of negative?
A:
Use MPI_Comm_compare() and check the result is MPI_IDENT
int MPI_Comm_compare(MPI_Comm comm1, MPI_Comm comm2, int *result)
MPI_IDENT results if and only if comm1 and comm2 are handles for the same object (identical groups and same contexts).
MPI_CONGRUENT
results if the underlying groups are identical in constituents and rank order; these communicators differ only by context.
MPI_SIMILAR
results of the group members of both communicators are the same but the rank order differs. MPI_UNEQUAL results otherwise.
Your method can lead so false positive. For example, if you MPI_Comm_dup(MPI_COMM_WORLD, &comm), then the resulting comm has the same size than MPI_COMM_WORLD, but it a different communicator.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does the category of posets have pushouts and pullbacks?
Let $\mathbf{Poset}$ be the category of partially ordered sets with order-preserving maps. Does $\mathbf{Poset}$ have both pushouts and pullbacks?
A:
Yes it is complete and cocomplete because it is locally presentable. Of course, a colimit of posets will "crush" all loops because of antisymmetry. In particular, it has pushouts and pullbacks.
| {
"pile_set_name": "StackExchange"
} |
Q:
Deferred Shading OpenGL implementation
I'm currently trying to implement deferred shading in OpenGL 3.2 and have a problem that I just can't seem to solve no matter what I try.
I implemented it in two steps(geometry pass and lighting pass) like one would expect. After compiling and running it the screen shows the scene I prepared almost like one would expect it to look like. The colors of the objects are correct and they are also positioned where and how I wanted them to be.
The thing is, that the light calculations seem to have no influence on the color, what so ever. After a lot of hours I found out, that the textures for the positions and normals seem to contain the same content like the color texture.
If one changes the last line in the lighting fragment shader from fragColor = lightIntensity * color; to fragColor = lightIntensity * norm; or fragColor = lightIntensity * pos; it has absolutely no impact on how the screen is rendered.
I have tried a lot to figure out what is going wrong but honestly have no idea what it could be.
It would be awesome if someone could help me.
My render method looks like this:
void render()
{
//geometry pass
gBuffer->bindForWriting();
geometryShader->use(true);
calculateGBuffer();
//lighting pass
gBuffer->bindForReading(lightShader->programID());
lightShader->use(true);
drawOnScreen();
}
The initialization of the gBuffer object is like this:
void GBuffer::initializeFBO(int viewWidth, int viewHeight)
{
//initialize fbo and corresponding textures;
glGenFramebuffers(1, &fbo_ID);
glBindFramebuffer(GL_FRAMEBUFFER, fbo_ID);
glGenTextures(1, &colorTexture_ID);
glBindTexture(GL_TEXTURE_2D, colorTexture_ID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, viewWidth, viewHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorTexture_ID, 0);
glGenTextures(1, &posTexture_ID);
glBindTexture(GL_TEXTURE_2D, posTexture_ID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, viewWidth, viewHeight, 0, GL_RGB, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, posTexture_ID, 0);
glGenTextures(1, &normTexture_ID);
glBindTexture(GL_TEXTURE_2D, normTexture_ID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, viewWidth, viewHeight, 0, GL_RGB, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, normTexture_ID, 0);
GLuint attachments[3] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 };
glDrawBuffers(3, attachments);
glGenRenderbuffers(1, &depthBuffer_ID);
glBindRenderbuffer(GL_RENDERBUFFER, depthBuffer_ID);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, viewWidth, viewHeight);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthBuffer_ID);
//Check Status
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
qDebug() << "error while initializing framebuffer" << glCheckFramebufferStatus(GL_FRAMEBUFFER);
else{
qDebug() << "framebuffer successfully created";
initialized = true;
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
The methods bindForReading and bindForWriting:
void GBuffer::bindForWriting()
{
glBindFramebuffer(GL_FRAMEBUFFER, fbo_ID);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void GBuffer::bindForReading(GLuint programID)
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, colorTexture_ID);
GLuint samplerTexture_ID = glGetUniformLocation(programID, "colorTexture");
glUniform1i(samplerTexture_ID, 0);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, posTexture_ID);
samplerTexture_ID = glGetUniformLocation(programID, "positionTexture");
glUniform1i(samplerTexture_ID, 1);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, normTexture_ID);
samplerTexture_ID = glGetUniformLocation(programID, "normTexture");
glUniform1i(samplerTexture_ID, 2);
}
And at last the 4 Shaders:
Geometry Vertex Shader:
#version 150
#extension GL_ARB_separate_shader_objects : enable
uniform mat4 MVPMatrix;
uniform mat4 modelMatrix;
in vec4 in_position;
in vec4 in_color;
in vec2 in_texcoord;
in vec3 in_norm;
out vec4 color_varying;
out vec3 frag_position;
out vec3 norm_vec;
out vec2 texcoord_varying;
void main()
{
gl_Position = MVPMatrix * in_position;
vec4 worldPosition = (modelMatrix * in_position);
frag_position = worldPosition.xyz;
norm_vec = in_norm;
color_varying = in_color;
texcoord_varying = in_texcoord;
}
Geometry Fragment Shader:
#version 150
#extension GL_ARB_explicit_attrib_location : enable
in vec4 color_varying;
in vec3 frag_position;
in vec3 norm_vec;
in vec2 texcoord_varying;
layout (location = 0) out vec4 fragColor;
layout (location = 1) out vec3 fragPosition;
layout (location = 2) out vec3 frag_norm_vec;
uniform sampler2D myTexture;
void main()
{
vec4 texel = texture(myTexture, texcoord_varying);
fragColor = texel * color_varying;
fragPosition = frag_position;
frag_norm_vec = normalize(norm_vec);
}
Lighting VertexShader:
#version 150
#extension GL_ARB_explicit_attrib_location : enable
layout (location = 0) in vec2 in_position;
out vec2 texCoord;
void main()
{
gl_Position = vec4(in_position, 0, 1.0f);
texCoord = in_position;
if(texCoord.x == -1.0f)
texCoord.x = 0.0f;
if(texCoord.y == -1.0f)
texCoord.y = 0.0f;
}
Lighting Fragment Shader(without lighting calculation to make it shorter)
#version 150
#extension GL_ARB_separate_shader_objects : enable
out vec4 fragColor;
in vec2 texCoord;
uniform sampler2D colorTexture;
uniform sampler2D positionTexture;
uniform sampler2D normTexture;
void main()
{
//extract fragment data from fbo
vec3 pos = texture(positionTexture, texCoord).rgb;
vec3 norm = texture(normTexture, texCoord).rgb;
vec4 color = texture(colorTexture, texCoord);
fragColor = lightIntensity * color;
}
Sry for the code spamming but I can't narrow down the error.
A:
The problem is most likely in your order of operations here:
gBuffer->bindForReading(lightShader->programID());
lightShader->use(true);
where, in bindForReading(), you have calls like this one:
samplerTexture_ID = glGetUniformLocation(programID, "positionTexture");
glUniform1i(samplerTexture_ID, 1);
The glUniform*() calls set uniform values on the currently active program. Since you make the lightShader active after you make these calls, the uniform values will be set on the previously active program, which probably doesn't even have these uniforms.
Simply changing the order of these calls might already fix this:
lightShader->use(true);
gBuffer->bindForReading(lightShader->programID());
Also, you're using GL_RGB16F as the format of two of your buffers. The OpenGL implementation you use may support this, but this is not a format that is required to be color-renderable in the spec. If you want your code to work across platforms, you should use GL_RGBA16F, which is guaranteed to be color-renderable.
| {
"pile_set_name": "StackExchange"
} |
Q:
Disable editing of QTableView in rubyqt
I'm trying to disable editing of QTableView in rubyqt. It's supposed to be done by setting triggers to QAbstractView::NoEdiTriggers:
TableView.setEditTriggers(QAbstractView::NoEditTriggers);
The trouble is, rubyqt doesn't recognize Qt::AbstractView:
irb(main):008:0> require 'Qt4'
=> true
irb(main):009:0> Qt::AbstractView
NameError: uninitialized constant Qt::AbstractView
from (irb):9:in `const_missing'
from (irb):9
from /usr/bin/irb:12:in `<main>'
Is there another way to disable editing with ruby and qt?
EDIT
Oh, and outside of irb:
searcher.rb:72:in `const_missing': uninitialized constant Qt::AbstractView (NameError)
And searcher.rb:72:
@ui.tableView.setEditTriggers(Qt::AbstractView::NoEditTriggers)
Changing it to (Qt::AbstractView.NoEditTriggers) doesn't work, neither.
A:
require 'Qt4'
Qt::Application.new(ARGV) do
Qt::Widget.new do
self.window_title = 'Hello QtRuby v1.0'
resize(200, 100)
button = Qt::PushButton.new('Quit') do
connect(SIGNAL :clicked) { Qt::Application.instance.quit }
end
tv = Qt::TableView.new do
setEditTriggers(Qt::TableView::NoEditTriggers)
end
tm = Qt::StandardItemModel.new(1, 1) do
setItem(0,0,Qt::StandardItem.new("aaa"))
end
tv.setModel tm
self.layout = Qt::VBoxLayout.new do
add_widget(tv, 0, Qt::AlignRight)
add_widget(button, 0, Qt::AlignCenter)
end
show
end
exec
end
The main idea is that if no Abstract class from Qt is binded to Ruby, try looking for it's ancestors or implementations.
| {
"pile_set_name": "StackExchange"
} |
Q:
Supervising multiple gen_servers with same module / different arguments
I have a OTP application comprising a single supervisor supervising a small number of gen_servers. A typical child specification is as follows:
{my_server,
{my_server, start_link, [123]},
permanent,
5000,
worker,
[my_server]}
No problems so far.
I now want to an add extra gen_server to the supervisor structure, using the same module Module/Fn as above, but different arguments, eg
{my_server_2,
{my_server, start_link, [123]},
permanent,
5000,
worker,
[my_server_2]}
I thought this would work, but no:
=SUPERVISOR REPORT==== 15-Apr-2010::16:50:13 ===
Supervisor: {local,my_sup}
Context: start_error
Reason: {already_started,<0.179.0>}
Offender: [{pid,undefined},
{name,my_server_2},
{mfa,{my_server,start_link,[]}},
{restart_type,permanent},
{shutdown,5000},
{child_type,worker}]
Do the module arguments in the second element of each child specification need to be different ?
Thanks,
Justin
A:
My guess is that my_server registers its name using using gen_server:start_link/4, so that when the second one tries to start it can't because the name is already taken. The gen_servers will either have to start without a name (gen_server:start_link/3) or with different names.
It seems strange to vary the last element of the child spec, which identifies the list of modules used by the worker. Is this really what you intend?
| {
"pile_set_name": "StackExchange"
} |
Q:
Independent Element Witdths
I am trying to get the widths of eachMyDropDown in a td to be dependent on the child not the parent.
http://jsfiddle.net/qsuwg/13/
HTML
<td>
<span class="MyDropDown" name="NormalMenu">This is a Normal Menu.</span>
<ul class="MyDropDownList" name="NormalMenu">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
<span class="MyDropDown" name="ShortMenu">Short Menu</span>
<span class="MyDropDown" name="LongMenu">This is a very long menu. It is the longest one.</span>
</td>
JS
var x = document.getElementsByClassName('MyDropDown');
for (i = 0; i < x.length; i++) {
var s = x[i].innerHTML;
x[i].innerHTML = '<table>\n<tr>\n<td>' + s + '</td>\n<td><div></div></td>\n</tr>\n</table>';
}
CSS
.MyDropDown {
display:block;
background-color: #333;
color: #FFF;
border-radius: 5px;
white-space: nowrap;
}
.MyDropDown td:nth-child(1) {
padding:5px 15px;
border-right:1px solid #777777;
}
.MyDropDown td:nth-child(1):hover {
color:#CCC;
}
.MyDropDown div:first-child {
margin: 0px 5px;
border-left: 4px solid transparent;
border-right: 4px solid transparent;
border-top: 4px solid #FFF;
}
.MyDropDown td:nth-child(2):hover > div:first-child {
border-top-color:#CCC;
}
A:
Set display: inline-block, that will fix that problem.
.MyDropDown {
display: inline-block;
background-color: #333;
color: #FFF;
border-radius: 5px;
white-space: nowrap;
}
DEMO
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to change the package being used at runtime?
I have a large application that I am working to expand upon to allow customized usage by other departments within my organization.
Each department has different needs but may share some of the same classes as-is but other must be modified to accommodate the department's specific needs.
What I am wanting to do is create a new package for each department and move the relevant classes under those packages, thus keeping them separated, but all contained within the same overall application.
Right now, my package structure is similar to this:
[src]
- Main.java
[view]
- D1 FXMLs
[controllers]
- D1 Controllers
[model]
-D1 Classes
What I am hoping to do is restructure the project to include additional departments, many using the same class names as D1 (department 1).
[src]
- Main.java
[D1]
[view]
- D1 FXMLs
[controllers]
- D1 Controllers
[model]
-D1 Classes
[D2]
[view]
- D2 FXMLs
[controllers]
- D2 Controllers
[model]
- D2 Classes
...etc
I would need my Main.java to determine which package the operate out of, based on the value of a variable at runtime.
Is this even possible or would I still need to create entirely separate projects for each department and have a "Loader" program determine which one to run?
EDIT: Perhaps I have just stumbled on the answer myself. Would it work to just have Main.java call a class within the D1 or D2 package and have that class properly assign the packages going forward?
A:
While possibly not the most elegant solution, I used a simple approach (as my skill is not yet to the point where I understand Factories).
I just implemented what my edit to the question suggested, calling a different package's RootLayoutController depending on which package was needed.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to run script in docker container
I am trying to run a shell script in docker container but when I launch the container, runtime is unable to find the script.
Here is my Dockerfile
FROM ubuntu:18.04
ENV URL=http://localhost:8080
ENV ORG="name1"
ENV ADMIN="john"
ADD data-prep.sh /usr/local/data-prep.sh
RUN chmod +x /usr/local/data-prep.sh
RUN ls -l /usr/local/*.sh
CMD ["/user/local/data-prep.sh", URL, ORG, ADMIN]
and when i run the container, I get following error
/bin/sh: 1: [/user/local/data-prep.sh,: not found
Any idea what is wrong with my Dockerfile
A:
The CMD is looking into wrong path, it should be usr not user.
CMD ["/usr/local/data-prep.sh", URL, ORG, ADMIN]
Also if you want to consume ENV, you need to change CMD as variable not expending in CMD.
CMD ["sh","-c","/usr/local/data-prep.sh $URL $ORG $ADMIN"]
| {
"pile_set_name": "StackExchange"
} |
Q:
UISearchBar not receiving touches when moved to top of screen
I have a UISearchBar as a subview of a UIViewController's view. The UIViewController has a navigation bar. When I touch on the UISearchBar, I initiate an animation that moves the navigation bar up and off of the screen and move the search bar up to be in place of the navigation bar.
When I do this, the cancel button belonging to the search bar does not send touch events to the search bar's delegate. When I move the search bar up a few pixels, the search bar cancel button still works.
Any suggestions on what I might be doing wrong?
A:
How do you get the touch events (UIGestureRecognizers?)? Are you sure the UISearchBar is not behind any other view (maybe with a transparent background)? This might cause that your touch events are sent to this overlaying view.
Also possible issue might be you moved the UISearchBar out its super view. Check by giving its super view some backgroundColor.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to read an XML input file, manipulate some nodes (remove and rename some) and write the output to a new XML output file?
I need to read an XML file from internet and re-shape it.
Here is the XML file and the code I have so far.
library(XML)
url='http://ClinicalTrials.gov/show/NCT00001400?displayxml=true'
doc = xmlParse(url,useInternalNode=TRUE)
I was able to use some functions within the XML package with sucess(e.g., getNodeSet), but I am not an expert and there are some examples on the internet but I was not able to crack this problem myself. I also know some XPath but this was 4 years ago and I am not an expert on sapply and similar functions.
But my goal is this:
I need to remove a whole set of XML children branches about location, for example: <location> ... anything </location>. There can be multiple nodes with location data. I simply don't need that detail in the output. The XML file above always complies to an XSD schema. The root node is called <clinical_study>.
The resulted simplified file should be written into a new XML file called "data-changed.xml".
I also need to rename and move one branch from old nested place of
<eligibility>
<criteria>
<textblock>
Inclusion criteria are xyz
</textblock/>...
In new output ("data-changed.xml") the structure should say a different XML node and be directly under root node:
<eligibility_criteria>
Inclusion criteria are xyz
</eligibility_criteria>
So I need to:
read the XML into memory
manipulate the tree (prune it somewhere)
move some XML nodes to a new place and under a new name and
write the resulting XML output file.
Any ideas are greatly appreciated?
Also, if you know about a nice (recent !) tutorial on XML parsing within R (or book chapter which tackles it, please share the reference). (I read the vignettes by Duncan and these are too advanced (too concise)).
A:
Code to remove all location nodes:
r <- xmlRoot(doc)
removeNodes(r[names(r) == "location"])
A:
The quick answer to your question on how to apply an xpath to an xml file is to use xpathSApply. This works for me:
library(XML)
nct_url <- "http://clinicaltrials.gov/ct2/show/NCT00112281?resultsxml=true"
xml_doc <- xmlParse(nct_url, useInternalNode=TRUE)
elig_path <- "/clinical_study/eligibility/criteria/textblock"
elig_text <- xpathSApply(xml_doc, elig_path, xmlValue)
I'm doing some work with clinicaltrials.gov XML files, using R and its XML package. The package is tricky, and I only partially understand it. I've written a function to help deal with missing nodes in the XML:
findbyxpath <- function(xmlfile, xpath) {
xmldoc <- xmlParse(xmlfile)
result <- try(xpathSApply(xmldoc, xpath, xmlValue))
if(length(result) == 0) { # check for empty list, returned if node not found
return("")
} else {
return(result)
}
}
I use xml in files downloaded from clinicaltrials.gov ahead of time, so file is one of those. Then my example would instead look like this:
file <- "NCT00112281.xml"
elig_text <- findbyxpath(file, elig_path)
Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Configure Qt in Visual C++
I have Visual C++ 2010 and want to install and configure Qt. How to do it?
A:
You can install the vs2008 version - it will work with 2010
You can build Qt with vs2010 using the 2008 build environment - it will update the project to 2010.
BUT - if you are planning to write QT the visual studio add-in tool doesn't support VS2010, it needs vs2008
| {
"pile_set_name": "StackExchange"
} |
Q:
Cycling jquery css background image
I just want to change the thumb of a video while my mouse is over the ...
I've create this script:
var thumb=0;
var num_thumbs = 11;
$("#<?=($video->id) ?>_video").hover(function(){
open_hover_div[<?=($video->id) ?>]=true;
var timer = setTimeout(function(){
if (open_hover_div[<?=($video->id) ?>]==true) {$(".over_<?=($video->id) ?>").fadeOut(200);$(".overTxt_<?=($video->id) ?>").delay(201).fadeIn();}}
, 1000);
var thumbs = setTimeout(function(){if (open_hover_div[<?=($video->id) ?>]==true) {
if ( thumb > (num_thumbs-1) ) {thumb=0;}
$("#<?=($video->id) ?>_video").css('background-image','url(images/video/<?=$video->id?>/'+thumb+'.jpg)');
thumb++;
}}
, 1000);
});
$("#<?=($video->id) ?>_video").mouseleave(function(){
thumb=0;
open_hover_div[<?=($video->id) ?>]=false; $(".over_<?=($video->id) ?>").fadeIn();$(".overTxt_<?=($video->id) ?>").hide();
$("#<?=($video->id) ?>_video").css('background-image','url(images/video/<?=$video->id?>.png)');
});
the problem is in this part:
var thumbs = setTimeout(function(){
if (open_hover_div[id) ?>]==true) {
if ( thumb > (num_thumbs-1) ) {thumb=0;}
$("#id) ?>_video").css('background-image','url(images/video/id?>/'+thumb+'.jpg)');
thumb++;
}}
, 1000);
When i put my mouse over, I'll see just one change, and not a cycling changing...
The script has to do:
on over, show 1.jpg, 2.jpg etc every XXX millisecond;
reaching last image (e.g. 11.jpg, restart to 0.jpg)
on mouseleave, restart automatically to 0.jpg if I re-hover mouse
Hope to be clear about my problem :(
A:
You shall use setInterval instead of setTimeout.
var thumbs = setInterval(function(){ // ......
Then on the mouseleave event, you shall clear the interval as such:
clearInterval(thumbs);
thumbs = null;
| {
"pile_set_name": "StackExchange"
} |
Q:
JFrame intercept exit on close to save data
I created a window and want to intercept the exit with the method windowStateChanged to save the data before the application closes. However, it doesn't appear to be saving the data before it closes. How can I correct this?
see code below:
public class InventoryMainFrame extends JFrame implements WindowStateListener{
//set up the main window - instantiate the application
private InventoryInterface inventoryInterface; //panel that contains menu choices and buttons
public InventoryMainFrame(){ //main window
setTitle("Inventory System");
setSize (500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
//setLocationRelativeTo(null); //center window on the screen
inventoryInterface = new InventoryInterface(); //set up the panel that contains menu choices and buttons
add(inventoryInterface.getMainPane()); //add that panel to this window
pack();
setVisible(true);
//display window on the screen
}
public static void main(String[] args) {
//sets up front end of inventory system , instantiate the application
InventoryMainFrame aMainWindow = new InventoryMainFrame( );
}
@Override
public void windowStateChanged(WindowEvent w) {
//intercept the window close event so that data can be saved to disk at this point
if (w.getNewState()==WindowEvent.WINDOW_CLOSED){
//save the index file
try{
inventoryInterface.getInventory().saveIndexToFile();
System.out.println("saving");
dispose(); //dispose the frame
}
catch(IOException io){
JOptionPane.showMessageDialog(null,io.getMessage());
}
}
}
}
A:
You should try registering a WindowAdapter and override its windowClosing method. For more information, see How to Write Window Listeners.
| {
"pile_set_name": "StackExchange"
} |
Q:
Do I need to use thread synchronisation tools in Google App Engine?
I am using the Python 2.7 runtime on Google App Engine 1.7.4 with threadsafe: true in my app.yaml.
I have the following code:
@ndb.tasklet
def fn_a(container):
''' access datastore and mutate container '''
@ndb.tasklet
def fn_b(container):
''' access datastore and mutate container '''
@ndb.toplevel
def parallel_fn():
shared_container = set()
yield fn_a(shared_container), fn_b(shared_container)
fn_a() and fn_b() both access and mutate shared_container and are called in parallel_fn(). shared_container is a standard library set and therefore is not thread safe.
Should I wrap the mutator/accessor methods of shared_container in the appropriate threading standard library locks?
From what I understand of App Engine each instance is single threaded despite setting threadsafe: true. Therefore is the use of the threading lock objects not required?
Preliminary tests show locks are not required and would just add extra overhead as well as deadlock. It also seems the following should not be done
if object not in shared_container:
yield any tasklet operation
shared_container.add(object)
as shared_container might be updated by another line of execution during the yield operation rendering the object not in shared_container statement potentially invalid. However
if object not in shared_container:
shared_container.add(object)
yield any tasklet operation
would be absolutely fine.
A:
You don't need to add locking code because tasklets don't run in separate threads. Read up about it in the tasklet docs.
GAE is multithreaded if you set threadsafe: true. Different threads are launched to handle multiple requests on the same instance. Generally this is not a problem, since you're supposed to design your request handlers to be able to run across various server instances anyways.
This doesn't really apply to this question, but if you ever really do test threading issues, be careful. I'm not certain but I believe threading behavior is different between running on dev_appserver and production GAE servers, so make sure you test on both.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using an if statement to pass through variables ot further functions for python
I am a biologist that is just trying to use python to automate a ton of calculations, so I have very little experience.
I have a very large array that contains values that are formatted into two columns of observations. Sometimes the observations will be the same between the columns:
v1,v2
x,y
a,b
a,a
x,x
In order to save time and effort I wanted to make an if statement that just prints 0 if the two columns are the same and then moves on. If the values are the same there is no need to run those instances through the downstream analyses.
This is what I have so far just to test out the if statement. It has yet to recognize any instances where the columns are equivalen.
Script:
mylines=[]
with open('xxxx','r') as myfile:
for myline in myfile:
mylines.append(myline) ##reads the data into the two column format mentioned above
rang=len(open ('xxxxx,'r').readlines( )) ##returns the number or lines in the file
for x in range(1, rang):
li = mylines[x] ##selected row as defined by x and the number of lines in the file
spit = li.split(',',2) ##splits the selected values so they can be accessed seperately
print(spit[0]) ##first value
print(spit[1]) ##second value
if spit[0] == spit[1]:
print(0)
else:
print('Issue')
Output:
192Alhe52
192Alhe52
Issue ##should be 0
188Alhe48
192Alhe52
Issue
191Alhe51
192Alhe52
Issue
How do I get python to recgonize that certain observations are actually equal?
A:
When you read the values and store them in the array, you can be storing '\n' as well, which is a break line character, so your array actually looks like this
print(mylist)
['x,y\n', 'a,b\n', 'a,a\n', 'x,x\n']
To work around this issue, you have to use strip(), which will remove this character and occasional blank spaces in the end of the string that would also affect the comparison
mylines.append(myline.strip())
You shouldn't use rang=len(open ('xxxxx,'r').readlines( )), because you are reading the file again
rang=len(mylines)
There is a more readable, pythonic way to replicate your for
for li in mylines[1:]:
spit = li.split(',')
if spit[0] == spit[1]:
print(0)
else:
print('Issue')
Or even
for spit.split(',') in mylines[1:]:
if spit[0] == spit[1]:
print(0)
else:
print('Issue')
will iterate on the array mylines, starting from the first element.
Also, if you're interested in python packages, you should have a look at pandas. Assuming you have a csv file:
import pandas as pd
df = pd.read_csv('xxxx')
for i, elements in df.iterrows():
if elements['v1'] == elements['v2']:
print('Equal')
else:
print('Different')
will do the trick. If you need to modify values and write another file
df.to_csv('nameYouWant')
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does my UIStatusBar not display as desired through overriding preferredStatusBarStyle?
My status bar acts accordingly in the root controller in each tab of my UITabBarController. Once I add a modal to the UIViewController through present(viewControllerToPresent:) with .overFullscreen modalPresentationStyle it requires me to assign the preferredStatusBarStyle through the UIViewController that sent it. I need the UIViewController being presented to have a clear background and see through to the previoues UIViewControllers content. Am I doing something wrong?
A:
I solved the issue with a friend. The correct answer follows:
modalViewController.modalPresentationCapturesStatusBarAppearance = true
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the difference between kalman filter and extended kalman filter?
I am working SLAM based problems in robotics and I want to know whether I can use Kalman filter instead of the Extended kalman filter that is predominantly used ?
If not, what is the difference?
A:
The Kalman filter (KF) is a method based on recursive Bayesian filtering
where the noise in your system is assumed Gaussian. The Extended Kalman Filter (EKF) is an extension of the classic Kalman Filter for non-linear systems where non-linearity are approximated using the first or second order derivative. As an example, if the states in your system are characterized by multimodal distribution you should use EKF instead of KF.
| {
"pile_set_name": "StackExchange"
} |
Q:
String '0' is true|false in javaScript
Possible Duplicate:
Why does ('0' ? 'a' : 'b') behave different than ('0' == true ? 'a' : 'b')
'0' == false; // true
'0' || 1; // '0'
'0' ? true : false; // true
!!'0' // true
Is "==" will cast '0'-> 0 -> false, but other don't?
I want more detail.
A:
Javascript truth table for you.
'' == '0' // false
0 == '' // true
0 == '0' // true
false == 'false' // false
false == '0' // true
false == undefined // false
false == null // false
null == undefined // true
" \t\r\n" == 0 // true
Give it a try and you will be able to remove your confusion I think.
| {
"pile_set_name": "StackExchange"
} |
Q:
Highlighting HTML table cells depending on value (jQuery)
There is a table that will populate depending on the selected dropdown element. Here is the code (I didn’t insert a line with dropdown elements):
<table id="myPlaneTable" class="table table-bordered">
<tr>
<td style="width: 20%">Max speed</td>
<td style="width: 15%">450</td>
<td style="width: 15%">487</td>
<td style="width: 15%">450</td>
<td style="width: 15%">600</td>
</tr>
<tr>
<td style="width: 20%">Max speed</td>
<td style="width: 15%">580</td>
<td style="width: 15%">490</td>
<td style="width: 15%">543</td>
<td style="width: 15%">742</td>
</tr>
</table
Here's what it looks like
Since I was just starting to learn jQuery, I tried the following code, but it does not work
$("#myPlaneTable tbody tr.data-in-table").each(function () {
$(this).find('td').each(function (index) {
var currentCell = $(this);
var nextCell = $(this).next('td').length > 0 ? $(this).next('td') : null;
if (index%2==0&&nextCell && currentCell.text() !== nextCell.text()) {
currentCell.css('backgroundColor', 'red');
nextCell.css('backgroundColor', 'green');
}
});
});
The result I'm trying to get
Highlighting if only the best and worst value (not between)
If the data matches in several cells, it is necessary to highlight them too
If there is no data, the cell should be without highlighting
Data should be compared within one <tr>, since there will be several lines
A:
You can store all the values of each row in an array.
Then, store the minimum and maximum values, and finally apply the color to each <td> if the value match.
$("#myPlaneTable tbody tr").each(function () {
var values = [];
var tds = $(this).find('td');
tds.each(function () {
if ($.isNumeric($(this).text())) {
values.push($(this).text());
}
});
var min = Math.min.apply(Math, values);
var max = Math.max.apply(Math, values);
tds.each(function () {
if ($(this).text() == min) {
$(this).css('backgroundColor', 'red');
}
if ($(this).text() == max) {
$(this).css('backgroundColor', 'green');
}
});
});
| {
"pile_set_name": "StackExchange"
} |
Q:
how to setup the mailman gem
I'm trying the following guide on mailman
http://dansowter.com/mailman-guide/
up until the incoming_mail.rb part I was finding it really easy. But where do I put that file?
A:
The best place to me, is in the lib directory lib/incoming_mail.rb
| {
"pile_set_name": "StackExchange"
} |
Q:
How to capture group with optional number of letters/numbers followed by optional comma?
I'm altering the segment of a string in javascript and got the following working (first iteration -optional comma).
var foo = "wat:a,username:x,super:man"
foo.replace(/(username\:\w+)(?:,)*/,"go:home,");
//"wat:a,go:home,super:man"
The trick now is that I might actually replace a key/value with only the key ... so I need to capture the original group with both optional value + optional comma.
var foo = "wat:a,username:,super:man"
foo.replace(/ ????? /,"go:home,");
//"wat:a,go:home,super:man"
As a bonus I'd like the most concise way to capture both optional numbers/and letters (updating my original to also support)
var foo = "wat:a,username:999,super:man"
foo.replace(/ ????? /,"go:home,");
//"wat:a,go:home,super:man"
A:
You need to replace the + (1 or more occurrences of the preceding subpattern) quantifier with the * (0 or more occurrences of the preceding subpattern).
See Quantifier Cheatsheet at rexegg.com:
A+ One or more As, as many as possible (greedy), giving up characters if the engine needs to backtrack (docile)
A* Zero or more As, as many as possible (greedy), giving up characters if the engine needs to backtrack (docile)
Besides, you are not using any of the capturing groups defined in the pattern, so I suggest removing them.
.replace(/username:\w*,*/,"go:home,")
^
And if you have just 1 optional ,, use just the ? quantifier (1 or 0 repetition of the preceding subpattern):
.replace(/username:\w*,?/,"go:home,")
^
Note that in case you can have any characters before the end of string or comma, you can also use Fede's suggestion of using a negated character class: /username:[^,]*,*/. The [^,]* matches any character (even a newline) other than a comma.
Also, please note that you do not need to escape a colon. The characters that must be escaped outside of character class to be treated as literals are ., *, +, ?, ^, $, {, (, ), |, [, ], \. See RegExp MDN reference.
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating autocomplete for multiline textbox problems
Alright so the images weren't working so here is the code itself
private void textBox_KeyUp(object sender, KeyEventArgs e)
{
listBox1 = new ListBox();
Controls.Add(listBox1);
var x = textBox1.Left;
var y = textBox1.Top + textBox1.Height;
var width = textBox1.Width + 20;
const int height = 40;
listBox1.SetBounds(x, y, width, height);
listBox1.KeyDown += listBox1_SelectedIndexChanged;
List<string> localList = list.Where(z => z.StartsWidth(textBox1.Text)).toList();
if (localList.Any() && !string.IsNullOrEmpty(textBox1.Text))
{
listBox1.DataSource = localList;
listBox1.Show();
listBox1.Focus();
}
}
void listBox_SelectedIndexChanged(object sender, KeyEventArgs e)
{
if (e.KeyValue == (decimal)Keys.Enter)
{
textBox1.Text = ((ListBox)sender).SelectedItem.ToString();
listBox1.Hide();
}
}
I have run into some errors and was wondering if anyone could help me with them. I am using the answer to this question. Any help is appreciated.
Current problems are:
listBox1.KeyDown += listBox1_SelectedIndexChanged;
List localList = list.Where(z => z.StartsWidth(textBox1.Text)).toList();
My errors are highlighted in bold.
A:
You don't have any method listbox1_SelectedIndexChanged. So change
listBox1_SelectedIndexChanged
to
listBox_SelectedIndexChanged
and you have bolded out List. It has to be your list of some object, which you haven't shown us. Change the name.
Note: When you copy do change the names as they are defined in your code.
| {
"pile_set_name": "StackExchange"
} |
Q:
Should update redux state onchange events?
I'm having that question on mind. It's right to update redux state on handleChange event? I mean, i guess that working with hooks to have like an intermediate state and only update the redux state when i'm skipping that component could be a better practice.
This is my code, a very simple example.
const handleTitle(event= => {
setCursoTitle(event.target.value);
}
And this is how it should be to avoid updates on every onChange event.
const [cursoTitle, setcursoTitle] = useState('');
const handleTitle = (event) => {
//handle onChange from Text Field
setCursoTitle(event.target.value);
}
const exitForm = () => {
//update Redux State
setCursoTitle(cursoTitle);
}
It's very expensive to update the redux state on every on change event? What way do you think is better ?
A:
It really depends of the scenario.Per example, if you are using websocket, i dont think your solution will work properly.
Take a look at https://github.com/xnimorz/use-debounce. It's a way to update your redux state only when the user stop typing. This way, your redux really represent your current data and you don't re-render your component on every key down.
| {
"pile_set_name": "StackExchange"
} |
Q:
Escape sequence for the escape key
On an SSH terminal, there is a command that takes over the terminal window, and it says I can press escape to end it.
My SSH terminal does not handle the escape key. What is the escape sequence (Ctrl+something) that I can use in its place. (or is there one)
I can just disconnect from SSH and connect again but I thought I would go ahead check if there was an escape sequence for the escape key. Would that even work?
A:
I think it's Ctrl + [ ( ^[ ).
filler
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to "register" an iPhone App Name?
I was wondering if It is possible to "register" an iPhone App Name before the app goes on the app store?
Example:
A developer comes up with a really clever name for a iphone game.
He wants to register the name before he programs the game so that no one else comes up with the same name.
A:
You can squat a name for something like 90 days per recent Apple iTunesConnect changes. If you do not upload a binary in that time, it will be deleted and you will be unable to use it again.
There exists a loophole I have found though I don't know how long it will stay open. It seems that uploading a binary, any binary, then immediately rejecting it will prevent you from deletion. I don't condone squatting, but sometimes, apps take longer than 90 days to develop.
A:
Yes, you can, but only for a limited amount of time. When I tried it, the time period was 120 days, but this may have been changed to 90 days. EDIT: It seems that this is now 180 days, based on the comments below.
A developer can choose enter information about the application before uploading it, but Apple will remove the app and it's meta information if the name is not used within the grace period. You cannot use the name ever again after that.
I have, however, some apps that were rejected on the first review and were never re-submitted. It seems that those names are still available to me. Just don't submit a really lame first submission or Apple will know that you are "parking" the name.
Here's a screenshot of my email from Apple:
| {
"pile_set_name": "StackExchange"
} |
Q:
ASP.Net - Handling session data in a load balanced environment?
How does ASP.Net deal with session data in a load balanced environment?
Let's say a user makes multiple requests while navigating through a couple of pages?
Do all requests go to the same server in the load balancer?
What can I do if they don't all point to the same server? how do I deal with my session data?
A:
You need to ensure that your NLB has the ability to enable "Sticky" sessions.
If this isn't an option, then you need to look at using the ASP.Net Session Modes to configure either a Session Server, or some backing store like SQL Server.
| {
"pile_set_name": "StackExchange"
} |
Q:
Determine the rate limit for requests
I have a question about rate limits.
I take a data from the CSV and enter it into the query and the output is stored in a list.
I get an error because I make too many requests at once.
(I can only make 20 requests per second). How can I determine the rate limit?
import requests
import pandas as pd
df = pd.read_csv("Data_1000.csv")
list = []
def requestSummonerData(summonerName, APIKey):
URL = "https://euw1.api.riotgames.com/lol/summoner/v3/summoners/by-name/" + summonerName + "?api_key=" + APIKey
response = requests.get(URL)
return response.json()
def main():
APIKey = (str)(input('Copy and paste your API Key here: '))
for index, row in df.iterrows():
summonerName = row['Player_Name']
responseJSON = requestSummonerData(summonerName, APIKey)
ID = responseJSON ['accountId']
ID = int(ID)
list.insert(index,ID)
df["accountId"]= list
A:
If you already know you can only make 20 requests per second, you just need to work out how long to wait between each request:
Divide 1 second by 20, which should give you 0.05. So you just need to sleep for 0.05 of a second between each request and you shouldn't hit the limit (maybe increase it a bit if you want to be safe).
import time at the top of your file and then time.sleep(0.05) inside of your for loop (you could also just do time.sleep(1/20))
| {
"pile_set_name": "StackExchange"
} |
Q:
Using the MVP pattern with MonoDroid
Here's my attempt at using MVP (or Passive View more specifically?) with a MonoDroid app:
https://gist.github.com/857356
My main goal isn't reuse, but rather increased testability and (hopefully) improved maintainability. Reuse would be a nice side-effect, but I currently don't plan to do a MonoTouch version or anything.
I'm generally pretty happy with it (with one exception), but I definitely need some critique/evaluation.
The one exception: the method "GetPortfolioIdForContextMenu" returns an 'int', which doesn't feel quite right, given the rest of the methods don't have to do that. It just feels wrong, but I can't quite put my finger on 'why', or what to even do about it.
A:
Have you considered the MVVM pattern? I use it with WPF development, although I haven't used it with my Android projects yet. I love the pattern, it's very similar to MVP, except that the ViewModel does not know that the View exists. MVVM is typically only possible with languages that support databinding.
Some useful links:
Wikipedia MVVM
You'll need the Android Binding project the motivation behind it. [main benefit: testing]
Tutorial on MVVM with Android.
Hope some of this helps.
-JP
Edit: Just realized that you're using MonoDroid. This may not be as useful. Maybe it'll be useful to other internet searchers though.
A:
onCreateContextMenu contains the View for which context menu is to be created. You can set the portfolio id as tag for each view and then use it in the onCreateContextMenu. HTH !
| {
"pile_set_name": "StackExchange"
} |
Q:
Converting 3D polar coordinates to cartesian coordinates
I've been doing a lot of searching on the math behind this conversion, and the best I've been able to come up with so far is this:
x = sin(horizontal_angle) * cos(vertical_angle)
y = sin(horizontal_angle) * sin(vertical_angle)
z = cos(horizontal_angle)
For arbitrary angles, this works fine. Where I have problems is when one of the rotations is 0 degrees. At 0 degrees (or 180, or 360, or...), sin() is going to be zero, which means both the x and y coordinates I get out of the above formulas will be zero, regardless of what the other angle was set to.
Is there a better formula out there that doesn't mess up at certain angles? My searches so far haven't found one, but there has to be a solution to this issue.
Update:
After some experimentation, I found that my main misunderstanding was the fact that I was assuming the poles of my spherical coordinates to be vertical (like latitude and longitude on a planet), while they were actually horizontal (projected into the screen). This was due to the fact that I'm working in screen space (x/y mapped to the screen, z projected into the screen), rather than a traditional 3D environment, but somehow didn't think that would be a contributing factor.
The final formula that worked for me to get the poles oriented correctly:
x = cos(horizontal_angle) * sin(vertical_angle)
y = cos(vertical_angle)
z = sin(horizontal_angle) * sin(vertical_angle)
A:
Your formula is correct for all angles. But the names that you've given the angles are probably not quite right. What you've called "horizontal angle" is the inclination angle - the angle between the vector and the z-axis. So if "horizontal angle" is 0, then the point lies on the z-axis, which means that it is correct for x and y to both be 0. What you've called "vertical angle" is actually the angle in the x-y plane. If it is 0, then the point lies in the x-z plane, so y is correctly set to 0.
| {
"pile_set_name": "StackExchange"
} |
Q:
storing data with name of author - laravel 5.2
I have hasMany relation to my model user and reports.
I want to set author name for the reports. (Like a blog-post author)
my model User:
public function reports() {
return $this->hasMany('App\Report', 'author_id');
}
model Report
public function user() {
return $this->belongsTo('App\User', 'author_id');
}
and my controller:
public function create()
{
$category = Category::lists('title','id');
return view('dash.reports.create')->with('category', $category);
}
/**
* Store a newly created resource in storage.
*
* @return void
*/
public function store(Request $request)
{
$this->validate($request, ['title' => 'required', ]);
Report::create($request->all());
Session::flash('flash_message', 'Report added!');
return redirect('dash/reports');
}
I'm able to set in in phpmyadmin, but how can i set it with my controller?
edit: my view:
{!! Form::open(['url' => '/dash/reports', 'class' => 'form-horizontal']) !!}
<div class="form-group {{ $errors->has('title') ? 'has-error' : ''}}">
{!! Form::label('title', 'Servizio', ['class' => 'col-sm-3 control-label']) !!}
<div class="col-sm-6">
{!! Form::text('title', null, ['class' => 'form-control', 'required' => 'required']) !!}
{!! $errors->first('title', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group {{ $errors->has('title') ? 'has-error' : ''}}">
{!! Form::label('date', 'Data lavorativa', ['class' => 'col-sm-3 control-label']) !!}
<div class="col-sm-2">
{!! Form::selectRange('day', 1, 31, null, ['class' => 'form-control']) !!}
{!! $errors->first('day', '<p class="help-block">:message</p>') !!}
</div>
<div class="col-sm-2">
{!! Form::selectMonth('month', null, ['class' => 'form-control']) !!}
{!! $errors->first('month', '<p class="help-block">:message</p>') !!}
</div>
<div class="col-sm-2">
{!! Form::select('year', array('2016' => '2016', '2015' => '2015'), null, ['class' => 'form-control']) !!}
{!! $errors->first('year', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group {{ $errors->has('category_id') ? 'has-error' : ''}}">
{!! Form::label('category_id', 'Cliente', ['class' => 'col-sm-3 control-label']) !!}
<div class="col-sm-6">
{!! Form::select('category_id', $category, null, ['class' => 'form-control'] ) !!}
{!! $errors->first('category_id', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-3">
{!! Form::submit('Create', ['class' => 'btn btn-primary form-control']) !!}
</div>
</div>
{!! Form::close() !!}
A:
Very easy. Replace Report::create... with this.
$user = Auth::user();
$report = new Report($request->all());
$report->author()->associate($user);
$report->save();
Make sure you use Auth; up at the top.
This uses the Auth object to get the current user,
Builds a new Report using the $request data without saving,
Tells the report we're associating $user as the author for the model,
Saves the report with the authorship information.
| {
"pile_set_name": "StackExchange"
} |
Q:
Defining the goal function in an optimization problem
I have an optimization problem. There are a few quantities, call them $a, b, c$, that describe how good a solution is. However, they all have different priority, from highest to lowest: $a, b, c$.
The goal is to minimize the values of $a, b, c$. The difference in priorities means that the solution with identical value of $a$, lower value of $b$ is lower than the other solution, no matter what the value of $c$ is. Similarly, if the value of $a$ is lower, then no matter what $b$ or $c$ is, the solution is better better than the other solution.
What's the best way to define a goal function for this problem? I don't know the range of those values. I was thinking about using some weight parameters, like multiplying $a$ by the greatest weight, $b$ by lower weight, and $c$ by the lowest weight value.
A:
If you know the minimum and maximum values for $a,b,c$, you can use a weighted linear combination. e.g., if $a,b,c \in [0,1000]$ (they are all between 0 and 1000), then you can use the objective function
$$\Phi(a,b,c) = 10^6 a + 10^3 b + c.$$
Minimizing this function is guaranteed to be optimal under your partial order.
Sometimes, even when you don't have upper and lower bounds, you can still use an objective function like the one above, as a heuristic. It's not guaranteed to give optimal results, but it might be good enough in your particular application.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create thread safe GetEventHandler()?
public partial class JobDataDuplicatorForm : Form
{
public JobDataDuplicatorForm(IJobDataDuplicatorEngine engine)
{
_engine.CopyStartedEvent += GetEventHandler(OnCopyStarted);
_engine.CopyEndedEvent += GetEventHandler(OnCopyEnded);
...
}
private static EventHandler GetEventHandler(Action action)
{
return (sender, args) => action();
}
private void OnCopyStarted()
{
copyStatus.Text = "Copy progress: ";
generateButton.Enabled = false; // Cross-thread operation not valid
}
}
I have the following exception:
Additional information: Cross-thread operation not valid: Control
'generateButton' accessed from a thread other than the thread it was created on.
Can I fix the exception by changing GetEventHandler() instead of wrapping each button in different places like this
Invoke((MethodInvoker)delegate {
generateButton.Enabled = false;
}); ?
How can I do this?
A:
From your comments you said you call JobDataDuplicatorForm(IJobDataDuplicatorEngine engine) from a background thread.
Your class is a Form, any windows controls (Which includes Form) must be initially created on the UI thread or things like Invoke and InvokeRequired break. Whatever code is calling the constructor of JobDataDuplicatorForm must do that call from the UI thread.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do we show that prime C* algebras have trivial center
A prime C* algebra is a C* algebra with the property that the product of any two of its non zero ideals is non zero. The claim is that it has trivial center, i.e., the only central elements are multiplies of the identity. I would be grateful for a hint on how to prove this. Thanks.
A:
The proof in ougao's answer is wrong; I've made a few comments there. Below is a different argument.
Suppose that the centre $Z(A)$ of $A$ has an element that is not a scalar multiple of the identity. Then $A$ has a selfadjoint central element $a\in Z(A)$ that is not a scalar multiple of the identity. So the spectrum of $a$ has two or more points. Let $\alpha=\min\sigma(a)$, $\beta=\max\sigma(a)$; we have $\alpha<\beta$.
Let $f\in C[\alpha,\beta]$ with $f(\alpha)=1$, and $f(t)=0$ for $t\geq (\alpha+\beta)/2$; similarly, let $g\in C[\alpha,\beta]$ with $g(\beta)=1$ and $g(t)=0$ for $t\leq(\alpha+\beta)/2$. Put $b=f(a)$, $c=g(a)$. Then $b,c\in Z(A)$ (since $a\in Z(A)$ and $Z(A)$ is a C$^*$-algebra) and, as $fg=0$, we have $bc=0$. Then $bAc=Abc=0$, so $A$ is not prime (or, consider the nonzero ideals $A_b=\overline{Ab}$ and $A_c=\overline{Ac}$ generated by $b$ and $c$ respectively, and note that $A_bA_c=0$).
| {
"pile_set_name": "StackExchange"
} |
Q:
How to capture value of listbox item
I am trying to capture the value of the selected item in a list box, and store that value into my database. My goal is when I choose "Male" (or "Female") the "Male" (or "Female") will be added to the Gender [column] in the database but I don't know how to do it.
MyDatabase:
[Table]
public class Member : INotifyPropertyChanged, INotifyPropertyChanging
{
// Define ID: private field, public property, and database column.
private int _ID;
[Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
public int ID
{
get { return _ID; }
set
{
if (_ID != value)
{
NotifyPropertyChanging("ID");
_ID = value;
NotifyPropertyChanged("ID");
}
}
}
private string _FullName;
[Column]
public string FullName
{
get { return _FullName; }
set
{
if (_FullName != value)
{
NotifyPropertyChanging("FullName");
_FullName = value;
NotifyPropertyChanged("FullName");
}
}
}
private string _Address;
[Column]
public string Address
{
get { return _Address; }
set
{
if (_Address != value)
{
NotifyPropertyChanging("Address");
_Address = value;
NotifyPropertyChanged("Address");
}
}
}
private string _Gender;
[Column]
public string Gender
{
get { return _Gender; }
set
{
if (_Gender != value)
{
NotifyPropertyChanging("Gender");
_FullName = value;
NotifyPropertyChanged("Gender");
}
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
// Used to notify that a property changed
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
#region INotifyPropertyChanging Members
public event PropertyChangingEventHandler PropertyChanging;
// Used to notify that a property is about to change
private void NotifyPropertyChanging(string propertyName)
{
if (PropertyChanging != null)
{
PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
}
}
#endregion
}
public class GenderPicker
{
public string sex
{
get;
set;
}
}
My ListPicker list:
public Add()
{
InitializeComponent();
this.DataContext = App.MainViewModel;
List<GenderPicker> picker = new List<GenderPicker>();
picker.Add(new GenderPicker() { sex = "Male" });
picker.Add(new GenderPicker() { sex = "FeMale" });
this.ListPicker.ItemsSource = picker;
}
My Add Button: I dont know what can be filled in ???????????????
Member is the table. Column is FullName | Address | Gender
private void Add_Click(object sender, EventArgs e)
{
if ((addaddress.Text.Length > 0) && (addfullname.Text.Length > 0))
{
Member newInfo = new Member
{
FullName = addfullname.Text,
Address = addaddress.Text,
Gender = ????????????????
};
App.MainViewModel.Addinfo(newInfo);
}
}
And my selection changed in LIstpicker:
private void ListPicker_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var samplesex =(GenderPicker)ListPicker.SelectedItem;
var selectedsex = (samplesex.sex).ToString();
}
A:
Have you tried? Found on stackoverflow.com
(ListPicker.SelectedItem as GenderPicker).sex.ToString()
or in your example:
private void Add_Click(object sender, EventArgs e)
{
if ((addaddress.Text.Length > 0) && (addfullname.Text.Length > 0))
{
Member newInfo = new Member
{
FullName = addfullname.Text,
Address = addaddress.Text,
Gender = (ListPicker.SelectedItem as GenderPicker).sex.ToString()
};
App.MainViewModel.Addinfo(newInfo);
}
}
you could/should make a property to have a default value so you don't receive NullReference exceptions if ListPicker has a NULL selected.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I layout a list of images + labels I gather from my DB properly inside my Horizontal StackLayout/Scrollview?
I have a two issues with my layout problem.
The first issue is that I am trying to make the Image Aspect.AspectFill but the image does not AspectFill with my current code (they remain with different sizes).
And the second issue is the layout itself.
With my current code what It looks like is this:
< IMAGE -> IMAGENAME -> LABEL -> IMAGE -> IMAGENAME -> LABEL etc. >
And I do not want the IMAGENAME to be shown.
What I want to achieve is this, where the IMAGE is connected with the right LABEL underneath:
< IMAGE IMAGE IMAGE IMAGE >
< LABEL LABEL LABEL LABEL >
This is the current code that I am working with:
My XAML:
<ScrollView Orientation="Horizontal" HorizontalOptions="StartAndExpand">
<StackLayout x:Name = "myStack" Orientation="Horizontal"
HorizontalOptions="StartAndExpand">
</StackLayout>
</ScrollView>
And this is my code:
public List <string> imageList = new List<string> ();
async void loadImages ()
{
var getImages = await phpApi.getImages ();
foreach (var theitems in getImages ["results"])
{
var value = "";
var valueTwo = "";
imageList.Add
(value = theitems ["Photo"].ToString());
imageList.Add
(valueTwo = theitems ["PhotoName"].ToString());
}
for (int i = 0; i < imageList.Count; i++) {
var image = new Image ();
AbsoluteLayout.SetLayoutBounds (image, new Rectangle (0.5, 0.6, 0.5, 0.4));
image.Source = imageList [i];
image.Aspect = Aspect.AspectFill;
var label = new Label ();
AbsoluteLayout.SetLayoutBounds (label, new Rectangle (0.5, 1.0, 0.5, 0.4));
label.Text = imageList [i];
myStack.Children.Add (image);
myStack.Children.Add (label);
}
}
A:
public Dictionary<string, string> imageList = new Dictionary<string,string> ();
async void loadImages ()
{
var getImages = await phpApi.getImages ();
foreach (var theitems in getImages ["results"])
{
imageList.Add(
theitems ["Photo"].ToString(),
theitems ["PhotoName"].ToString()
);
}
foreach (var key in imageList.Keys) {
// vertical stack for each image/label pair
var inner = new StackLayout();
var image = new Image ();
image.Source = key;
image.Aspect = Aspect.AspectFill;
var label = new Label ();
label.Text = imageList [key];
inner.Children.Add(image);
inner.Children.Add(label);
myStack.Children.Add (inner);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Android - How to retrieve data from multiple SQLite tables?
I have two tables and I want to show parts of both in a list view using a list Activity. But only one of the tables is showing. I have a foreign key set but nothing except the one table is showing.
My Tables
db.execSQL("CREATE TABLE " + WW_TABLE +
" (" + KEY_ROWIDLL + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_LAT + " TEXT NOT NULL, " +
KEY_LON + " TEXT NOT NULL);");
db.execSQL("CREATE TABLE " + WW_TIMETABLE +
" (" + KEY_ROWIDTIME + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_HOUR + " TEXT NOT NULL, " +
KEY_FOREIGN + " INTEGER," +
" FOREIGN KEY ("+KEY_FOREIGN+") REFERENCES "+WW_TABLE+" ("+KEY_ROWIDLL+") ON DELETE CASCADE);");
How I query the information
public Cursor fetchTime() {
// TODO Auto-generated method stub
return ourdb.query(WW_TIMETABLE, new String[] {KEY_ROWIDTIME, KEY_HOUR, KEY_FOREIGN}, null, null, null, null, null);
}
Where I View the Information
private void fillData() {
// Get all of the rows from the database and create the item list
mTimeNotesCursor = mDbHelper.fetchTime();
startManagingCursor(mTimeNotesCursor);
// startManagingCursor(mNotesCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{WWDatabase.KEY_HOUR,WWDatabase.KEY_FOREIGN};
//String[] fromTime = new String[]{WWDatabase.KEY_HOUR};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.textView2, R.id.textView3};
//int[] toTime = new int[]{R.id.textView4};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.time_text_row, mTimeNotesCursor, from, to);
setListAdapter(notes);
// SimpleCursorAdapter notesTime =
//new SimpleCursorAdapter(this, R.layout.time_text_row, mTimeNotesCursor, fromTime, toTime);
//setListAdapter(notesTime);
}
I do not get any errors with this, But like I said it only shows the one table. All help is appreciated.
A:
Use the rawQuery:
private final String MY_QUERY = "SELECT * FROM table_a a INNER JOIN table_b b ON a.id=b.other_id WHERE b.property_id=?";
OR
private final String MY_QUERY = "SELECT * FROM table_a a INNER JOIN table_b b ON a.id=b.other_id WHERE a.property_id=?";
db.rawQuery(MY_QUERY, new String[]{String.valueOf(propertyId)});
| {
"pile_set_name": "StackExchange"
} |
Q:
Can drbd be used for mongodb replication or active/passive setting?
From this guide we know DRBD can used for PostgreSQL Active/Passive setting:
https://www.howtoforge.com/how-to-set-up-an-active-passive-postgresql-cluster-with-pacemaker-corosync-and-drbd-centos-5.5-p4
It use /dev/drbd0 to mount PostgreSQL data path /var/lib/psql:
mount -t ext3 /dev/drbd0 /var/lib/pgsql
So is it possible to use this way to mount a MongoDB data path and where is that path?(Maybe this on CentOS 7.3: /var/lib/mongo)
If use this way, the multiple nodes will use the synced same file data but not master-slave replication. Maybe this is called master-master replication. Is it good?
A:
Answer is NO, you cannot use it with MongoDB. Result would be corrupted data, sooner or later. MongoDB keeps active data in memory and don't know how to react if data is changed "on-the-fly" at disk.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do you handle line breaks in HTML Encoded MVC view?
I am unsure of the best way to handle this. In my index view I display a message that is contained in TempData["message"]. This allows me to display certain error or informational messages to the user when coming from another action (for example, if a user tries to enter the Edit action when they don't have access, it kicks them back to the Index with a message of "You are not authorized to edit this data").
Prior to displaying the message, I run Html.Encode(TempData["message"]). However, I have recently come into the issue where for longer messages I want to be able to separate the lines out via line breaks (<br>). Unfortunately (and obviously), the <br> gets encoded by Html.Encode so it doesn't cause an actual line break.
How do I process line breaks correctly in Html Encoded strings?
A:
The easiest solution I've seen is:
@MvcHtmlString.Create(Html.Encode(TempData["message"]).Replace(Environment.NewLine, "<br />"))
If you are using a razor view, you should not have to call Html.Encode normally. By default, Razor html encodes all output. From Scott Gu's blog introducing Razor:
By default content emitted using a @ block is automatically HTML encoded to better protect against XSS attack scenarios.
A:
I agree with @Roger's comment - there is not really any need to encode anything that you have total control over.
If you still wish to be better safe than sorry (which isn't a bad thing), you could use the Microsoft AntiXss library and use the .GetSafeHtmlFragment(input) method - see HTML Sanitization in Anti-XSS Library
e.g.
<%= AntiXss.GetSafeHtmlFragment(TempData["message"]) %>
A:
FYI, the Microsoft Web Protection Library (A.K.A. Microsoft AntiXSS Library) developers seem to have broken the assembly and pulled all previous versions that were working. It is no longer a viable solution in its current state. I was looking at it as a solution for this problem before reading the comments. All 18 of the current ratings for the latest release are negative and complain about it being broken with no updates from the developers so I didn't even try it.
I went with @ICodeForCoffee's solution since I'm using Razor. It is simple and seems to work quite well. I needed to take potentially lengthy descriptions with line breaks and format them so the line breaks would come through in the page.
Just for completeness, here's the code I used which is @ICodeForCoffee's code modified to use the description field of the view's model:
@MvcHtmlString.Create(Html.Encode(Model.Description).Replace(Environment.NewLine, "<br />"))
| {
"pile_set_name": "StackExchange"
} |
Q:
how to select rows with float64 nan?
I have a dataframe from excel which has several NaNs in rows.I`d like to replace rows whose values are all NaNs by another baseline row.
The original dataframe is like this:
Country Name Years tariff1_1 tariff1_2 tariff1_3
830 Hungary 2004 9.540313 6.287314 13.098201
831 Hungary 2005 9.540789 6.281724 13.124401
832 Hungary 2006 NaN NaN NaN
833 Hungary 2007 NaN NaN NaN
834 eu 2005 8.55 5.7 11.4
835 eu 2006 8.46 5.9 11.6
836 eu 2007 8.56 5.3 11.9
so if the tariffs for Hungary of a specific year are all NaNs,this row should be replaced by the eu data, according to the exact year.
The ideal result is :
Country Name Years tariff1_1 tariff1_2 tariff1_3
830 Hungary 2004 9.540313 6.287314 13.098201
831 Hungary 2005 9.540789 6.281724 13.124401
832 Hungary 2006 8.46 5.9 11.6
833 Hungary 2007 8.56 5.3 11.9
834 eu 2005 8.55 5.7 11.4
835 eu 2006 8.46 5.9 11.6
836 eu 2007 8.56 5.3 11.9
I looked into the type of the NaN in a specific row ('Hungary',2006) and it turns to be 'float64'.So it turns out as ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'' after I use np.isnan.
So I adopted math.isnan. But it doesn`t seem to detect the NaN in my test row:
test=df.loc[(df['Country Name'] == 'Hungary') & (df['Years']== 2006)]
test.iloc[:,4]
Out[293]:
832 NaN
Name: tariff1_3, dtype: float64
math.isnan(any(test))
Out[294]:False
np.isnan(any(test))
Out[295]:ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
Here are my original lines.
Eu=['Austria','Belgium','Curacao','Denmark','Finland','France','Germany']
for country in Eu:
for year in range(2001,2012)
if math.isnan(all(df.loc[(df['Country Name'] == country) & (df['Years'] == year)])):
df.loc[(df['Country Name'] == country) & (df['Years'] == year)]=df.loc[(df['Country Name'] == 'eu') & (df['Years'] == year)]
Thanks !
A:
If need convert only NaNs rows:
print (df)
Country Name Years tariff1_1 tariff1_2 tariff1_3
830 Hungary 2004 9.540313 6.287314 13.098201
831 Hungary 2005 NaN 6.281724 13.124401
832 Hungary 2006 NaN NaN NaN
833 Hungary 2007 NaN NaN NaN
834 eu 2005 8.550000 5.700000 11.400000
835 eu 2006 8.460000 5.900000 11.600000
836 eu 2007 8.560000 5.300000 11.900000
Eu=['Austria','Belgium','Curacao','Denmark','Finland','France','Germany','Hungary']
#all columns without specified in list
cols = df.columns.difference(['Country Name','Years'])
#eu DataFrame for repalce missing rows
eu = df[df['Country Name'] == 'eu'].drop('Country Name', 1).set_index('Years')
print (eu)
tariff1_1 tariff1_2 tariff1_3
Years
2005 8.55 5.7 11.4
2006 8.46 5.9 11.6
2007 8.56 5.3 11.9
#filter only Eu countries and all missing values with columns cols
mask = df['Country Name'].isin(Eu) & df[cols].isnull().all(axis=1)
#for filtered rows replace missing rows by fillna
df.loc[mask, cols] = pd.DataFrame(df[mask].set_index('Years')
.drop('Country Name', 1).fillna(eu).values,
index=df.index[mask], columns=cols)
print (df)
Country Name Years tariff1_1 tariff1_2 tariff1_3
830 Hungary 2004 9.540313 6.287314 13.098201
831 Hungary 2005 NaN 6.281724 13.124401
832 Hungary 2006 8.460000 5.900000 11.600000
833 Hungary 2007 8.560000 5.300000 11.900000
834 eu 2005 8.550000 5.700000 11.400000
835 eu 2006 8.460000 5.900000 11.600000
836 eu 2007 8.560000 5.300000 11.900000
A:
You can try :
df.isnull().values.any()
For your case:
test.isnull().values.any()
| {
"pile_set_name": "StackExchange"
} |
Q:
Integrating android-misc-widget 'Panel' into Android project
I'm running into a ClassCastException when trying to integrate the Panel widget from android-misc-widgets.
I have copied the org.miscwidgets.widget and org.miscwidgets.interpolator packages into my project and am having trouble viewing the Panel show up in the graphical layout. The xml looks like this -
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:panel="org.miscwidgets.widget"..
<FrameLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="37dip"
android:paddingRight="37dip"
>
<org.miscwidgets.widget.Panel
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/topPanel"
android:paddingBottom="4dip"
panel:handle="@+id/panelHandle"
panel:content="@+id/panelContent"
panel:position="top"
panel:animationDuration="1000"
panel:linearFlying="true"
panel:openedHandle="@drawable/top_switcher_expanded_background"
panel:closedHandle="@drawable/top_switcher_collapsed_background"
>
<Button
android:id="@+id/panelHandle"
android:layout_width="fill_parent"
android:layout_height="33dip"
/>
<LinearLayout
android:id="@+id/panelContent"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<CheckBox
android:layout_width="fill_parent"
android:layout_height="60dip"
android:gravity="center"
android:text="top check box"
android:background="#688"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Bounce\nInterpolator"
android:textSize="16dip"
android:padding="4dip"
android:textColor="#eee"
android:textStyle="bold"
android:background="#323299"
/>
</LinearLayout>
</org.miscwidgets.widget.Panel>
</FrameLayout>...
The stack trace is:
java.lang.ClassCastException: com.android.layoutlib.bridge.MockView cannot be cast to android.view.ViewGroup
at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:77)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:702)
at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:79)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:702)
at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:79)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:702)
at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:79)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:702)
at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:79)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:702)
at android.view.LayoutInflater.inflate(LayoutInflater.java:479)
at android.view.LayoutInflater.inflate(LayoutInflater.java:367)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:315)
at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:314)
at com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:283)
at com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart.renderWithBridge(GraphicalEditorPart.java:1506)
at com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart.renderWithBridge(GraphicalEditorPart.java:1312)
at com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart.recomputeLayout(GraphicalEditorPart.java:1043)
at com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart.activated(GraphicalEditorPart.java:870)
at com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditor.pageChange(LayoutEditor.java:365)
at org.eclipse.ui.part.MultiPageEditorPart$2.widgetSelected(MultiPageEditorPart.java:290)
at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:234)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Display.sendEvent(Display.java:3783)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1375)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1398)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1383)
at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:1195)
at org.eclipse.swt.custom.CTabFolder.setSelection(CTabFolder.java:2743)
at org.eclipse.swt.custom.CTabFolder.onMouse(CTabFolder.java:1429)
at org.eclipse.swt.custom.CTabFolder$1.handleEvent(CTabFolder.java:257)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Display.sendEvent(Display.java:3783)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1375)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1398)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1383)
at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:1195)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3629)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3284)
at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2640)
at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2604)
at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2438)
at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:671)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:664)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:115)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:369)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:620)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:575)
at org.eclipse.equinox.launcher.Main.run(Main.java:1408)
Just trying to implement a top-down sliding drawer in android.
Can someone help me figure out what I'm doing wrong?
A:
The line in the opening LinearLayout tag -
xmlns:panel="org.miscwidgets.widget"
should be
xmlns:panel="http://schemas.android.com/apk/res/name.of.the.package.that.contains.java.file.that.uses.this.layout.file"
Hope this helps someone.
| {
"pile_set_name": "StackExchange"
} |
Q:
WPF: Exception if new EllipseGeometry() called on non UI thread
I have a WPF application that retrieves object 'movement' messages from a EasyNetQ/RabbitMQ message queue. Getting the message works fine as I can see in my logger.
private void btnSubscribeToMessageQ_Click(object sender, RoutedEventArgs e)
{
_logger.Debug("Listening for messages.");
_messageBus.Subscribe<RZMD.Messages.Movement>("test", HandleMovement);
}
Handling the message happens with:
private void HandleMovement(RZMD.Messages.Movement movementMessage)
{
_logger.Debug("Movement: {0}", movementMessage);
AddCirkelToCanvasWithDispatcher(movementMessage);
_movements.Add(movementMessage);
}
The UI is updated as follows by drawing a cirkel on the canvas:
private void AddCirkelToCanvasWithDispatcher(RZMD.Messages.Movement movementMessage)
{
var center = new Point(movementMessage.X, movementMessage.Y);
//var cirkel = new EllipseGeometry() { Center = center, RadiusX = 5, RadiusY = 5 }; <<
// above line causes exception re threads
// System.InvalidOperationException: 'The calling thread cannot access
// this object because a different thread owns it.'
Application.Current.Dispatcher.Invoke( ()=>
{
//if I put new EllipseGeometry() here all is fine
var cirkel = new EllipseGeometry() { Center = center, RadiusX = 5, RadiusY = 5 };
var path = new Path() { Stroke = Brushes.Black, Data = cirkel };
cnvFloor.Children.Add(path);
});
}
What I don't understand is why the call to var cirkel = new EllipsGeometry()... throws an exception when it is placed before the Dispatcher.
There is no problem creating the center Point object of the cirkel before the dispatcher. How is the Ellipse object different?
Is this the right (modern) approach? Or are there better tools such as 'async/await', 'TPL' or 'Parallel Linq'
Also I'm adding the movements to a collection of movements.
Should I investigate using an Observable collection and Notify events to draw the cirkel on the canvas instead?
A:
How is the EllipseGeometry object different?
It is a System.Windows.Threading.DispatcherObject, and hence has thread affinity, i.e. unless it is frozen, it can only be accessed in the thread where it was created.
Instead of creating the EllipseGeometry inside the Dispatcher action, you may freeze it to make it cross-thread accessible:
var cirkel = new EllipseGeometry() { Center = center, RadiusX = 5, RadiusY = 5 };
cirkel.Freeze();
Application.Current.Dispatcher.Invoke(() =>
{
var path = new Path() { Stroke = Brushes.Black, Data = cirkel };
cnvFloor.Children.Add(path);
});
| {
"pile_set_name": "StackExchange"
} |
Q:
What types of legal questions are on-topic here?
I know legal issues are in the faq as on-topic but I could not find an existing discussion of it.
Do legal questions such as the iPhone issue or non-paying customer question really have a place here? I think that providing amateur legal advice (even if it is good) is a disservice to the community and it would be better if we were to close these as off-topic. It seems these topics always end up with a lot of meta-discussion in the comments directly related to the dubious nature of internet legal advice, caveats etc.
A:
To tackle the relatively easy part of your question first, if you see a comment chain devolving into an extended discussion that does nothing to improve the post to which it is attached, flag the post for moderator review. Extended discussion, on any question, is discouraged and we will actively clean those up.
Regarding legal questions, it's really a two parter:
Are all legal questions ill-served by being asked here?
If not, is there a certain kind of legal question that's ill-served here?
To the first question, I don't think so. The Stack Exchange system can provide great answers, and there is a certain amount of community vetting in the form of voting, comments, and counter-answers, but it requires common sense.
If, for example, I told you that the best practice for implementing scrum in your job was to submit TPS reports daily that contain nothing but 14 pages of the letter 'K', I would hope you wouldn't do that even if my answer was the top-voted.
In the context of legal questions, common sense is always, always consult a lawyer. Asking a site devoted to non-lawyers who do not have an attorney-client relationship for definitive legal advice is obviously dangerous.
But that's not to say you can't ask about legal issues: it's akin to asking a colleague or a friend about their experiences in a similar situation.
Take the non-paying customer question, for instance: you might ask that question of a colleague, who might say something like "Obviously get a lawyer, but when that happened to me, this is what worked." That's the type of answer we want on Programmers.SE.
To the second question, the highly-specific legal question that can only be answered by a lawyer, like a question about being sued and asking for a legal interpretation for a defense, would be off-topic. We're not lawyers: we can't answer those.
I think there is always going to be a fine line between what constitutes regular, professional advice (on-topic) and what constitutes personal legal advice (off-topic). The standard should be, "would a reasonable person consider the question to be asking for personal legal advice?" If so, it's a candidate for closure.
One footnote regarding common sense: there are askers who appear to have the wrong set of expectations when asking legal questions, and both of the questions you listed appear to have this problem. A person who appears to think Programmers.SE substitutes a lawyer needs to be educated that he cannot use the answers given as a way to circumvent legal council.
To this end, it's similar to questions on Stack Overflow where someone asks how to do something insane, and the only correct answer is "Don't do that. Do X instead."
But the purpose of the Stack Exchange network is to build up questions and answers that can help others, not just the asker. So a misguided asker isn't reason enough to close a question.
A:
I don't think the wholesale discouraging of such questions would be productive. There are a number of topics, for instance free software licenses, where people here do have considerable knowledge to share.
Like it or not - licenses, patents, copyright and trademarks are in fact a part of many of our professional lives. Many of us have, if nothing worse, made mistakes that could help someone else. Such questions are surely on topic. A lot of people learned about organizations like the Software Freedom Law Center / Software Freedom Conservancy from reading questions here. Those are valuable resources.
I would hope that people are wise enough to consult with an attorney for legal advice. Asking if the new BSD license is compatible with version 3 of the GPL is not asking for legal advice, that's asking for information that anyone working in open source should know.
Not everything is so cut and dry, but I'd hate to alienate a possible answer like this:
I was in this situation and I live close to you. I ended up contacting an attorney and this is what we did, it cost me a fortune and I never did get the resolution I was after. I recommend talking to your lawyer, but my experience was dreadful, I wish now I had just let it go.
That's not sharing legal advice, that's sharing your first hand experience from being in a very similar situation.
We can't guarantee common sense in all users, but I think we should be able to assume that some exists for the sake of keeping the site rolling productively.
A:
My opinion: No. They don'y have a place here.
If any answer is, or should be, followed up with "... but you need to speak to a lawyer" then the answer is immediately irrelevant. A lawyer, who knows the situation/location (which potentially already makes them too localized as questions) could easily contradict everything in the answer.
All someone is saying is "I think [this], but I'm not a lawyer, so I don't actually know." which is not an answer. At best it's a hypothesis based on experience. At worst, it's bad advice that "sounds right". If there's anything that I've learned about the law, it's that things that sound right, or should be right, or seem to be common sense... are rarely any of those things in a room full of lawyers.
Now, does that mean that things like software licensing are off topic in my view? No. Those are not. The line is obviously blurry, but even then most responsible companies still end up needing to consult a lawyer when it comes to licensing.
IMO: relate them to questions about hardware on this site. Sure we're programmers, so lots of us know, and are expected to know, about hardware issues. Harware cabn also be very related to programming... but it's off topic. The only downside is that we don't have a legal.stackexchange.com where we do have a serverfault and superuser.
| {
"pile_set_name": "StackExchange"
} |
Q:
What should I do with one answer copy/paste in different questions?
While I was browsing the new answers to old questions tool (> 10k rep only), I noticed this user, Chancho, was posting the very same answer in every question related to Facebook FQL:
Paging in Facebook FQL
Paging with FQL
FQL: Limit and Offset variance return unexpected results
Facebook FQL stream limit?
FQL equivalent to Graph API pagination
What should I do in this case (and any future similar)? Burn my flag votes to flag every post with a comment that says it should be close as a duplicate? Check if the answer is relevant to each question even though I am not an expert about this topic? Ask moderators to look at this user?
A:
You don't really need to do anything. The system automatically raises a flag on every single post when a user posts exact duplicates of their answers across multiple questions. So we already have flags on them all.
If you have some pertinent information that moderators should know when handling these, feel free to flag one of them in the chain. Otherwise, consider it handled.
If you know anything about the subject, consider analyzing the questions to see if they're duplicates. That's always helpful, too.
| {
"pile_set_name": "StackExchange"
} |
Q:
C - struct returned from function not assigned to variable
I am getting a segfault when trying to print a string.
here is some context for the problem, I think that it is due to me somehow passing a struct incorrectly.
Load file reads *file_path and it returns it as a document struct, but in int main() sudo never has any data in it. I run the program in gdb and doc inside of load_file() has valid data inside of it, but sudo (also a document struct in int main() never gets the data. Is there a reason why?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
const char *sudoers_path = "thing";
char *read_string = "sandos";
int read_string_len = 6;
struct document{
char *string;
int length;
};
struct document sudoers;
struct document loadfile(char *file_path){
char char_temp[2] = "1";
struct document doc;
int temp=0;
FILE *file = fopen(file_path,"r");
doc.string = (char *)malloc(10*sizeof(*doc.string));
doc.length=10;
int len_doc_read = 0;
while(temp != EOF){
temp = fgetc(file);
if(temp == EOF){
break;
}
char_temp[0] = (char) temp;
if(doc.length - len_doc_read==0){
doc.string = (char *)realloc(doc.string, (doc.length+10)*sizeof(*doc.string));
for(int i = doc.length; i< len_doc_read-2; i++)
doc.string[i]=' ';
doc.string[doc.length-1] = '\0';
}
len_doc_read++;
strcat(doc.string, char_temp);
strcat(doc.string, "\0");
doc.length++;
}
//I am the cracker of C, destroyer of programming! --me
if(doc.string = NULL)
printf("memory failed");
return doc;
}
int main(){
struct document sudo = loadfile(sudoers_path);
struct document sand_find;
sand_find.string = "sandos";
sand_find.length = 7;
puts(sudo.string);
return 0;
}
Incase it matters I am compiling and running the program on a modern version of Arch Linux and the comand that I am using to compile it is
$ gcc main.c -o out
A:
In your program, by mistake instead of checking for NULL, you are assigning NULL to doc.string -
if(doc.string = NULL)
Change it to -
if(doc.string == NULL)
| {
"pile_set_name": "StackExchange"
} |
Q:
IBM Message Broker 6.1 configuration manager doesn't start
After I installed fix pack 6.1.0-WS-MB-WinIA32-FP0011 the configuration manager throws a verification error at start.
It complains the java level:
Verification failed. The required Java level ''1.5.0'' was not found.
The MQSI_JREPATH is set in mqsiprofile and in the PATH.
Thank you.
EDIT:
javaw.exe -Xshareclasses:destroy in the Message Broker Toolkit Directory /jdk/jre/bin
A:
The CVP process checks for a supported level of java before loading the copmonents. If you are sure that your java level is supported then you can disable this checking using the environment variable:
MQSI_DISABLE_CVP=1
Remember on windows you ened to set this in your mqsiprofile.cmd script and then start a new command window and restart the config manager.
On unix platforms you simply need to export the value in the shell before you start the config manager.
I would also advise doing a little problem determination, you can use the command "which java" on unix to determine the java installation being used. This should return a jre within the MQSI_FILEPATH folder
You can also do java -version to list the jre that the shell is picking up prior to launching the broker.
If after checking these you think that CVP is incorrectly identifying your java level as an unsupported version then I would suggest raising a PMR (but you can keep the env var set to diable CVP just to get you going.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Failed to remove labels from force directed graph
I try to add some labels in my force directed graph but for some reason that i dont know i cant "remove" them when i try to expand / shrink my nodeset.
my code for the labels is the following:
var labels = labelg.selectAll('text .textlabel').data(data.links);
labels.exit().remove();
labels.enter().append('text')
.attr('class','textlabel')
.attr("x", function(d) {return d.size ? (d.source.group_data.x + d.target.group_data.x) / 2 : (d.source.x + d.target.x)/2 ;})
.attr("y", function(d) { return (d.size ? (d.source.group_data.y + d.target.group_data.y) / 2 : (d.source.y + d.target.y))/2 ; })
.attr("text-anchor", "middle")
.text(function(d) {return d.reason;});
and in my "tick" function i positioned as follows
force.on("tick", function() {
//... node & link stuff ...
labels
.attr("x", function(d) { return (d.size ? (d.source.group_data.x + d.target.group_data.x) / 2 : (d.source.x + d.target.x)/2) ; })
.attr("y", function(d) { return (d.size ? (d.source.group_data.y + d.target.group_data.y) / 2 : (d.source.y + d.target.y))/2 ; });
});
And now, if i click on a node, the group expand and shows the labels between the nodes. But if i expand the second group and/or contract the first one, the labels are not be removed.
for a better understanding of my problem i make a fiddle http://jsfiddle.net/NVmf5/
Does someone may help me.
Any help would be appreciated.
A:
It looks like the problem here is that you're setting up the labels with data.links - so you always have all the labels for all your links in the SVG. The only reason you don't see them is that, if their group isn't expanded, the x and y attributes are set to NaN, so the labels are off-screen. Once you expand, the x and y values are set; contracting stop them from updating, but the data.links array doesn't change, so nothing is removed.
| {
"pile_set_name": "StackExchange"
} |
Q:
JavaScript/jQuery --> How to add thousand separator to 'Total value?'
How to add thousand separator to 'Total value?' so that it looks like 1 000, or 23 000 --> with blank space between thousands and hundreds, not coma but blank space...
Also when I write into INPUT 5-digit number the total value disappears...
Here is Fiddle
HTML:
<input type="text" id="nazwa" min="0" max="500000" >
<br><br>
Total value: <span id="total_expenses1"></span>
JavaScript/jQuery:
$('#nazwa').keyup(function(){ // run anytime the value changes
var raz = document.getElementById('nazwa');
var dwa = document.getElementById('total_expenses1');
var firstValue = Number($('#nazwa').val()); // get value of field
var secondValue = 1.15; // convert it to a float
raz.value = THOUSAND_SEPARATOR(this.value);
var mega = $('#total_expenses1').html(Math.ceil(firstValue * secondValue));
THOUSAND_SEPARATOR(mega.value);
// add them and output it
});
As for now thousand separator function works only for input value
A:
document.getElementById('total_expenses1').innerHTML = THOUSAND_SEPARATOR(String(Math.ceil(Number((this.value || '').replace(/\s/g, '')) * secondValue)));
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I subscribe to non-http data and how?
I am building a shopping cart and I would like to have my shopping cart icon display the number of items in the cart.
For the moment I do not have an API set up for the shopping cart yet as it is not a priority. So, for now, i just have a service that has an array of items where one gets added every time I click on "Add to Cart".
My problem is that when I add things to the shopping cart, the icon and count in the menu bar are not updated.
How can I achieve this without resorting to a http service?
Mock Cart Service
@Injectable()
export class ShoppingcartService {
//MOCK SERVICE
//fields
items: any[] = [];
//constructor
constructor() { }
//public methods
addToShoppingcart(item: any) {
this.items.push(item);
}
removeFromShoppingcart() {
}
changeQuantity() {
}
getAllItems() {
return this.items;
}
getItemsCount() {
return this.items.length;
}
Shopping Cart Icon TS
export class ShoppingcartIconComponent implements OnInit {
count: number;
constructor(private shoppingcartService: ShoppingcartService) {
this.count = this.shoppingcartService.getItemsCount();
}
ngOnInit() {
}
}
Shopping Cart Icon Html
<div class="btn btn-outline-info cart">
<i class="fa fa-shopping-cart">
</i>
<div class="count">
{{count}}
</div>
</div>
The component where the Add to Cart is..
HTML
<button class="btn btn-warning" (click)="addToCart()">
<i class="fa fa-plus-square"></i> {{shoppingCartTitle}}
</button>
TS
export class AlbumdetailsComponent implements OnInit {
shoppingcart;
album: any[];
id: number;
shoppingCartTitle: string = "Add to shoppingcart";
constructor(private musicService: MusicService,
private activatedRoute: ActivatedRoute,
private shoppingcartService: ShoppingcartService)
{
this.shoppingcart = this.shoppingcartService.getAllItems();
}
ngOnInit() {
//
}
}
addToCart() {
this.shoppingcartService.addToShoppingcart(this.album);
}
}
Quick screenshot of the situation, the Json shows that there is indeed an item in the cart, but the counter stays at 0.
The components are not parent or child of eachother, one is in the menu, the other is in the main view.
A:
Yes, you can. Just return an observable of those items, using Observable.of()
Here are couple of methods you can modify:
addToShoppingcart(item: any) {
this.items.push(item);
return Observable.of({message:'Item Added', addedItem: item})
//note that object can be anything you want to mock
}
removeFromShoppingcart() {
return Observable.of({message:'Item Deleted'});
}
changeQuantity() {
}
getAllItems() {
return Observable.of(this.items); //this automatically wraps the array in an observable
}
getItemsCount() {
return Observable.of(this.items.length); //this returns a number, but is wrapped in an observable
}
And the rest of the code you can treat each of them as observable as you would normally do, i.e subscribe to them. For example, in your constructor, you can do this:
constructor(private shoppingcartService: ShoppingcartService) {
this.shoppingcartService.getItemsCount()
.subscribe(count=>this.count = count);
}
Note: to use Observable.of, remember to import it:
import "rxjs/add/observable/of";
Edit:
I am keeping the above service codes for reference because they answers the question title.
If you want to have your items[] being updated asynchronously every time you call addToShoppingCart(), you will need to create a Subject or BehaviourSubject to keep track of it. In the example below we will use BehaviourSubject because it allows intialization of a default value.
In your service, make a property called itemBSubject with type of BehaviourSubject. Do not confuse this with items[]. This subject is to keep track of your items[].
items: any[] = [];
itemBSubject: BehaviourSubject<any[]>
In your constructor, sync up itemBSubject with items:
constructor() {
this.itemBSubject = new BehaviorSubject<any[]>(items);
}
Now, in every method that modifies the items[], you will need to update the itemBSubject as well, by using the .next():
addToShoppingcart(item: any) {
this.items.push(item);
this.itemBSubject.next(this.items); // this will update the behavior subject
return this.itemBSubject.asObservables();
}
//same goes to delete. call .next() after this items are sliced.
And now here is the magic of all. For your getItems() and also getItemsCount(), return the BehaviourSubject (as an observable).
getItems(){
return this.itemBSubject.asObservable()
}
getItemsCount(){
return this.itemBSubject.asObservable()
.map(items=>items.length)
}
And now, you will realize your count will automatically being incremented, even though you are adding the item in another component.
| {
"pile_set_name": "StackExchange"
} |
Q:
Parsing a date returned as JSON in .net?
Hi I was receiving responses from an API as JSON and loading it into my application. Everything imports fine except for a date that that a specific item was published on. The date is returned as a number which I never worked with before:
'date_created' : 1279643054
I tried using a normal DateTime.Parse() with no luck. Does anyone know how to parse this, or if anything what the name of this format is so I can do further research? Thanks.
A:
It's a UNIX Timestamp. Use this code to convert the timestamp to a DateTime object:
static DateTime ConvertFromUnixTimestamp(long timestamp)
{
return new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(timestamp);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Useful software resources for reviewing papers
I have a paper for review and I would like to include comments (on clarifications/suggestions/errors) over specific paragraphs or statements.
What are some ideal software resources that could help reviewers? I would prefer them to be Linux-based.
A:
If you have access to the LaTeX source, there are a number of packages that will help you. Some include todonotes and fixme.
However it's more likely that you have a PDF only. In that case, you need a PDF annotating package. A free cross-platform solution is Xournal, which runs on windows/linux (and maybe Mac).
If you're on a iOS device, then Goodreader is a nice app that does annotations.
There's always Adobe Acrobat as well. Both of these solutions are not free though.
Update: (by @atiretoo)
One issue to be careful with providing comments on a pdf or other document is maintaining anonymity. Adobe Acrobat (and probably other software), automatically flags your annotations with information about you unless you are careful to remove that from the document before commenting.
A:
The approach taken by many reviewers (myself included) is to simply reference the page and line number, or to insert a copy of the statement in question in the referee report, e.g.:
On page 7, line 6, the word "mispell" should be "misspell".
This is probably the easiest approach if the number of such comments is not too large, since it doesn't require any extra software and doesn't require the authors to search through the PDF for your annotations.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to add checkboxes to tree nodes in extjs4
i am working in extjs4. i have view with tree panel as-
Ext.define('Balaee.view.qb.qbquestion.tree1', {
extend: 'Ext.tree.Panel',
title: 'Simple Tree',
width: 200,
height: 150,
alias : 'widget.tree1',
//store: 'qb.qbquestioncomplexityStore',
rootVisible: true,
renderTo: Ext.getBody()
});
In controller i have created static store. And binded it to this view. Code is as-
var store = Ext.create('Ext.data.TreeStore', {
root: {
expanded: true,
children: [
{ text: "detention", leaf: true },
{ text: "homework", expanded: true, children: [
{ text: "book report", leaf: true },
{ text: "algebra", leaf: true}
] },
{ text: "buy lottery tickets", leaf: true }
]
}
});
var bchart=Ext.create('Balaee.view.qb.qbquestion.tree1',{
store:store
});
var comp=Ext.getCmp('QuestionView');
comp.removeAll();
comp.add(bchart);
its working correctly. its displaying tree panel view correctly. But how to add checkboxes to this tree nodes?
A:
You need to add checked property to your tree node data either true or false. Existence of this property will tell ExtJs to add checkbox for a node.
example definition of children nodes for your tree:
children: [
{ text: "detention", leaf: true, checked: true },
{ text: "homework", expanded: true, children: [
{ text: "book report", leaf: true },
{ text: "algebra", leaf: true, checked: false}
] },
{ text: "buy lottery tickets", leaf: true }
]
| {
"pile_set_name": "StackExchange"
} |
Q:
Is undefined behavior worth it?
Many bad things happened and continue to happen (or not, who knows, anything can happen) due to undefined behavior. I understand that this was introduced to leave some wiggle-room for compilers to optimize, and maybe also to make C++ easier to port to different platforms and architectures. However the problems caused by undefined behavior seem to be too large to be justified by these arguments. What are other arguments for undefined behavior? If there are none, why does undefined behavior still exist?
Edit To add some motivation for my question: Due to several bad experiences with less C++-crafty co-workers I have gotten used to making my code as safe as possible. Assert every argument, rigorous const-correctness and stuff like that. I try to leave as little room has possible to use my code the wrong way, because experience shows that, if there are loopholes, people will use them, and then they will call me about my code being bad. I consider making my code as safe as possible a good practice. This is why I do not understand why undefined behavior exists. Can someone please give me an example of undefined behavior that cannot be detected at runtime or compile time without considerable overhead?
A:
My take on undefined behavior is this:
The standard defines how the language is to be used, and how the implementation is supposed to react when used in the correct manner. However, it would be a lot of work to cover every possible use of every feature, so the standard just leaves it at that.
However, in a compiler implementation, you can't just "leave it at that," the code has to be turned into machine instructions, and you can't just leave blank spots. In many cases, the compiler can throw an error, but that's not always feasible: There are some instances where it would take extra work to check whether the programmer is doing the wrong thing (for instance: calling a destructor twice -- to detect this, the compiler would have to count how many times certain functions have been called, or add extra state, or something). So if the standard doesn't define it, and the compiler just lets it happen, witty things can sometimes happen, maybe, if you're unlucky.
A:
I think the heart of the concern comes from the C/C++ philosophy of speed above all.
These languages were created at a time when raw power was sparse and you needed to get all the optimizations you could just to have something usable.
Specifying how to deal with UB would mean detecting it in the first place and then of course specifying the handling proper. However detecting it is against the speed first philosophy of the languages!
Today, do we still need fast programs ? Yes, for those of us working either with very limited resources (embedded systems) or with very harsh constraints (on response time or transactions per second), we do need to squeeze out as much as we can.
I know the motto throw more hardware at the problem. We have an application where I work:
expected time for an answer ? Less than 100ms, with DB calls in the midst (say thanks to memcached).
number of transactions per second ? 1200 in average, peaks at 1500/1700.
It runs on about 40 monsters: 8 dual core opteron (2800MHz) with 32GB of RAM. It gets difficult to be "faster" with more hardware at this point, so we need optimized code, and a language that allows it (we did restrain to throw assembly code in there).
I must say that I don't care much for UB anyway. If you get to the point that your program invokes UB then it needs fixing whatever the behavior that actually occurred. Of course it would be easier to fix them if it was reported straight away: that's what debug builds are for.
So perhaps that instead of focusing on UB we should learn to use the language:
don't use unchecked calls
(for experts) don't use unchecked calls
(for gurus) are you sure you really need an unchecked call here ?
And everything is suddenly better :)
A:
The problems are not caused by undefined behaviour, they are caused by writing the code that leads to it. The answer is simple - don't write that kind of code - not doing so is not exactly rocket science.
As for:
an example of undefined behavior that
cannot be detected at runtime or
compile time without considerable
overhead
A real world issue:
int * p = new int;
// call loads of stuff which may create an alias to p called q
delete p;
// call more stuff, somewhere in which you do:
delete q;
Detecting this at compile time is imposisible. at run-time it is merely extremely difficult and would require the memory allocation system to do far more book-keeping (i.e. be slower and take up more memory) than is the case ifwe simply say the second delete is undefined. If you don't like this, perhaps C++ is not the language for you - why not switch to java?
| {
"pile_set_name": "StackExchange"
} |
Q:
ActivityIndicator not showing
I'm implementing what seems to be standard code for iOS activity indicator, but it's not showing. This is what I do, following advice from around here:
In viewDidLoad:
indicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
indicator.frame = CGRectMake(0, 0, 80.0, 80.0);
indicator.hidden = NO;
indicator.center = self.view.center;
[self.view insertSubview:indicator atIndex:100]; // to be on the safe side
[indicator bringSubviewToFront:self.view];
[UIApplication sharedApplication].networkActivityIndicatorVisible = TRUE;
Then in viewWillAppear, just before calling my long process method:
[NSThread detachNewThreadSelector:@selector(threadStartAnimating:) toTarget:self withObject:nil];
My threadStartsAnimating:
-(void)threadStartAnimating:(id)data
{
[indicator startAnimating];
}
Then I have a Parse.com method that does some work in the background:
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if(!error) {
// do some work
[indicator stopAnimating];
}
}
For all I can see, this should work. But it doesn't. What am I missing?
A:
Whenever you want to manipulate your view (i.e. addSubview, etc) it is best to do so in viewWillAppear. viewDidLoad is too early to manipulate views since other methods will still alter it (i.e. setFrame).
So moving your current code from viewDidLoad to viewWillAppear should do the trick!
| {
"pile_set_name": "StackExchange"
} |
Q:
Gensim built-in model.load function and Python Pickle.load file
I was trying to use Gensim to import GoogelNews-pretrained model on some English words (sampled 15 ones here only stored in a txt file with each per line, and there are no more context as corpus). Then I could use "model.most_similar()" to get their similar words/phrases for them. But actually the file loaded from Python-Pickle method couldn't be used for gensim-built-in model.load() and model.most_similar() function directly.
how should I do to cluster the 15 English words (and more in the future), since I couldn't train and save and load a model from the beginning?
import gensim
from gensim.models import Word2Vec
from gensim.models.keyedvectors import KeyedVectors
GOOGLE_WORD2VEC_MODEL = '../GoogleNews-vectors-negative300.bin'
GOOGLE_ENGLISH_WORD_PATH = '../testwords.txt'
GOOGLE_WORD_FEATURE = '../word.google.vector'
model = gensim.models.KeyedVectors.load_word2vec_format(GOOGLE_WORD2VEC_MODEL, binary=True)
word_vectors = {}
#load 15 words as a test to word_vectors
with open(GOOGLE_ENGLISH_WORD_PATH) as f:
lines = f.readlines()
for line in lines:
line = line.strip('\n')
if line:
word = line
print(line)
word_vectors[word]=None
try:
import cPickle
except :
import _pickle as cPickle
def save_model(clf,modelpath):
with open(modelpath, 'wb') as f:
cPickle.dump(clf, f)
def load_model(modelpath):
try:
with open(modelpath, 'rb') as f:
rf = cPickle.load(f)
return rf
except Exception as e:
return None
for word in word_vectors:
try:
v= model[word]
word_vectors[word] = v
except:
pass
save_model(word_vectors,GOOGLE_WORD_FEATURE)
words_set = load_model(GOOGLE_WORD_FEATURE)
words_set.most_similar("knit", topn=3)
---------------error message--------
AttributeError Traceback (most recent call last)
<ipython-input-8-86c15e366696> in <module>
----> 1 words_set.most_similar("knit", topn=3)
AttributeError: 'dict' object has no attribute 'most_similar'
---------------error message--------
A:
You've defined word_vectors as a Python dict:
word_vectors = {}
Then your save_model() function just saves that raw dict, and your load_model() loads that same raw dict.
Such dictionary objects don't implement the most_similar() method, which is specific to the KeyedVectors interface (& related classes) of gensim.
So, you'll have to leave the data inside a KeyedVectors-like object to be able to use most_similar().
Fortunately, you have a few options.
If you happened to need the just the first 15 words from inside the GoogleNews file (or first 15,000, etc), you could use the optional limit parameter to only read that many vectors:
from gensim.models import KeyedVectors
model = KeyedVectors.load_word2vec_format(GOOGLE_WORD2VEC_MODEL, limit=15, binary=True)
Alternatively, if you really need to select an arbitrary subset of the words, and assemble them into a new KeyedVectors instance, you could re-use one of the classes inside gensim instead of a plain dict, then add your vectors in a slightly different way:
# instead of a {} dict
word_vectors = KeyedVectors(model.vector_size) # re-use size from loaded model
...then later inside your loop of each word you want to add...
# instead of `word_vectors[word] = _SOMETHING_`
word_vectors.add(word, model[word])
Then you'll have a word_vectors that is an actual KeyedVectors object. While you could save that via plain Python-pickle, at that point you might as well use the KeyedVectors built-in save() and load() - they may be more efficient on large vector sets (by saving large sets of raw vectors as a separate file which should be kept alongside the main file). For example:
word_vectors.save(GOOGLE_WORD_FEATURE)
...
words_set = KeyedVectors.load(GOOGLE_WORD_FEATURE)
words_set.most_similar("knit", topn=3) # should work
| {
"pile_set_name": "StackExchange"
} |
Q:
ASP Classic functionality with ASP.NET MVC
I have a current site written in classic ASP VB and I would like to upgrade it and I have been working heavily in ASP.NET MVC 3.
I would like to find a solution to get a system that works with both CLASSIC and ASP.NET.
Is there a way to develop a new system in MVC and navigate in and out of CLASSIC and back into MVC workflow?
If so, whats the best way to achieve this?
A:
Your biggest issue is state. In ASP, chances are you threw a lot of crap into the Session object. ASP.NET (MVC or web forms) and ASP do not share the same session (state), so you end up having to store state somewhere to have it continue to work.
As long as you can get a place to store the state that both ASP and ASP.NET MVC can both consult, you can start migrating the pages piecemeal. If you cannot figure that out, you will have to scrap the ASP after you completely rebuild the site in ASP.NET MVC.
NOTE: I have been leading migrations (ASP >> ASP.NET (both flavors) and VB >> VB.NET). Unless you absolutely have to use a mixed mode, you are better to rebuild and then migrate the site over rather than rely on a mixed site. The worst thing that can happen is somebody stored something stupid in session or application, that you did not envision, and you are now in a place where you are not keeping something important. And you probably find it after a user complains about some transaction they did that did not migrate and now you no longer have any information about it.
NOTE 2: Sometimes clients want to migrate piecemeal and refuse to listen to you stating it is a bad idea. Your option, at this time, is move on to another client (or job) or do it. If "do it" is the option, make sure you have your butt covered, as this is a minefield.
| {
"pile_set_name": "StackExchange"
} |
Q:
Find polynomial $f(x)$ based on divisibility properties of $f(x)+1$ and $f(x) - 1$
$f(x)$ is a fifth degree polynomial. It is given that $f(x)+1$ is divisible by $(x-1)^3$ and $f(x)-1$ is divisible by $(x+1)^3$. Find $f(x)$.
A:
Hint: Use the fact that $f^{\prime}(x)$ is divisible by $(x-1)^2$ and $(x+1)^2$.
A:
We can clearly see that: $f(1)+1=0$ and $f(-1)-1=0$
We can write $f(x)-1=p(x)(x+1)^3$ and $f(x)+1=q(x)(x-1)^3$
By differentiation and double differentiation, you can see that
$f'(1)=0$ and $f''(1)=0$
AND
$f'(-1)=0$ and $f''(-1)=0$
You got six conditions and six unknowns!
[assume $f(x) = x^6+a_1x^5+a_2x^4+a_3x^3+a_4x^2+a_5x+a_6$]
A:
If $(x-1)^3$ divides $f(x)+1$, then $(x-1)^2$ divides $f'(x)$.
If $(x+1)^3$ divides $f(x)-1$, then $(x+1)^2$ divides $f'(x)$.
As deg$\,f=5$, then deg$\,f'=4$, and hence $f'(x)=a(x-1)^2(x+1)^2=a(x^4-2x^2+1)$,
for some $a\in\mathbb R$.
Thus
$$
f(x)=\frac{a}{5}x^5-\frac{2a}{3}x^3+ax+b,
$$
for some $b\in\mathbb R$.
Now, as $(x-1)^3$ divides $g(x)=f(x)+1$, in particular $f(1)+1=g(1)=0$. Thus
$$
-1=f(1)=\frac{a}{5}-\frac{2a}{3}+a+b. \tag{1}
$$
Similarly,
as $(x+1)^3$ divides $h(x)=f(x)-1$, in particular $f(-1)-1=g(-1)=0$. Thus
$$
1=f(-1)=-\frac{a}{5}+\frac{2a}{3}-a+b. \tag{2}
$$
Adding $(1)$ and $(2)$ we obtain that $b=0$, and thus $a=-15/8$.
Hence
$$
f(x)=-\frac{3}{8}x^5+\frac{5}{4}x^3-\frac{15}{8}x.
$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Number of Independent variables in su(2) (Lie algebra) is 3, and in SU(2) (Lie group) it is 4...?
The lie algebra su(2) is the linear combination of the pauli matrices. For instance : $x \sigma_x+y\sigma_y+z\sigma_z$. There are three degrees of freedom, namely x,y,z.
Let us compare it to the SU(2) group.
The definition of the SU(2) group is :
$$
SU(2):=\left\{ \pmatrix{\alpha & - \overline{\beta} \\ \beta &\overline{\alpha} } : \alpha,\beta \in \mathbb{C}, |\alpha|^2+|\beta|^2=1 \right\}
$$
where $\alpha=a+ib$ and $\beta = c+id$. So the SU(2) has 4 degrees of freedom.
The algebra is connected to the group by the map $\exp^{ i su(2)} = SU(2)$
How can a lie algebra with 3 independent variables generate a group with 4 independent variables?
A:
The condition $|\alpha|^2 +|\beta|^2=1$ reduce the degree of freedom by 1.
| {
"pile_set_name": "StackExchange"
} |
Q:
Programa tendo saída inesperada
Estou tendo um problema de saída inesperada e não consigo achar o erro em meu código, a saída em questão é os erros de todas as frases as quais não sejam "Cachorro anda .", uma observação notória é o fato de se o usuário entrar com "Cachorro" enter "anda" enter "." enter, o programa só vai acusar o NOT OK ao fim do ".", porém, quando colocamos quaisquer outras frases que não sejam as mesmas citadas, no primeiro enter já obtenho o resultado "Not ok". Ex: "Peixe" enter, (Not ok impresso), "Nada", enter, (not ok impresso), ".", enter, (not ok novamente).
#include <iostream>
#include <stdlib.h>
#include <vector>
using namespace std;
vector<string> nome;
vector<string> verbo;
vector<string> conjuncao;
void inicializar(){ // Função pra definir valores dos vetores
nome.push_back("cachorro");
nome.push_back("passaro");
nome.push_back("peixe");
verbo.push_back("anda");
verbo.push_back("nada");
verbo.push_back("voa");
conjuncao.push_back("e");
conjuncao.push_back("ou");
conjuncao.push_back("mas");
}
bool isName(string v){
for(int x = 0; x<nome.size(); x++){ //Verifica se a primeira palavra é um nome
if(nome[x] == v) return true;
return false;
}
}
bool isVerb(string v){
for(int x = 0; x<verbo.size(); x++){
if(verbo[x] == v) return true; //Verifica se a segunda palavra é um verbo
return false;
}
}
bool isConjuncao(string v){
for(int x = 0; x<conjuncao.size(); x++){
if(conjuncao[x]==v) return true; //Verifica se a segunda palavra é uma conj
return false;
}
}
bool sentenca(){ //Insere e faz todas as verificações
string v;
cin >> v;
if(!isName(v)) return false;
string v2;
cin >> v2;
if(!isVerb(v2)) return false;
string v3;
cin >> v3;
if(v3 == ".") return true; //Se for ".", termina, senão, continua.
if(!isConjuncao(v3)) return false;
return sentenca();
}
int main()
{
inicializar();
while(cin){ //Cria um loop para repetir o processo.
bool b = sentenca();
if(b) cout << "OK" << endl; //Caso true, "ok"
else cout << "Not ok" << endl;
}
return 0;
}
A:
1) Todos os três métodos de verificação estão errados.
Você deveria colocar o "return false" fora do loop for e não dentro. Porque apenas se ele não encontrar lá dentro retornará falso.
2) Sentença não deveria ser recursivo...
Por qual motivo sentença é um método que chama a si mesmo? Você está fazendo o loop com o while já na função main. É melhor retornar falso se não encontrar um retorno verdadeiro.
| {
"pile_set_name": "StackExchange"
} |
Q:
Celery rate_limit affecting multiple tasks
I have a setup with rabbitmq and celery, with workers running on 4 machines with 4 instances each. I have two task functions defined, which basically call the same backend function, but one of them named process_transaction with no rate_limit defined, and another called slow_process_transaction, with rate_limit="6/m". The tasks go to different queues on rabbitmq, slow and normal.
The strange thing is the rate_limit being enforced for both tasks. If I try to change the rate_limit using celery.control.rate_limit, doing it with the process_transaction doesn't change the effective rate, and using the slow_process_transaction name changes the effective rate for both.
Any ideas on what is wrong?
A:
By reading the bucket source code I figured out celery implements rate limiting by sleeping the time delta after finishing a task, so if you mix tasks with different rate limits in the same workers, they affect each other.
Separating the workers solved my problem, but it's not the optimal solution.
You can separate the workers by using node names and named parameters on your celeryd call. For instance, you have nodes 'fast' and 'slow', and you want them to consume separate queues with concurrency 5 and 1 respectively:
celeryd <other opts> -Q:fast fast_queue -c:fast 5 -Q:slow slow_queue -c:slow 1
| {
"pile_set_name": "StackExchange"
} |
Q:
Palindromic numbers whose squares are palindromic too
In any base $b>2$, there are infinite palindromic numbers whose squares are palindromic too: for any $n\geq 0$, if $a_n:=1\underbrace{0\dots 0}_{\text{n}}1_b$ then
$a_n^2=1\underbrace{0\dots 0}_{\text{n}}2\underbrace{0\dots 0}_{\text{n}}1_b$.
Is this property true also in base $2$?
A:
There are only finitely many base-$2$ palindromes whose square is also a base-$2$ palindrome. Namely, the trivial $0$ (if one counts that as a palindrome), $1$, and the not-quite-trivial $3 = 11_2$.
To see that, let's first look at numbers with few bits set. There's only one number with no bits set, $0$. Whether that should count as a palindrome is left to the reader. There's only one base-$2$ palindrome with exactly one bit set, namely $1$. For base-$2$ palindromes with exactly two bits set, we easily see that $3$ is the only one whose square is also a base-$2$ palindrome. For if $x = 2^k + 1$ with $k \geqslant 2$, then $x^2 = 2^{2k} + 2^{k+1} + 1$, and there are only $k-2$ zeros between the first two ones, and $k$ zeros between the last two ones, hence $x^2$ is not a base-$2$ palindrome. Base-$2$ palindromes with exactly three bits set are of the form $x = 2^{2k} + 2^k + 1$, and then $x^2 = 2^{4k} + 2^{3k+1} + 2^{2k+1} + 2^{2k} + 2^{k+1} + 1$. For $k \geqslant 2$, we have $4k > 3k+1 > 2k+1 > 2k > k+1 > 0$, and we again have only $k-2$ zeros between the first two ones, and $k$ zeros between the last two ones in the binary representation of $x^2$. For $k = 1$ we have $x = 7$ and $x^2 = 49 = 110001_2$ which also isn't a base-$2$ palindrome.
So let's finally look at base-$2$ palindromes with at least four bits set. These are of the form $x = 2^k + 2^{k-a} + \dotsc + 2^a + 1$ with $1 \leqslant a < \frac{k}{2}$. Writing $x = 1 + 2^a\cdot u$ with $u$ odd, we see that $x^2 = 1 + 2^{a+1} u + 2^{2a}u^2$, so there are at least $a$ zeros between the last two ones in the binary representation of $x^2$ (exactly $a$ if $a \geqslant 2$, at least $2$ if $a = 1$). At the front, writing $x = 2^k + v$, with $2^{k-a} < v < 2^{k+1-a}$, we see that $x^2 = 2^{2k} + 2^{k+1}v + v^2$, and
$$2^{2k+1-a} < 2^{k+1}v + v^2 < 2^{2k+2-a} + 2^{2k+2-2a}, \tag{$\ast$}$$
so there are at most $a-2$ zeros between the first two ones in the binary representation of $x^2$ and hence $x^2$ is not a base-$2$ palindrome, unless we have carry at the front, i.e. $2^{k+1}v + v^2 \geqslant 2^{2k}$.
From $(\ast)$ it is readily seen that there is no carry at the front if $a \geqslant 3$, so we only need to look at the cases $a = 2$ and $a = 1$.
For $a = 2$, we have $x \equiv 5 \pmod{8}$ and therefore $x^2 \equiv 9 \pmod{16}$, so $x^2$ can only be a base-$2$ palindrome if $2^{2k+1} + 2^{2k-2} \leqslant x^2 < 2^{2k+1} + 2^{2k-1}$. But we have $x < 2^k + 2^{k-1}$ and hence
$$x^2 < (2^k + 2^{k-1})^2 = 2^{2k+1} + 2^{2k-2},$$
thus $x^2$ is never a base-$2$ palindrome when $a = 2$.
Last, we look at the case $a = 1$. If $x \equiv 7 \pmod{8}$, then $x^2 \equiv 1 \pmod{16}$, so there are at least three zeros between the last two ones in the binary representation of $x^2$, but then, since $x$ is a base-$2$ palindrome we have $2^k + 2^{k-1} + 2^{k-2} = 2^{k+1} - 2^{k-2} < x < 2^{k+1}$ and
$$(2^{k+1} - 2^{k-2})^2 = 2^{2k+2} - 2^{2k} + 2^{2k-4} = 2^{2k+1} + 2^{2k} + 2^{2k-4} < x^2 < 2^{2k+2},$$
so the binary representation of $x^2$ starts with two consecutive ones, and therefore $x^2$ is not a base-$2$ palindrome.
Thus we must have $x \equiv 3 \pmod{8}$ and consequently $x^2 \equiv 9 \pmod{16}$, so there are exactly two zeros between the last two ones in the binary representation of $x^2$, whence $x^2$ can only be a base-$2$ palindrome if $2^{2k+1} + 2^{2k-2} < x^2 < 2^{2k+1} + 2^{2k-1}$. This implies $x < 2^{k} + 2^{k-1} + 2^{k-3}$, so the binary representation of $x$ must be $1100\dotsc0011$ (leaving out the verification that $x = 51 = 110011_2$ and $x = 99 = 1100011_2$ don't have base-$2$ palindromic squares). But then $x \equiv 3 \pmod{16}$ and $x^2 \equiv 9 \pmod{32}$, so the binary expansion of $x^2$ ends with $01001$ and we must have $2^{2k+1} + 2^{2k-2} < x^2 < 2^{2k+1} + 2^{2k-2} + 2^{2k-3}$, which in turn implies $x < 2^k + 2^{k-1} + 2^{k-4}$, and thus, since $x$ shall be a base-$2$ palindrome, $x \equiv 3 \pmod{32}$. Now it is easily verified that for $x = 2^k + 2^{k-1} + 2 + 1$, the square is never a base-$2$ palindrome, and thus the last family of candidates is of the form
$$x = 2^k + 2^{k-1} + 2^{k-b} + \dotsc + 2^b + 2 + 1$$
with $b \geqslant 5$ (or in case $k = 2b$ of the form $2^{2b} + 2^{2b-1} + 2^b + 2 + 1$; the form is slightly different, the argument is the same). Writing $x = 1 + 2 + 2^b\cdot u$ with odd $u$, we find that
$$x^2 = 1 + 2^3 + 2^{b+1} + \dotsc,$$
so there are exactly $b-3$ zeros between the third-to-last and the penultimate one in the binary representation of $x^2$. On the other hand, from $2^k + 2^{k-1} + 2^{k-b} < x < 2^k + 2^{k-1} + 2^{k+1-b}$ we obtain
$$2^{2k+1} + 2^{2k-2} + 2^{2k+1-b} + 2^{2k-b} + 2^{2k-2b} < x^2 < 2^{2k+1} + 2^{2k-2} + 2^{2k+2-b} + 2^{2k+1-b} + 2^{2k+2-2b},$$
so there are at most $(2k-2) - (2k+1-b) - 1 = b-4$ zeros between the second and third one in the binary representation of $x^2$, which shows that $x^2$ isn't a base-$2$ palindrome for such $x$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Arms Workout per Week
I doing gym for almost 5 months.I got nice shoulders and chest.But when it come to arms i feel something left out.I was thinking of doing arms 2-3 times a week.Is it good to do that and if i do that how i'm gonna cover my other body parts.
I have chest of 38-40 inches and i got arms of 12 inches only. I like to go for 14-16 because my height is 5'11 and its feel like an average arms.
Please help me
Thanks in Advance
A:
Large muscle groups develop in a more obvious way than the smaller ones. That said, you clearly understand how to build muscle through effective diet and exercise.
Arms can be trained through a number of means, there are 3 major muscle groups. I'll list the best exercises that have their major focus on that muscle group but are the best compound version:
Biceps
Barbell Bicep Curl: This is the simplest and when done standing engages your core and posterior chain to keep you upright. Play around with grip, some people struggle with standard grip. Overhand also works forearms as well.
Dumbbell Bicep Curl: Do this standing for the reasons above. Also start the exercise with your weakest arm to ensure that you don't over-work one side.
Cable Curl: Same as above but you get linear resistance throughout the movement.
Other: Chin-ups, any rowing movement, any variation on above (preacher, seated)
Triceps
Dips: And their best friend, weighted dips. Also builds chest. Seriously, everyone should be doing 3x10 dips.
Close Grip Bench Press: Bench. Press. Don't let elbows flare out.
Cable Tricep Pushdown: As with biceps, gives resistance across whole ROM.
Other: Skull crushers, Diamond push ups, Behind the neck plate raises
Forearms
Deadlifts: Just lots of really heavy deadlifts with a normal, double overhand grip.
Farmers Walks: Pick up 2 32-50KG kettlebells or dumbbells and go for a walk.
Hold something heavy.
Hang from something.
A:
“I was thinking of doing arms 2-3 times a week.Is it good to do that
and if i do that how i'm gonna cover my other body parts.”
If your goal is a balanced, aesthetic physique, then, “more is not necessarily better”. Hypertrophy is a very individual thing. There’s no specific set of exercises that will guarantee you growth for a specific muscle group. While exercise selection does contribute to muscle growth, I think it’s much more important to examine your approach to training. Ask yourself, “Is my training approach optimum for making muscular gains?”.
You need to understand that you build muscular size when you optimize your nutrition, sleep, and recovery. If one facet of your training is “off”, chances are, you will not make gains. Closely examining each of these should provide insight into any potential areas that are lacking.
If you feel that you’re training optimally, there is one change that may be effective for you. If you feel that a particular body part is lagging, you should take a look at prioritizing your routine. An excerpt from the National Strength and Conditioning Association indicates that
“The order of exercises within a workout significantly affects acute
lifting performance and subsequent changes in strength during
resistance training. The primary training goals should dictate the
exercise order. Exercises performed early in the workout are completed
with less fatigue, yielding greater rates of force development, higher
repetition number, and greater amount of weights lifted.”
If you feel that your arms are lacking, you should consider training biceps and triceps earlier in your routine. You should also consider using “pre-exhaustion” as a method to stimulate growth.
Lastly, achieving muscle growth, for those training drug-free, should be considered as a long term goal. If you consistently optimize your training, the cumulative effect should be obvious in later years.
| {
"pile_set_name": "StackExchange"
} |
Q:
Difference between if(isset(a,b)) and if(isset(a) && isset(b))
As mentioned in the title, What is the difference between using
if(isset($a, $b)){
//execute...
}
And
if(isset($a) && isset($b)){
//execute...
}
And which one is better in your opinion?
A:
There is a difference if you plan on using empty() later on, instead of isset().
The isset() does allow for comma separated values, while empty() does not.
Therefore, you will need to use separate conditions on empty(), should this be the case at a future date.
But to answer this, there is no difference; both are valid and work the same way.
And which one is better in your opinion?
That's purely by preference.
However, if one or another should fail, then check for both in separate conditions. Both need to be set in order for isset() to work when using this method if(isset($a, $b)).
| {
"pile_set_name": "StackExchange"
} |
Q:
Device detection in grails version 2
We're building a multi platform application in grails 2. I'm aware we can use JQuery mobile to build the views, but what's the best plugin for device detection in grails 2.
The Spring plugin is for Grails version : 1.3.6 , is there some work around for this?
Thank you in advance.
A:
Use http://grails.org/plugin/browser-detection - it's actively maintained (updated last month)
| {
"pile_set_name": "StackExchange"
} |
Q:
Custom function to map through nested lists sorting by time-stamp
In the following example, please assume that we are using time-to-seconds to convert each times-stamp into a decimal representation. I have already converted the time-stamps to seconds in this example. Each node has at least one time-stamp, but there might be more than one time-stamp per node. The current node with corresponding time-stamp is represented by a cons cell with the cdr being t. The time-stamps will always be unique. The nodes are vectors with multiple elements.
(defun goto-node (time-stamp n)
"Go to the desired node commencing from an existing TIME-STAMP.
If N is positive, then go forwards in time by that number of N time-stamps.
If N is negative, then backwards in time by that number of N time-stamps.
If node does not exist, return nil; otherwise, return node and corresponding time-stamp."
INSERT MAGIC HERE)
BEGIN WITH:
'(([node1] ((5.6) (3.7) (11.7) (8.2)))
([node2] ((4.4) (9.9) (6.1 . t)))
([node3] ((7.5) (2.3) (1.5)))
([node4] ((10.3))))
EXAMAPLES:
(goto-node 6.1 -1) => '([node1] (5.6))
(goto-node 6.1 -4) => '([node3] (2.3))
(goto-node 6.1 1) => '([node3] (7.5))
(goto-node 6.1 4) => '([node4] (10.3))
A:
Generate a complete (rassoc-) map assigning time-stamps to nodes at first. Afterwards sort and then locate time-stamp in the sorted list. From there you can go forward and backward.
(defvar goto-node-timestamp-tolerance 1e-5
"Tolerance for testing equality of timestamps.")
(defun goto-node (list time-stamp n)
"Go to the desired node commencing from an existing TIME-STAMP in LIST.
If N is positive, then go forwards in time by that number of N time-stamps.
If N is negative, then backwards in time by that number of N time-stamps.
If node does not exist, return nil; otherwise, return node and corresponding time-stamp."
(let* ((full-list (apply #'append
(loop for node-stamps in list
collect (mapcar (lambda (stamp) (list (car node-stamps) stamp)) (cadr node-stamps)))))
(full-list (cl-sort full-list (lambda (node-stamp1 node-stamp2) (< (caadr node-stamp1) (caadr node-stamp2)))))
(current-pos (cl-position-if (lambda (node-stamp) (< (abs (- (caadr node-stamp) time-stamp)) goto-node-timestamp-tolerance)) full-list)))
(assert current-pos nil "Timestamp not found in list!")
(nth (max (min (+ current-pos n) (1- (length full-list))) 0) full-list)))
(setq l '(([node1] ((5.6) (3.7) (11.7) (8.2)))
([node2] ((4.4) (9.9) (6.1 . t)))
([node3] ((7.5) (2.3) (1.5)))
([node4] ((10.3)))))
(goto-node l 6.1 -1) ; => '([node3] (5.6))
(goto-node l 6.1 -4) ; => '([node3] (2.3))
(goto-node l 6.1 1) ; => '([node3] (7.5))
(goto-node l 6.1 4) ; => '([node4] (10.3))
| {
"pile_set_name": "StackExchange"
} |
Q:
What to do if a member of a team finishes all his sprint tasks ahead of schedule?
I run 1 week sprints, lately my sprints are finishing ahead of schedule (one day before the end of the sprint) for one member of the team.
I know that some PMs wait until the next sprint cycle, however that means losing a day doing no work.
What's the best way to deal with this?
A:
You have a few options at your disposal.
Use the available time to work on technical debts or fix bugs.
Ask the team member to share load another team member to help her/him in completing the sprint backlog because its a cross-functional team and its their shared responsibility / commitment to deliver sprint items as a team.
Pick the next highest priority item from the backlog after discussing with the Product Owner. Try to break the item down into a smaller or thinner slice which can actually be completed in the same sprint.
Sklivvz wrote the following in this answer:
you can add stories to a running sprint, if the team agrees to it. It's not a good practice though as it reduces the usefulness and predictive ability of the methodology
Same approach is also mentioned on this blog post:
I recommend you conduct a product grooming session which in this case acts as a cutdown sprint planning session for the small amount of new work that could possibly fit into the remaining time. If the new product backlog item(s) get completed before the end of the sprint their corresponding story points will count towards the velocity
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't kill celery workers
Try as I might I cannot kill these celery workers.
I run:
celery --app=my_app._celery:app status
I see I have 3 (I don't understand why 3 workers = 2 nodes, please explain if you know)
celery@ip-x-x-x-x: OK
celery@ip-x-x-x-x: OK
celery@named-worker.%ip-x-x-x-x: OK
2 nodes online.
I run (as root):
ps auxww | grep 'celery@ip-x-x-x-x' | awk '{print $2}' | xargs kill -9
The workers just keep reappearing with a new PID.
Please help me kill them.
A:
A process whose pid keeps changing is called comet. Even though pid of this process keeps on changing, its process group ID remains constant. So you can kill by sending a signal.
ps axjf | grep '[c]elery' | awk '{print $3}' | xargs kill -9
Alternatively, you can also kill with pkill
pkill -f celery
This kills all processes with fullname celery.
Reference: killing a process
A:
pkill -f celery
Run from the command line, this will kill at processes related to celery.
| {
"pile_set_name": "StackExchange"
} |
Q:
Change Letters in A String One at a Time (Pandas,Python3)
I have a list of words in Pandas (DF)
Words
Shirt
Blouse
Sweater
What I'm trying to do is swap out certain letters in those words with letters from my dictionary one letter at a time.
so for example:
mydict = {"e":"q,w",
"a":"z"}
would create a new list that first replaces all the "e" in a list one at a time, and then iterates through again replacing all the "a" one at a time:
Words
Shirt
Blouse
Sweater
Blousq
Blousw
Swqater
Swwater
Sweatqr
Sweatwr
Swezter
I've been looking around at solutions here: Mass string replace in python?
and have tried the following code but it changes all instances "e" instead of doing so one at a time -- any help?:
mydict = {"e":"q,w"}
s = DF
for k, v in mydict.items():
for j in v:
s['Words'] = s["Words"].str.replace(k, j)
DF["Words"] = s
this doesn't seem to work either:
s = DF.replace({"Words": {"e": "q","w"}})
A:
This answer is very similar to Brian's answer, but a little bit sanitized and the output has no duplicates:
words = ["Words", "Shirt", "Blouse", "Sweater"]
md = {"e": "q,w", "a": "z"}
md = {k: v.split(',') for k, v in md.items()}
newwords = []
for word in words:
newwords.append(word)
for c in md:
occ = word.count(c)
pos = 0
for _ in range(occ):
pos = word.find(c, pos)
for r in md[c]:
tmp = word[:pos] + r + word[pos+1:]
newwords.append(tmp)
pos += 1
Content of newwords:
['Words', 'Shirt', 'Blouse', 'Blousq', 'Blousw', 'Sweater', 'Swqater', 'Swwater', 'Sweatqr', 'Sweatwr', 'Swezter']
Prettyprint:
Words
Shirt
Blouse
Blousq
Blousw
Sweater
Swqater
Swwater
Sweatqr
Sweatwr
Swezter
Any errors are a result of the current time. ;)
Update (explanation)
tl;dr
The main idea is to find the occurences of the character in the word one after another. For each occurence we are then replacing it with the replacing-char (again one after another). The replaced word get's added to the output-list.
I will try to explain everything step by step:
words = ["Words", "Shirt", "Blouse", "Sweater"]
md = {"e": "q,w", "a": "z"}
Well. Your basic input. :)
md = {k: v.split(',') for k, v in md.items()}
A simpler way to deal with replacing-dictionary. md now looks like {"e": ["q", "w"], "a": ["z"]}. Now we don't have to handle "q,w" and "z" differently but the step for replacing is just the same and ignores the fact, that "a" only got one replace-char.
newwords = []
The new list to store the output in.
for word in words:
newwords.append(word)
We have to do those actions for each word (I assume, the reason is clear). We also append the world directly to our just created output-list (newwords).
for c in md:
c as short for character. So for each character we want to replace (all keys of md), we do the following stuff.
occ = word.count(c)
occ for occurrences (yeah. count would fit as well :P). word.count(c) returns the number of occurences of the character/string c in word. So "Sweater".count("o") => 0 and "Sweater".count("e") => 2.
We use this here to know, how often we have to take a look at word to get all those occurences of c.
pos = 0
Our startposition to look for c in word. Comes into use in the next loop.
for _ in range(occ):
For each occurence. As a continual number has no value for us here, we "discard" it by naming it _. At this point where c is in word. Yet.
pos = word.find(c, pos)
Oh. Look. We found c. :) word.find(c, pos) returns the index of the first occurence of c in word, starting at pos. At the beginning, this means from the start of the string => the first occurence of c. But with this call we already update pos. This plus the last line (pos += 1) moves our search-window for the next round to start just behind the previous occurence of c.
for r in md[c]:
Now you see, why we updated mc previously: we can easily iterate over it now (a md[c].split(',') on the old md would do the job as well). So we are doing the replacement now for each of the replacement-characters.
tmp = word[:pos] + r + word[pos+1:]
The actual replacement. We store it in tmp (for debug-reasons). word[:pos] gives us word up to the (current) occurence of c (exclusive c). r is the replacement. word[pos+1:] adds the remaining word (again without c).
newwords.append(tmp)
Our so created new word tmp now goes into our output-list (newwords).
pos += 1
The already mentioned adjustment of pos to "jump over c".
Additional question from OP: Is there an easy way to dictate how many letters in the string I want to replace [(meaning e.g. multiple at a time)]?
Surely. But I have currently only a vague idea on how to achieve this. I am going to look at it, when I got my sleep. ;)
words = ["Words", "Shirt", "Blouse", "Sweater", "multipleeee"]
md = {"e": "q,w", "a": "z"}
md = {k: v.split(',') for k, v in md.items()}
num = 2 # this is the number of replaces at a time.
newwords = []
for word in words:
newwords.append(word)
for char in md:
for r in md[char]:
pos = multiples = 0
current_word = word
while current_word.find(char, pos) != -1:
pos = current_word.find(char, pos)
current_word = current_word[:pos] + r + current_word[pos+1:]
pos += 1
multiples += 1
if multiples == num:
newwords.append(current_word)
multiples = 0
current_word = word
Content of newwords:
['Words', 'Shirt', 'Blouse', 'Sweater', 'Swqatqr', 'Swwatwr', 'multipleeee', 'multiplqqee', 'multipleeqq', 'multiplwwee', 'multipleeww']
Prettyprint:
Words
Shirt
Blouse
Sweater
Swqatqr
Swwatwr
multipleeee
multiplqqee
multipleeqq
multiplwwee
multipleeww
I added multipleeee to demonstrate, how the replacement works: For num = 2 it means the first two occurences are replaced, after them, the next two. So there is no intersection of the replaced parts. If you would want to have something like ['multiplqqee', 'multipleqqe', 'multipleeqq'], you would have to store the position of the "first" occurence of char. You can then restore pos to that position in the if multiples == num:-block.
If you got further questions, feel free to ask. :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to edit a node in-place in any javascript tree visualization toolkit (preferably InfoVis)?
I had earlier asked a question asking how/what to use to show to render data in a top-down tree like fashion.
I also stumbled up this post: Graph visualization library in JavaScript where the following toolkits were suggested for visualization:
arbor.js
Sophisticated graphing with nice physics and eyecandy.
Canviz
JS renderer for Graphviz graphs
Flare
Beautiful and powerful Flash based graph drawing
Graph JavaScript framework, version 0.0.1
Basic graph layout
Graphviz
Sophisticated graph visualization language
JavaScript Canvas Hyperbolic Tree
Small and flexible script
JavaScript InfoVis Toolkit
Jit, an interactive, multi-purpose graph drawing and layout framework
JS Graph It
Promising project using HTML5
jsPlumb
jQuery plug-in for creating interactive connected graphs
jssvggraph
Lightweight yet nice graph layouter
Moo Wheel
Interactive JS representation for connections and relations
NodeBox
Python Graph Visualization
Protovis
Graphical Toolkit for Visualization (JavaScript)
I decided to pick the InfoVis Toolkit's SpaceTree visualization. However, the issue that's been nagging me is no library seems to come with in-place editing of node text...or at least that's what I feel. Our requirement is that when a user clicks a node (or right-clicks and selects an option etc.,) the node text should be editable in place.
Most of the toolkits didn't allow it - they seem to be a read-only visualization/view of the underlying data (except for JS Graph It - however it doesn't have any layouting built in and that's important).
I don't mind changing my choice of toolkit and was wondering if anyone knew either how to edit the text of a node in-place in InfoVis or would recommend another toolkit for that?
Any ideas?
A:
Even though its late, I would answer your question for others having similar requirement.
In infoVis you can simply change the node.name to edit the text of node.
onRightClick: function( node, eventInfo, e){
node.name = "Changed the name in-place"
fd.plot(); // fd is an instance of ForceDirected visualization
}
Here I am changing node text in-place on right-click event, you can change that as per your need.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.